Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Message Fixes #23

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 22 additions & 22 deletions encodesrv/logs/bots/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,22 @@
from ...config import Config
from ..messages import Message_enum, message_dict

privmsg_re = re.compile(r"^<?@?([^ |^>]*)>?: *(.*)")
privmsg_re = re.compile(r"^<?@?([^ |^>]*)>?:? *(.*)$")
"""Regex to pull the user and message from Slack/IRC strings."""


def form_msg(enum_value, encodesrv_daemon = None):

"""Form whatever message is required.

Arguments:
enum_value (Message_enum): The enum value related to the requested message.
encodesrv_daemon (EncodeSrvDaemon): Main encodesrv instance.

Returns:
Message (string).
"""

if enum_value == Message_enum.status:
assert encodesrv_daemon != None
return form_status_msg(encodesrv_daemon)
Expand All @@ -32,49 +32,49 @@ def form_msg(enum_value, encodesrv_daemon = None):


def form_help_msg():

"""Form a nice, human readable, help message for the bot.

Arguments:
None.

Returns:
Help message (string).
"""

return message_dict[Message_enum.unknown_cmd]


def form_status_msg(encodesrv_daemon):

"""Form a nice, human readable message for the status of the server.

Arguments:
None.

Returns:
Status message (string).
"""

encoding = encodesrv_daemon.get_current_jobs()

if encoding == []:
encoding = 'no jobs'
else:
encoding = ', '.join(encoding).rstrip(', ')

dbconn = psycopg2.connect(**Config["database"])
cur = dbconn.cursor()
cur.execute("""SELECT COUNT(*)
FROM encode_jobs
WHERE status ='Not Encoding'
cur.execute("""SELECT COUNT(*)
FROM encode_jobs
WHERE status ='Not Encoding'
or status = 'Waiting'
""")
waiting = cur.fetchone()[0]
cur.close()
dbconn.close()
return message_dict[Message_enum.status].format(enc_jobs = encoding,
wait_jobs = waiting,
pl = "" if int(waiting) == 1 else "s"

return message_dict[Message_enum.status].format(enc_jobs = encoding,
wait_jobs = waiting,
pl = "" if int(waiting) == 1 else "s"
)
66 changes: 39 additions & 27 deletions encodesrv/logs/bots/slack.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,31 +13,33 @@
from ...config import Config
from ..messages import Message_enum

import websocket._exceptions

logger = logging.getLogger(__name__)

class Slack_rtm_thread(threading.Thread):

def __init__(self, parent, api_key, send_queue):

super(Slack_rtm_thread, self).__init__(daemon = True)
self.api_key = api_key
self.send_queue = send_queue
self.channel = None
self.parent = parent
self.connected = False

def get_connected(self):

return self.connected

def get_channel(self):

return self.channel

def set_channel(self, channel):

self.channel = channel

def run(self):
self.slackclient = slackclient.SlackClient(self.api_key)
connect = self.slackclient.rtm_connect()
Expand All @@ -49,7 +51,17 @@ def run(self):
msg = self.send_queue.get(block = False)
self.slackclient.rtm_send_message(self.get_channel(), Config["servername"] + "> " + msg)
except queue.Empty:
responses = self.slackclient.rtm_read()
try:
responses = self.slackclient.rtm_read()
except (ConnectionResetError, websocket._exceptions.WebSocketConnectionClosedException):
connect = self.slackclient.rtm_connect()
retries = 0
while not connect:
if retries > 8:
retries = 8
connect = self.slackclient.rtm_connect()
time.sleep(retries*15)
retries += 1
if responses == []:
continue
for msg in responses:
Expand All @@ -62,9 +74,9 @@ def run(self):
time.sleep(0.1)
else:
raise Exception("Could not connect to Slack.")

def _slack_respond(self, msg):

matches = common.privmsg_re.findall(msg['text'])
if len(matches) != 1:
return
Expand All @@ -73,23 +85,23 @@ def _slack_respond(self, msg):
daemon = self.parent.parent
enum = Message_enum
form_msg = common.form_msg

if cmd == "status":
msg = form_msg(enum.status, daemon)
else:
msg = form_msg(enum.unknown_cmd, daemon)

self.send_queue.put(msg)

def __str__(self):

return str(self.slackclient)


class Encode_slack():

def __init__(self, parent, api_key = None, channel = None, **kwargs):

assert type(api_key) == str
self.send_queue = queue.Queue()
self.rtm_thread = Slack_rtm_thread(self, api_key, self.send_queue)
Expand All @@ -100,19 +112,19 @@ def __init__(self, parent, api_key = None, channel = None, **kwargs):
while not self.rtm_thread.get_connected():
time.sleep(0.1)
logger.info("Connected to Slack.")

def get_channel(self):

return self.rtm_thread.get_channel()

def set_channel(self, channel):

self.rtm_thread.set_channel(channel)

def send_msg(self, msg):

self.send_queue.put(msg)

def emit(self, record):

self.send_msg(record.getMessage())
self.send_msg(record.getMessage())