This repository has been archived by the owner on Apr 26, 2023. It is now read-only.
forked from kiedtl/ircbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot
executable file
·204 lines (157 loc) · 6.26 KB
/
bot
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
#!/usr/bin/env python3
import datetime
import os
import time
import traceback
import pydle
import botsecrets
import config
import fmt
import handlers
# cache output, module name on a per-channel basis
# this is for self.msg and self.more
output_buf = {}
last_modname = {}
class SIGSEGV(pydle.Client):
def __init__(self, *args, **kwargs):
self.fndata = {}
self.modules = {}
self.help = {}
self.userinfo = {}
self.aliases = {}
# handle commands, raw PRIVMSGs,
# and messages that match a regex,
# respectively.
self.handle_cmd = {}
self.handle_raw = {}
self.handle_reg = {}
# HACK: avoid executing commands from
# channel history playback
self.ignore_cmd = 0
self.prefix = config.prefix
self.asleep = {}
super().__init__(*args, **kwargs)
async def on_connect(self):
await super().on_connect()
self.log('irc', 'connected!')
self.log('modules', 'loading modules...')
await self.load_mods()
self.log('irc', 'joining channels')
for i in config.initial_chans:
await self.join(i)
self.log('irc', 'done!')
if config.set_botmode:
self.log('irc', 'attempting to set mode +B')
await self.set_mode(self.nickname, '+B')
async def load_mods(self):
for i in [s for s in os.listdir('mod') if '.py' in s]:
i = i[:-3]
self.log('modules', f'loading {i}')
module = __import__('mod.' + i)
module = eval('module.' + i)
await module.init(self)
self.modules[i] = module
async def on_join(self, chan, by):
await super().on_join(chan, by)
if by == self.nickname:
self.ignore_cmd = time.time() + 3
async def on_invite(self, chan, by):
await super().on_invite(chan, by)
self.log('irc', 'received invite by {} to {}'.format(by, chan))
if config.join_on_invite:
if chan not in config.bannedchans:
await self.join(chan)
async def on_channel_message(self, chan, source, msg):
await super().on_channel_message(chan, source, msg)
# ignore channel playback on channels that have
# mode +H (only on ircv3 servers)
if not time.time() > self.ignore_cmd:
return
for i in self.handle_raw:
await self.handle_raw[i](self, chan, source, msg)
if source == self.nickname:
return
if not chan in self.asleep:
self.asleep[chan] = time.time()
for i in self.handle_reg:
# (<regex>, <function>)
if not self.handle_reg[i][0].match(msg):
continue
await self.handle_reg[i][1](self, chan, source, msg)
if msg[:len(self.prefix)] == self.prefix:
msg = msg[len(self.prefix):]
elif msg[:len(f"{self.nickname}: ")] == f"{self.nickname}: ":
msg = msg[len(f"{self.nickname}: "):]
else:
return
cmd = msg.split(' ')[0]
msg = msg[len(cmd) + 1:]
# check if the command might be an alias
matches = {k for k, v in self.aliases.items() if cmd in v}
if len(matches) > 0 and cmd not in self.handle_cmd:
cmd = list(matches)[0]
if cmd in self.handle_cmd:
self.log('irc', 'recieved command "{} {}" from "{}" in "{}"'
.format(cmd, msg, source, chan))
func = self.handle_cmd[cmd]
is_admin = await self.is_admin(source)
if self.asleep[chan] < time.time() or is_admin:
try:
await handlers.execute(self, func, chan, source, msg)
except Exception as err:
if func in self.fndata:
module = self.fndata[func]['module']
else:
module = 'oops'
await self.msg(module, chan,
['segmentation fault', repr(err)])
self.log(module, f"EXCEPTION: {repr(err)}")
traceback.print_tb(err.__traceback__)
return
async def on_private_message(self, chan, source, msg):
await super().on_private_message(chan, source, msg)
await self.on_channel_message(source, source, msg)
async def on_user_mode_change(self, modes):
await super().on_user_mode_change(modes)
self.log('irc', 'mode changed: {}'.format(modes))
# ---- utility functions ----
async def msg(self, mod, chan, msg: list):
# TODO: throttling (if the messages are too big)
if chan in output_buf:
del output_buf[chan]
output_buf[chan] = msg[:] # copy list
last_modname[chan] = mod
msg_fmted = "{}"
if len(last_modname[chan]) > 1:
msg_fmted = fmt.modname(last_modname[chan]) + " " + msg_fmted
if len(output_buf[chan]) > 1:
msg_fmted = msg_fmted + " (more)"
await self.message(chan, msg_fmted.format(output_buf[chan].pop(0)))
async def more(self, chan):
if len(output_buf[chan]) == 0:
await self.message(
chan, "{} no more text to show".format(fmt.modname("more"))
)
return
msg_fmted = "{}"
if len(last_modname[chan]) > 1:
msg_fmted = fmt.modname(last_modname[chan]) + " " + msg_fmted
if len(output_buf[chan]) > 1:
msg_fmted = msg_fmted + " (more)"
await self.message(chan, msg_fmted.format(output_buf[chan].pop(0)))
async def is_admin(self, nickname):
info = await self.whois(nickname)
# check if they are identified
if not 'account' in info:
return False
return info['account'] in config.admins
@staticmethod
def log(mod, txt):
now = datetime.datetime.now()
timestamp = datetime.datetime.strftime(now, '%Y-%M-%dT%H:%m:%SZ')
print(f'{timestamp}: [{mod}]: {txt}')
if __name__ == '__main__':
client = SIGSEGV(config.nickname, realname=config.realname,
sasl_username=config.username, sasl_password=botsecrets.sasl_password,
sasl_identity=config.username)
client.run(config.server, tls=config.tls, tls_verify=config.tls_verify)