This repository has been archived by the owner on May 6, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sbhx-ircbot.py
585 lines (512 loc) · 19.7 KB
/
sbhx-ircbot.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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
import socket, urllib2, re, os
import urllib, httplib
import time
from datetime import datetime
USER = 'sbhx'
auto_connect = True
bot_default = USER + "_bot"
network_default = 'irc.freenode.net'
chan_default = '#sbhackerspace'
if not auto_connect:
botname = raw_input('Say my name! (' + bot_default + ') ')
if not botname:
botname = bot_default
network = raw_input('IRC network? (' + network_default + ') ')
if not network:
network = network_default
chatchannel = raw_input('Channel Name (' + chan_default + ') #')
if not chatchannel:
chatchannel = chan_default
else:
chatchannel = chan_default
network = network_default
botname = bot_default
# Detect platform
# Windows needs \r\n, Linux just needs \n
# if 'win' in os.uname()[0].lower():
# end = '\r\n'
# else:
end = '\n'
bad_on = False
badlist = """
Microsoft Windows iOS Apple Camarillo Ventura Russia China
Bieber Beiber Gentoo
""".split()
profanity_on = False
profanity = """
fuck shit bitch asshole cunt tits twat fag dick
""".split()
#scripting project projects PCBs
good_on = False
goodlist = """
Android Python Django Ruby Rails Clojure Bash Linux Emacs
Dropbox Wikileaks infosec DEFCON BSD hacking BackTrack
Slackware
""".split()
start_time = str(datetime.now())[:16]
irc = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
port = 6667
premess = 'PRIVMSG ' + chatchannel + ' :'
def new_connection(irc_obj):
irc_obj.connect( ( network, port ) )
print irc_obj.recv( 4096 )
irc_obj.send( 'NICK ' + botname + end )
irc_obj.send( 'USER ' + USER + 'bot botty bot bot: Python IRC' + end )
irc_obj.send( 'JOIN ' + chatchannel + end )
return irc_obj
# Used to store messages users leave for one another
left_messages = {}
left_priv_messages = {}
# Dictionaries of the form d == {'username1': 4, 'username2': 17}
utter_counts = {}
bot_response_counts = {}
a2morse = {'a': '.-', 'g': '--.', 'm': '--', 's': '...', 'y': '-.--',
'4': '....-', 'b': '-...', 'h': '....', 'n': '-.',
't': '-', 'z': '--..', '5': '.....', 'c': '-.-.',
'i': '..', 'o': '---', 'u': '..-', '0': '-----',
'6': '-....', 'd': '-..', 'j': '.---', 'p': '.--.',
'v': '...-', '1': '.----', '7': '--...', 'e': '.',
'k': '-.-', 'q': '--.-', 'w': '.--', '2': '..---',
'8': '---..', 'f': '..-.', 'l': '.-..', 'r': '.-.',
'x': '-..-', '3': '...--', '9': '----.'}
morse2a = {}
# DO NOT CONFUSE THIS WITH irc.msg
def irc_msg(msg):
"""Sends msg to channel"""
irc.send(premess + msg + end)
return
def priv_msg(user, msg):
"""Sends private msg to username"""
irc.send('PRIVMSG ' + user + ' :' + msg.strip('\r\n ') + end)
def getuser():
"""Returns nick of current message author"""
try:
#user = data.split()[2].strip(':')
#user = data.split()[0].split('~')[0].strip(':!')
user = data.split()[0].split('!')[0].strip(':')
except:
user = data.split('!')[0].strip(':')
return user
def timescrapes():
"""Sends current time in given city to IRC channel"""
html = urllib2.urlopen('http://www.timeanddate.com/worldclock/').read()
local = 'Los Angeles'
city = data.split(':!time')[1].strip('\r\n ')
print "city = " + city
if not city:
city = local
city = ' '.join([word.capitalize() for word in city.split()]) #cap words
print "city = " + city
time = html.split(city)[1].split('>')[3].split('<')[0]
irc_msg(time)
return
def timescrapes24():
"""Sends current time in given city to IRC channel"""
html = urllib2.urlopen('http://www.timeanddate.com/worldclock/').read()
local = 'Los Angeles'
city = data.split(':!time24')[1].strip('\r\n ')
if not city:
city = local
city = ' '.join([word.capitalize() for word in city.split()]) #cap words
time = html.split(city)[1].split('>')[3].split('<')[0]
if time.split()[2] == 'PM':
hours = int(time.split()[1].split(':')[0]) + 12
if hours == 24:
hours = 12;
minutes = time.split()[1].split(':')[1]
time = ' '.join([time.split()[0], str(hours) + ':' + str(minutes)])
else: # if 'AM'
hours = int(time.split()[1].split(':')[0])
if hours == 12:
hours = 0;
minutes = time.split()[1].split(':')[1]
time = ' '.join([time.split()[0], str(hours) + ':' + str(minutes)])
#time = ' '.join(time.split()[:2])
irc_msg(time)
#str(datetime.now())[:16].split()[1]
return
loadfile = "projectlinks.txt"
i = 0
def read():
"""Reads local db"""
dbfile = open(loadfile, 'r')
dbold = dbfile.read()
dbfile.seek(0)
for line in dbfile:
irc_msg(line)
dbfile.seek (0)
dbfile.close()
def empty():
"""Empties local db"""
dbfile = open(loadfile, 'w')
dbfile.close()
def writea():
"""Write given project info to local db"""
dbfile = open(loadfile, 'r')
dbold = dbfile.read()
dbfile.close()
link = get_content('project add')
link = username + str(link)
dbfile = open(loadfile, 'w')
dbfile.write(link + str(dbold))
dbfile.close()
def inc_bot_response_counts():
try: ### Slide right one space
bot_response_counts[username] += 1
print "Bot responses to", username, " ==", bot_response_counts[username]
except:
try:
bot_response_counts[username] = 1
except:
print "inc_bot_response_counts is REALLY broken"
def inc_utter_counts():
try:
utter_counts[username] += 1
print "Utter count of", username, " ==", bot_response_counts[username]
except:
try:
utter_counts[username] = 1
except:
print "inc_utter_counts is REALLY broken"
def get_content(keyword):
return data.split(':!' + keyword + ' ')[1].strip('\r\n ')
def remove_tags(html):
tags = re.findall(r"(<.*?>)", html, re.DOTALL)
for tag in tags:
print tag
html = html.replace(tag, '')#.replace('<', '').replace('>', '')
return html
while True:
try:
data = irc.recv ( 4096 )
except:
time.sleep(15)
irc = new_connection(irc)
continue
datasp = data.split(' :')[0]
datasp = str(datasp)
username = getuser()
# inc_utter_counts()
if 'PING' in data:
irc.send( 'PONG ' + data.split()[1] + end )
if ':!quit' in data.lower() or ':!stats' in data.lower() or \
':!kick' in data.lower():
message = username + " has been terminated."
irc.send( 'KICK ' + chan_default + ' ' + username + " :" + message + end )
if ':!time' in data:
if ':!time24' in data:
try:
timescrapes24()
except:
irc_msg("Error try: !time <city> ex. !time Berlin")
else:
try:
timescrapes()
except:
irc_msg("Error try: !time <city> ex. !time Berlin")
if ':!project' in data:
if ':!project read' in data:
try: read()
except: irc_msg("Could not read")
if ':!project empty' in data:
empty()
if ':!project add' in data:
writea()
if 'KICK' in data:
irc.send( 'JOIN ' + chatchannel + end )
# Return URLs to Google search queries
if ':!google ' in data:
query = get_content('google').replace(' ','+')
search = "http://www.google.com/search?q=" + query
irc_msg(search)
if ':!g ' in data:
query = get_content('g').replace(' ','+')
search = "http://www.google.com/search?q=" + query
irc_msg(search)
if ':!lucky ' in data:
try:
query = get_content('lucky').replace(' ','+')
except:
irc_msg("!lucky <search_term>")
search = "http://www.google.com/search" + \
"?btnI=I'm+Feeling+Lucky&q=" + query
irc_msg(search)
if ':!wikilink ' in data:
url = get_content('wikilink')
html = urllib2.urlopen(
'http://sbhackerspace.com/wiki/index.php' +
'?title=Links&action=edit').read()
textarea = re.findall(r'<textarea.*>(.*)</textarea>',
html, re.DOTALL)[0]
appended_data = end + '* ' + url
new_textarea = textarea + appended_data
print new_textarea
print data
# Save messages to a dictionary of the form
# dict['recipient'] = ['message 1', 'message 2', 'message 3']
if ':!msg ' in data:
try:
# recips can be a single nick or a comma-delimited list of nicks
recips, msg = get_content('msg').split(' ', 1)
except:
#irc_msg("Notice: " + username + " can't get anything right.")
irc_msg("Options: !time <city>, !msg <recipient> <message>, " +
"!privmsg <recipient> <message>")
date, now = str(datetime.now())[:16].split()
try:
msg += " (from " + username + " at " + now + " on " + date + ")"
except:
msg = username + ' tried to crash the bot. Bastard.'
fails = []
for recip in recips.split(','):
try:
left_messages[recip].append(msg)
except KeyError:
left_messages[recip] = []
left_messages[recip].append(msg)
except:
fails.append(recip)
#irc_msg(username + ' is trying to kill me!')
if len(fails) > 0:
if len(fails) == len(recips):
irc_msg("User error. Replace current user and reboot.")
else:
irc_msg("Okay, %s. Skipped %s." % (username, ', '.join(fails)))
else:
irc_msg("Okay, %s." % username)
del fails
if ':!privmsg ' in data:
try:
recip, msg = get_content('privmsg').split(' ', 1)
except:
irc_msg("Options: !time <city>, !msg <recipient> <message>, " +
"!privmsg <recipient> <message>")
msg = ""
date, now = str(datetime.now())[:16].split() # Ghetto, but works
msg += " (from " + username + " at " + now + " on " + date + ")"
# print "recip ==", recip
# print
# print "msg ==", msg
# print
try:
left_priv_messages[recip].append(msg)
except KeyError:
left_priv_messages[recip] = []
left_priv_messages[recip].append(msg)
except:
irc_msg(username + 'fucked up my code. Bastard.')
else:
irc_msg('Okay, %s.' % username)
# Send messages to user but only if they say something in
# the channel, not because they've joined, quit, etc
if username in left_messages and 'ACTION' not in data \
and 'QUIT' not in data and 'JOIN' not in data \
and 'KICK' not in data:
msg_count = len(left_messages[username])
irc_msg(username + ' has ' + str(msg_count) + ' message(s)! ')
for m in range(msg_count):
irc_msg(left_messages[username][m])
del left_messages[username]
if username in left_priv_messages:
msg_count = len(left_priv_messages[username])
irc.send('PRIVMSG ' + username + ' :You have ' +
str(msg_count) + ' private message(s):' + end)
for m in range(msg_count):
irc.send('PRIVMSG ' + username + ' : ' +
left_priv_messages[username][m] + end)
del left_priv_messages[username]
if not username.lower().endswith('bot'):
if profanity_on:
for word in profanity:
if word.lower() in data.lower() and \
'motherfucker' not in data.lower():
irc_msg('Hey ' + username +
': watch your mouth, motherfucker')
inc_bot_response_counts()
break
if bad_on:
for word in badlist:
if word.lower() in data.lower() and \
'radioshack' not in data.lower() and \
'fios' not in data.lower():
irc_msg('Notice: ' + username +
' is a dipshit for mentioning ' + word)
inc_bot_response_counts()
break
if good_on:
for word in goodlist:
if word.lower() in data.lower():
irc_msg('Notice: ' + username +
' is redeemed for mentioning ' + word)
inc_bot_response_counts()
break
if ':!wiki ' in data:
page = get_content('wiki')
url = "http://sbhackerspace.com/wiki/index.php?title="
irc_msg(url + page)
inc_bot_response_counts()
if ':!help' in data:
irc_msg("Options: !time <city>, !msg <recipient> <message>, " +
"!privmsg <recipient> <message>")
inc_bot_response_counts()
# if username == 'paul_be' or username == 'm0tan':
# irc_msg('Hey ' + username + ', am I annoying yet?')
# if username == 'elimisteve':
# irc_msg('STFU ' + username + '!')
if ':!members' in data:
member_list = []
#url = data.split(':!members')[1]
html = urllib2.urlopen(
'http://sbhackerspace.com/wiki/index.php' +
'?title=Members&action=edit').read()
textarea = re.findall(r'<textarea.*>(.*)</textarea>',
html, re.DOTALL)[0]
for line in textarea.split('\n'):
member_list.append(line.split(',')[0].split()[-1].replace(']', ''))
irc_msg('Current Members (from wiki): ' + ', '.join(member_list))
inc_bot_response_counts()
# if ':!stats' in data:
# priv_msg(username, "Since " + start_time)
# priv_msg(username, "----------------------")
# priv_msg(username, "Total Speakers: %d" % len(utter_counts))
# total_utter = sum([utter_counts[nick] for nick in utter_counts])
# priv_msg(username, "Total Utterances: %d" % total_utter)
# total_bot_utter = sum([bot_response_counts[nick]
# for nick in bot_response_counts])
# priv_msg(username, "Total Bot Responses: %d" % total_bot_utter)
# nick_width = max([len(nick) for nick in utter_counts])
# priv_msg(username, "") # Blank line
# priv_msg(username, "Nick%sMsg Count" % (' ' * nick_width))
# priv_msg(username, "%s" % ('-' * (nick_width+13)))
# for nick in utter_counts:
# priv_msg(username, nick + ' ' + str(utter_counts[nick]))
# inc_bot_response_counts()
if ":!userlist" in data:
irc_msg("/userlist")
if ':!ircbot ' in data:# and data.split(':!ircbot')[1] == '':
try:
url = get_content('ircbot')
html = urllib2.urlopen('http://stevendphillips.com/ircbot/@edit/index').read()
textarea = re.findall(
r'<textarea.*>(.*)</textarea>', html, re.DOTALL)[0].strip('\r\n ')
print textarea
print '\n\n\n\n'
appended_data = '\n' + '* ' + url
new_textarea = textarea + appended_data
# HTTP POST
params = urllib.urlencode({'text': new_textarea})
headers = {"content-type": "text/html"}
conn = httplib.HTTPConnection('stevendphillips.com' + ":80")
conn.request("POST", "/ircbot/", params, headers)
response = conn.getresponse()
print response.status, response.reason
data = response.read()
print data
conn.close()
# Show user what the wiki page now looks like
for line in [line.strip() for line in new_textarea.split('\n')]:
priv_msg(username, line)
priv_msg(username, "") # Blank line
priv_msg(username, 'New Feature List: http://stevendphillips.com/ircbot')
except:
priv_msg(username, "Nice try :-)")
# if ':!ircbot' in data and ':!ircbot ' not in data:
# html = urllib2.urlopen('http://stevendphillips.com' +
# '/ircbot/@edit/index').read()
# textarea = re.findall(
# r'<textarea.*>(.*)</textarea>', html, re.DOTALL)[0].strip('\r\n ')
# for line in [line.strip() for line in textarea.split('\n')]:
# priv_msg(username, line)
if ':!echo ' in data:
msg = get_content('echo')
irc_msg(msg)
if ':!badlist ' in data:
cmd = get_content('badlist')
if cmd.lower() == 'off': bad_on = False
elif cmd.lower() == 'on': bad_on = True
else: irc_msg("!badlist on|off")
if ':!goodlist ' in data:
cmd = get_content('goodlist')
if cmd.lower() == 'off': good_on = False
elif cmd.lower() == 'on': good_on = True
else: irc_msg("!goodlist on|off")
if ':!profanity ' in data:
cmd = get_content('profanity')
if cmd.lower() == 'off':
profanity_on = False
bad_on = False
elif cmd.lower() == 'on':
profanity_on = True
bad_on = True
else: irc_msg("!profanity on|off")
if ':!shutup' in data or ':!lists off' in data:
bad_on = False
good_on = False
profanity_on = False
irc_msg("All lists disabled")
if ':!fuckyou' in data or ':!lists on' in data:
bad_on = True
good_on = True
profanity_on = True
irc_msg("Careful, " + username + "...")
if ':!define' in data and ':!define ' not in data:
irc_msg("!define searchterm")
if ':!define ' in data:
query = get_content('define').replace(' ', '+')
url = "http://www.google.com/search?q=define:"
request = urllib2.Request(url + query)
request.add_header('User-agent', 'Mozilla 3.10')
html = urllib2.urlopen(request).read()
try:
definition = re.findall(r'<div class=s><div>(.*?)</div>',
html, re.DOTALL)[0]
if type(definition) is tuple:
definition = definition[0]
definition = definition.replace('"', '"')
definition = remove_tags(definition)
if ' ' in definition:
ndx = definition.index(' ')
definition = definition[:ndx]
irc_msg(query.replace('+', ' ') + ': ' + str(definition))
except:
irc_msg("!define searchterm")
continue
if ':!urbandef' in data and ':!urbandef ' not in data:
irc_msg("!urbandef searchterm")
if ':!urbandef ' in data:
query = get_content('urbandef').replace(' ', '+')
url = "http://www.urbandictionary.com/define.php?term="
request = urllib2.Request(url + query)
request.add_header('User-agent', 'Mozilla 3.10')
html = urllib2.urlopen(request).read()
try:
definition = re.findall(r'<div class="definition">(.*?)</div>',
html, re.DOTALL)[0]
if type(definition) is tuple:
definition = definition[0]
definition = definition.replace('"', '"').replace('\r', ' ')
definition = remove_tags(definition)
irc_msg(query.replace('+', ' ') + ': ' + str(definition))
except:
irc_msg("!urbandef searchterm")
if ':!whoami' in data.lower() or ':!saymyname' in data.lower():
irc_msg(username)
if ':!morse ' in data.lower():
ndx = data.lower().index(':!morse')
irc_msg(' '.join([a2morse[x] if x in a2morse else x for x in data.lower().replace(':!morse ', '')[ndx:]]))
if ':!convert ' in data.lower():
query = get_content('convert').replace(' ', '+')
url = "http://www.google.com/search?q=convert+"
request = urllib2.Request(url + query)
request.add_header('User-agent', 'Mozilla 3.10')
html = urllib2.urlopen(request).read()
try:
definition = re.findall(r'<h2 class=r .*?><b>(.*?)</b>',
html, re.DOTALL)[0]
if type(definition) is tuple:
definition = definition[0]
definition = definition.replace('"', '"')
definition = remove_tags(definition)
irc_msg(definition)
except:
irc_msg("!convert [what you want converted]")