1
Fork 0
mirror of https://github.com/Steffo99/greed.git synced 2024-11-22 22:14:19 +00:00

Restructure the ChatWorker class

This commit is contained in:
Steffo 2017-12-14 09:40:03 +01:00
parent 1ee792e9ee
commit edefc57147
WARNING! Although there is a key with this ID in the database it does not verify this commit! This commit is SUSPICIOUS.
GPG key ID: C27544372FBB445D
2 changed files with 42 additions and 46 deletions

View file

@ -62,7 +62,7 @@ def main():
# Otherwise, forward the update to the corresponding worker # Otherwise, forward the update to the corresponding worker
receiving_worker = chat_workers.get(update.message.chat.id) receiving_worker = chat_workers.get(update.message.chat.id)
# Ensure a worker exists for the chat and is alive # Ensure a worker exists for the chat and is alive
if receiving_worker is None or not receiving_worker.thread.is_alive(): if receiving_worker is None or not receiving_worker.is_alive():
# Suggest that the user restarts the chat with /start # Suggest that the user restarts the chat with /start
bot.send_message(update.message.chat.id, strings.error_no_worker_for_chat) bot.send_message(update.message.chat.id, strings.error_no_worker_for_chat)
# Skip the update # Skip the update

View file

@ -15,60 +15,56 @@ class StopSignal:
self.reason = reason self.reason = reason
class ChatWorker: class ChatWorker(threading.Thread):
"""A worker for a single conversation. A new one should be created every time the /start command is sent.""" """A worker for a single conversation. A new one is created every time the /start command is sent."""
def __init__(self, bot: telegram.Bot, chat: telegram.Chat): def __init__(self, bot: telegram.Bot, chat: telegram.Chat, *args, **kwargs):
# Initialize the thread
super().__init__(name=f"ChatThread {chat.first_name}", *args, **kwargs)
# Store the bot and chat info inside the class
self.bot = bot
self.chat = chat
# The sending pipe is stored in the ChatWorker class, allowing the forwarding of messages to the chat process # The sending pipe is stored in the ChatWorker class, allowing the forwarding of messages to the chat process
self.queue = queuem.Queue() self.queue = queuem.Queue()
# A new thread running the conversation handler is created, and the queue is passed to its arguments to enable the receiving of messages
self.thread = threading.Thread(target=conversation_handler, args=(bot, chat, self.queue))
def start(self): def run(self):
"""Start the worker process.""" """The conversation code."""
self.thread.start() # TODO: catch all the possible exceptions
# Welcome the user to the bot
self.bot.send_message(self.chat.id, strings.conversation_after_start)
# TODO: Send a command list or something
while True:
# For now, echo the sent message
update = self._receive_next_update()
self.bot.send_message(self.chat.id, f"{threading.current_thread().name} {update.message.text}")
def stop(self, reason: str=""): def stop(self, reason: str=""):
"""Gracefully stop the worker process""" """Gracefully stop the worker process"""
# Send a stop message to the thread # Send a stop message to the thread
self.queue.put(StopSignal(reason)) self.queue.put(StopSignal(reason))
# Wait for the thread to stop # Wait for the thread to stop
self.thread.join() self.join()
# TODO: maybe move these functions to a class def _receive_next_update(self) -> telegram.Update:
"""Get the next update from the queue.
def graceful_stop(bot: telegram.Bot, chat: telegram.Chat, queue):
"""Handle the graceful stop of the process."""
# Notify the user that the session has expired
bot.send_message(chat.id, strings.conversation_expired)
# End the process
sys.exit(0)
def receive_next_update(bot: telegram.Bot, chat: telegram.Chat, queue) -> telegram.Update:
"""Get the next update from a pipe.
If no update is found, block the process until one is received. If no update is found, block the process until one is received.
If a stop signal is sent, try to gracefully stop the process.""" If a stop signal is sent, try to gracefully stop the thread."""
# Pop data from the queue # Pop data from the queue
try: try:
data = queue.get(timeout=int(config["Telegram"]["conversation_timeout"])) data = self.queue.get(timeout=int(config["Telegram"]["conversation_timeout"]))
except queuem.Empty: except queuem.Empty:
# If the conversation times out, gracefully stop the thread # If the conversation times out, gracefully stop the thread
graceful_stop(bot, chat, queue) self._graceful_stop()
# Check if the data is a stop signal instance # Check if the data is a stop signal instance
if isinstance(data, StopSignal): if isinstance(data, StopSignal):
# Gracefully stop the process # Gracefully stop the process
graceful_stop(bot, chat, queue) self._graceful_stop()
# Return the received update # Return the received update
return data return data
def _graceful_stop(self):
def conversation_handler(bot: telegram.Bot, chat: telegram.Chat, queue): """Handle the graceful stop of the thread."""
"""This function is ran once for every conversation (/start command) by a separate process.""" # Notify the user that the session has expired
# TODO: catch all the possible exceptions self.bot.send_message(self.chat.id, strings.conversation_expired)
# Welcome the user to the bot # End the process
bot.send_message(chat.id, strings.conversation_after_start) sys.exit(0)
# TODO: Send a command list or something
while True:
# For now, echo the sent message
update = receive_next_update(bot, chat, queue)
bot.send_message(chat.id, f"{threading.current_thread().name} {update.message.text}")