-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpubbot.py
More file actions
executable file
·64 lines (55 loc) · 2.48 KB
/
pubbot.py
File metadata and controls
executable file
·64 lines (55 loc) · 2.48 KB
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
import time
from slackclient import SlackClient
import config
from utils import get_users
from loggers import blog
from trigger_node import trigger_node_factory
class Bot(object):
def __init__(self):
self.slack_client = SlackClient(config.bot_user_oauth_token)
self.bot_name = config.bot_name
self.bot_id = self.get_bot_id()
self.handlers = {}
if self.bot_id is None:
blog.error("Could not find bot: exiting")
exit("Error, could not find " + self.bot_name)
self.listen()
def get_bot_id(self):
api_call = self.slack_client.api_call("users.list")
if api_call.get('ok'):
# retrieve all users so we can find our bot
users = get_users(self.slack_client)
for user in users:
if 'name' in user and user.get('name') == self.bot_name:
return user.get('id')
raise ValueError('The token does not match self.bot_name')
def listen(self):
if self.slack_client.rtm_connect(with_team_state=False):
blog.info("Successfully connected, listening for commands")
while True:
events = self.slack_client.rtm_read()
if events and len(events) > 0:
self.handle_events(events)
time.sleep(1)
else:
blog.error("Connection failed: exiting")
exit("Error, Connection Failed")
def handle_events(self, events):
for event in events:
# TODO: not from any bot
if 'text' in event and 'user' in event and event['user']!=self.bot_id:
if 'channel' in event and event['channel']:
channel = event['channel']
blog.debug(f"Received: {event['text']}")
if channel in self.handlers.keys() and self.handlers[channel]:
self.handlers[channel] = \
self.handlers[channel].handle_message(event['user'],
event['text'])
else:
blog.info("Using default handler.")
self.handlers[channel] = trigger_node_factory(self, channel)
self.handlers[channel] = \
self.handlers[channel].handle_message(event['user'],
event['text'])
if __name__ == "__main__":
Bot()