-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathixchel.py
134 lines (112 loc) · 4.09 KB
/
ixchel.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
"""
The Ixchel module is the primary interface with users on Slack.
It monitors the Slack channel for user input and passes commands to the
IxchelCommand module. Ixchel also monitors (and resets) connections to Slack and
the telescope host machine (aster) via ssh..
"""
from datetime import datetime
import os
import logging
import time
import datetime
import json
import re
import slack
import asyncio
import signal
import threading
from globals import doAbort
from ixchel_command import IxchelCommand
from slack_client import Slack
from config import Config
from telescope import Telescope
# logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(name)s - %(funcName)s - %(message)s',
handlers=[
logging.FileHandler("ixchel.log"),
logging.StreamHandler()
])
logger = logging.getLogger('ixchel')
# config
cfg_file_path = './cfg/ixchel.cfg'
class Ixchel:
def __init__(self, config):
self.logger = logging.getLogger('Ixchel')
# init config
self.config = config
# init loc
self.lock = threading.Lock()
# init Slack interface
self.slack = Slack(self)
# the telescope
self.telescope = Telescope(self)
# init IxchelCommand
self.ixchel_commands = IxchelCommand(self)
# update settings
self.bot_name = self.config.get('slack', 'bot_name')
self.channel = self.config.get('slack', 'channel_name')
self.channel_id = self.config.get('slack', 'channel_id')
async def parse_message(self, **payload):
message = payload['data']
# if 'username' in message:
# self.logger.debug(message['username'])
# if 'user' in message:
# self.logger.debug(message['user'])
# ignore any messages sent from this bot
if 'username' in message and message['username'] == self.bot_name:
return
# only process commands from the self.channel
if 'channel' in message:
# message posted in ixchel channel?
if message['channel'] == self.channel_id:
# self.slack.send_typing()
self.process(message)
else: # message posted directly to bot
self.logger.warning('Received direct message.')
self.slack.send_message('Please use the channel #%s for communications with %s.' % (
self.channel, self.bot_name), None, message['channel'], self.bot_name)
def process(self, message):
if not 'text' in message:
self.logger.error('Invalid message received.')
return False
text = message['text'].strip()
if re.search(r'^\\\w+', text):
self.ixchel_commands.parse(message)
else:
self.logger.warning('Received non-command text (%s).' % text)
async def loop(): # main loop
while True:
try:
logger.debug('Checking connections (Slack, telescope, etc.)...')
ixchel.telescope.ssh.is_connected()
ixchel.slack.is_connected()
await asyncio.sleep(10)
except asyncio.CancelledError:
break
def cleanup(signum, frame): # perform cleanup tasks
tasks.cancel()
logger.info('Starting ixchel...')
# read configuration file
logger.info('Reading configuration from file (%s)...' % cfg_file_path)
if not os.path.exists(cfg_file_path):
raise Exception('Configuration file (%s) is missing.' % cfg_file_path)
config = Config(cfg_file_path)
# Mayan goddess of the moon, medicine, and birth (mid-wifery). Stronger half of Itzamna!
ixchel = Ixchel(config)
# call back for incoming messages
ixchel.slack.rtm.on(event="message", callback=ixchel.parse_message)
# run slack and main loop concurrently
tasks = asyncio.gather(ixchel.slack.rtm.start(), loop())
# handle signals
signal.signal(signal.SIGINT, cleanup)
signal.signal(signal.SIGTERM, cleanup)
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(tasks)
except asyncio.CancelledError as e:
logger.error('Exception ( % s).' % e)
finally:
logger.info("%s has stopped." % ixchel.bot_name)
loop.close()