-
Notifications
You must be signed in to change notification settings - Fork 13
/
foosbot.py
executable file
·104 lines (81 loc) · 2.54 KB
/
foosbot.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
#!/usr/bin/env python
import slacker
# import json
import websocket
import slackparser
import json
import traceback
import time
import sys
import yaml
import datetime
config = yaml.load(open('config.yaml'))
slack = slacker.Slacker(config['slacktoken'])
def getniceuser(users, n):
uc = filter(lambda x: x['name'] == n, users)
if len(uc) != 1:
print "Unable to find user %s in slack, please check your config" % (config['adminuser'])
sys.exit(1)
else:
print "User %s found with id %s" % (n, uc[0]['id'])
return uc[0]['id']
def mangleconfig(config):
# Sort out friendly names in config
chans = slack.channels.list().body['channels']
cc = filter(lambda x: x['name'] == config['fooschan'], chans)
if len(cc) != 1:
print "Unable to find channel %s in slack, please check your config" % (config['fooschan'])
sys.exit(1)
else:
print "Channel %s found with id %s" % (config['fooschan'], cc[0]['id'])
config['fooschan'] = cc[0]['id']
users = slack.users.list().body['members']
config['adminuser'] = getniceuser(users, config['adminuser'])
config['botuser'] = getniceuser(users, config['botuser'])
def onrecv(ws, message):
# print message
sendback = slackparser.processMessage(slack, config, message)
# print sendback
for s in sendback:
s['channel'] = config['fooschan']
# print ss
try:
# print "SENDING", json.dumps(s)
ws.send(json.dumps(s) + '\n')
time.sleep(1)
except Exception as e:
print "ERROR SENDING"
print str(e)
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_tb(exc_traceback)
def onerr(ws, err):
print "ERROR: ", err
def onclose(ws):
print "Socket closed"
def run_bot():
rtminfo = slack.rtm.start()
wsurl = rtminfo.body['url']
print "Attempting to connect to %s" % (wsurl)
ws = websocket.WebSocketApp(wsurl, on_message=onrecv,
on_error=onerr, on_close=onclose)
ws.run_forever()
mangleconfig(config)
failcount = 0
lastfail = datetime.datetime.now()
while True:
print "Connecting"
run_bot()
print "Connection lost..."
now = datetime.datetime.now()
timeran = now - lastfail
lastfail = now
if timeran.total_seconds() < 3600:
failcount += 1
else:
failcount = 0
if failcount > 10:
print "Too many failures, exiting"
break
else:
print "Will reconnect in 60 seconds"
time.sleep(60)