forked from KpaBap/genmaybot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
genmaybot.py
360 lines (294 loc) · 12.4 KB
/
genmaybot.py
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
#! /usr/bin/env python
#
#To run this bot use the following command:
#
# python genmaybot.py irc.0id.net "#chan" Nickname
#
### look in to !seen functionality
# |- on_join, on_part, on_kick, on_nick, on_quit
# |---use on_whoreply to confirm the users are who their nick is?
# |---check who is in the channel when the bot joins?
# | db: users_table: user UNQ | cur-nick | cur-inchannel BOOL | last action | last-timestamp | <user_aliases> | <user_knownhostmasks>
# | db: user_aliases: user | alternick (allow wildcards in alternick)
# | db: user_knownhostmasks: user | hostmask
# (hostmask might be username | hostmask where username@hostmask
#
### random descision maker?
# test comment please ignore
from ircbot import SingleServerIRCBot
import time, imp
import sys, os, socket, configparser, threading, traceback
socket.setdefaulttimeout(5)
class TestBot(SingleServerIRCBot):
def __init__(self, channel, nickname, server, port=6667):
SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname, 30)
self.channel = channel
self.doingcommand = False
self.botnick = nickname
self.commandaccesslist = {}
self.commandcooldownlast = {}
self.spam = {}
self.load_config()
print(self.loadmodules())
def load_config(self):
config = configparser.ConfigParser()
try:
cfgfile = open('genmaybot.cfg')
except IOError:
print("You need to create a .cfg file using the example")
sys.exit(1)
config.readfp(cfgfile)
self.botconfig = config
self.botadmins = config["irc"]["botadmins"].split(",")
self.error_log = simpleLogger(config['misc']['error_log'])
self.event_log = simpleLogger(config['misc']['event_log'])
sys.stdout = self.event_log
sys.stderr = self.error_log
def on_nicknameinuse(self, c, e):
c.nick(c.get_nickname() + "_")
def on_kick(self, c, e):
#attempt to rejoin any channel we're kicked from
if e.arguments()[0][0:6] == c.get_nickname():
c.join(e.target())
def on_disconnect(self, c, e):
print("DISCONNECT: " + str(e.arguments()))
def on_welcome(self, c, e):
c.privmsg("NickServ", "identify " + self.botconfig['irc']['identpassword'])
c.join(self.channel)
self.alerts(c)
self.irccontext = c
def on_pubmsg(self, c, e):
self.process_line(c, e)
def on_privmsg(self, c, e):
from_nick = e.source().split("!")[0]
line = e.arguments()[0].strip()
command = line.split(" ")[0]
if command in self.admincommands and self.isbotadmin(from_nick):
self.admincommand = line
c.who(from_nick)
self.process_line(c, e, True)
def on_whoreply(self, c, e):
nick = e.arguments()[4]
line = self.admincommand
command = line.split(" ")[0]
self.admincommand = ""
try:
if e.arguments()[5].find("r") != -1 and line != "":
say = self.admincommands[command](line, nick, self, c)
say = say.split("\n")
for line in say:
c.privmsg(nick, line)
except Exception as inst:
print("admin exception: " + line + " : " + str(inst))
def process_line(self, c, ircevent, private = False):
if self.doingcommand:
return
self.doingcommand = True
line = ircevent.arguments()[0]
from_nick = ircevent.source().split("!")[0]
hostmask = ircevent.source()[ircevent.source().find("!")+1:]
command = line.split(" ")[0].lower()
args = line[len(command)+1:].strip()
if private:
linesource = from_nick
else:
linesource = ircevent.target()
e = None
etmp = []
try:
#commands names are defined by the module as function.command = "!commandname"
if command in self.bangcommands and (self.commandaccess(command) or from_nick in self.botadmins):
e = self.botEvent(linesource, from_nick, hostmask, args)
e.botnick = self.botnick #store the bot's nick in the event in case we need it.
if linesource in self.channels and hasattr(self.bangcommands[command], 'privateonly'):
self.doingcommand = False
return
etmp.append(self.bangcommands[command](self, e))
else:
#lineparsers take the whole line and nick for EVERY line
#ensure the lineparser function is short and simple. Try to not to add too many of them
#Multiple lineparsers can output data, leading to multiple 'say' lines
for command in self.lineparsers:
e = self.botEvent(linesource, from_nick, hostmask, line)
e.botnick = self.botnick #store the bot's nick in the event in case we need it.
if linesource in self.channels and hasattr(command, 'privateonly'):
continue
etmp.append(command(self, e))
firstpass = True
for e in etmp:
if e and e.output:
if firstpass and not e.source == e.nick and not e.nick in self.botadmins:
if self.isspam(e.hostmask, e.nick): break
firstpass = False
self.botSay(e)
except Exception as inst:
traceback.print_exc()
print(line + " : " + str(inst))
pass
self.doingcommand = False
return
def botSay(self, botevent):
try:
if botevent.output:
for line in botevent.output.split("\n"):
line = line.replace("join", "join")
line = line.replace("come", "come")
if botevent.notice:
self.irccontext.notice(botevent.source, line)
else:
self.irccontext.privmsg(botevent.source, line)
except Exception as inst:
print("bot failed trying to say " + str(botevent.output) + "\n" + str(inst))
traceback.print_exc()
def loadmodules(self):
self.tools = vars(imp.load_source("tools", "./botmodules/tools.py"))
filenames = []
for fn in os.listdir('./botmodules'):
if fn.endswith('.py') and not fn.startswith('_'):
filenames.append(os.path.join('./botmodules', fn))
self.bangcommands = {}
self.admincommands = {}
self.botalerts = []
self.lineparsers = []
for filename in filenames:
name = os.path.basename(filename)[:-3]
try:
module = imp.load_source(name, filename)
except Exception as inst:
print("Error loading module " + name + " : " + str(inst))
else:
try:
vars(module)['__init__'](self)
except:
pass
for name, func in vars(module).items():
if hasattr(func, 'command'):
command = str(func.command)
self.bangcommands[command] = func
elif hasattr(func, 'admincommand'):
command = str(func.admincommand)
self.admincommands[command] = func
elif hasattr(func, 'alert'):
self.botalerts.append(func)
elif hasattr(func, 'lineparser'):
self.lineparsers.append(func)
commands, botalerts, lineparsers, admincommands = "", "", "", ""
if self.bangcommands:
commands = 'Loaded command modules: %s' % list(self.bangcommands.keys())
else:
commands = "No command modules loaded!"
if self.botalerts:
botalerts = 'Loaded alerts: %s' % ', '.join((command.__name__ for command in self.botalerts))
if self.lineparsers:
lineparsers = 'Loaded line parsers: %s' % ', '.join((command.__name__ for command in self.lineparsers))
if self.admincommands:
admincommands = 'Loaded admin commands: %s' % list(self.admincommands.keys())
return commands + "\n" + botalerts + "\n" + lineparsers + "\n" + admincommands
def isbotadmin(self, nick):
return nick in self.botadmins
def commandaccess(self, command):
if "all" in self.commandaccesslist:
command = "all"
if command in self.commandaccesslist:
if type(self.commandaccesslist[command]) == int:
if time.time() - self.commandcooldownlast[command] < self.commandaccesslist[command]:
return False
else:
self.commandcooldownlast[command] = time.time()
return True
elif self.commandaccesslist[command] == "Disabled":
return False
else: #if there's no entry it's assumed to be enabled
return True
def isspam(self, user, nick):
if not (user in self.spam):
self.spam[user] = {}
self.spam[user]['count'] = 0
self.spam[user]['last'] = 0
self.spam[user]['first'] = 0
self.spam[user]['limit'] = 15
self.spam[user]['count'] += 1
self.spam[user]['last'] = time.time()
if self.spam[user]['count'] == 1:
self.spam[user]['first'] = time.time()
if self.spam[user]['count'] > 1:
self.spam[user]['limit'] = (self.spam[user]['count'] - 1) * 15
if not ((self.spam[user]['last'] - self.spam[user]['first']) > self.spam[user]['limit']):
bantime = self.spam[user]['limit'] + 15
print("%s : %s band %s seconds" % (time.strftime("%d %b %Y %H:%M:%S", time.localtime()), nick, bantime))
return True
else:
self.spam[user]['first'] = 0
self.spam[user]['count'] = 0
self.spam[user]['limit'] = 15
return False
def alerts(self, context):
try:
for command in self.botalerts:
say = command()
if say:
for channel in self.channels:
context.privmsg(channel, say)
except Exception as inst:
print("alerts: " + str(inst))
pass
self.t = threading.Timer(60, self.alerts, [context])
self.t.start()
class botEvent:
def __init__(self, source, nick, hostmask, inpt, output="", notice=False):
self.source = source
self.nick = nick
self.input = inpt
self.output = output
self.notice = notice
self.hostmask = hostmask
def main():
#print sys.argv
if len(sys.argv) != 4:
config = configparser.ConfigParser()
try:
cfgfile = open('genmaybot.cfg')
except IOError:
print("You need to create a .cfg file using the example")
sys.exit(1)
config.readfp(cfgfile)
if config['irc']['nick'] and config['irc']['server'] and config['irc']['channels']:
nickname = config['irc']['nick']
server, port = config['irc']['server'].split(":", 1)
try:
port = int(port)
except:
port = 6667
channel = config['irc']['channels']
else:
print("Usage: bot.py <server[:port]> <channel> <nickname> \nAlternatively configure the server in the .cfg")
sys.exit(1)
else:
s = sys.argv[1].split(":", 1)
server = s[0]
if len(s) == 2:
try:
port = int(s[1])
except ValueError:
print("Error: Erroneous port.")
sys.exit(1)
else:
port = 6667
channel = sys.argv[2]
nickname = sys.argv[3]
bot = TestBot(channel, nickname, server, port)
bot.start()
#this bullshit is necessary because sys.stdout doesn't write the file continuously
class simpleLogger():
def __init__(self,logfile):
self.logfile = logfile
open(logfile,"w").write("") ##clear out any previous contents
def write(self,logtext):
logfile = open(self.logfile,"a")
logfile.write(logtext)
logfile.close()
return 0
def flush(self):
return 0
if __name__ == "__main__":
main()