From fcc726774ec453121f8050cc18377e5896276dce Mon Sep 17 00:00:00 2001 From: Frank Dai Date: Sat, 14 Dec 2019 22:03:40 -0800 Subject: [PATCH] Add a lock to the bot's say function --- ircbot/ircbot.py | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/ircbot/ircbot.py b/ircbot/ircbot.py index 16da42c..584e0e3 100644 --- a/ircbot/ircbot.py +++ b/ircbot/ircbot.py @@ -135,6 +135,9 @@ def __init__( self.plugins: Dict[str, ModuleType] = {} self.extra_channels: Set[str] = set() # plugins can add stuff here + # As we use threads, we should ensure that we use them safely + self.lock = threading.RLock() + # Register plugins before joining the server. self.register_plugins() @@ -340,17 +343,19 @@ def plusone(m): self.connection.topic(channel, new_topic=new_topic) def say(self, channel, message): - # Find the length of the full message - msg_len = len(f'PRIVMSG {channel} :{message}\r\n'.encode('utf-8')) - - # The message must be split up if over the length limit - if msg_len > MAX_CLIENT_MSG: - messages = split_utf8(message.encode('utf-8'), MAX_CLIENT_MSG) - - for msg in messages: - self.connection.privmsg(channel, msg) - else: - self.connection.privmsg(channel, message) + # This is writing to a socket, it should be synchronized + with self.lock: + # Find the length of the full message + msg_len = len(f'PRIVMSG {channel} :{message}\r\n'.encode('utf-8')) + + # The message must be split up if over the length limit + if msg_len > MAX_CLIENT_MSG: + messages = split_utf8(message.encode('utf-8'), MAX_CLIENT_MSG) + + for msg in messages: + self.connection.privmsg(channel, msg) + else: + self.connection.privmsg(channel, message) # Generator which splits the unicode message string