summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAndrew Yu <andrew@andrewyu.org>2022-08-12 02:30:00 +0800
committerAndrew Yu <andrew@andrewyu.org>2022-08-12 02:30:00 +0800
commit054308f65881934a190bc192687ad9decf909194 (patch)
tree6657a8968a596f169649bda1ab427e7a3c867d13
parent76bd3f2c09178b1fb29a05f905de391cb1688a3a (diff)
downloadirc-mod-bot-054308f65881934a190bc192687ad9decf909194.tar.gz
irc-mod-bot-054308f65881934a190bc192687ad9decf909194.zip
Add support for single-use callbacksHEADmaster
-rw-r--r--bot.py21
1 files changed, 13 insertions, 8 deletions
diff --git a/bot.py b/bot.py
index a4bad69..94dda72 100644
--- a/bot.py
+++ b/bot.py
@@ -247,17 +247,18 @@ def reply(s: socket.socket, msg: Message, text: bytes) -> bytes:
IRC_CALLBACK_FUNCTION_TYPE = Callable[
[socket.socket, State, User, dict[bytes, User], dict[bytes, Channel], Message], None
]
-irc_callbacks: dict[bytes, IRC_CALLBACK_FUNCTION_TYPE] = {}
-
+irc_callbacks: dict[bytes, list[tuple[IRC_CALLBACK_FUNCTION_TYPE, bool]]] = {}
+# The bool here indicates if this callback is single-use.
def register_irc_callback(
cmd: bytes,
) -> Callable[[IRC_CALLBACK_FUNCTION_TYPE], IRC_CALLBACK_FUNCTION_TYPE]:
- if cmd in irc_callbacks.keys():
- raise ValueError("%s was already added to the callback list" % repr(cmd))
+ def add_handler(f: IRC_CALLBACK_FUNCTION_TYPE, single_use: bool = False) -> IRC_CALLBACK_FUNCTION_TYPE:
+ try:
+ irc_callbacks[cmd].append((f, single_use))
+ except KeyError:
+ irc_callbacks[cmd] = [(f, single_use)]
- def add_handler(f: IRC_CALLBACK_FUNCTION_TYPE) -> IRC_CALLBACK_FUNCTION_TYPE:
- irc_callbacks[cmd] = f
return f
return add_handler
@@ -338,7 +339,7 @@ def handle_part(
) -> None:
if msg.source is None:
raise ProtocolViolation("PART without source")
- if msg.source.nick.lower() == me.nick():
+ if msg.source.nick.lower() == me.nick.lower():
try:
channels[msg.args[0]].joined = False
except KeyError:
@@ -685,7 +686,11 @@ def handle_incoming_message(
msg: Message,
) -> None:
try:
- irc_callbacks[msg.cmd](s, state, me, users, channels, msg)
+ for callback in irc_callbacks[msg.cmd]:
+ callback[0](s, state, me, users, channels, msg)
+ if callback[1]:
+ # Remove single-use callbacks after use.
+ irc_callbacks[msg.cmd].remove(callback)
except KeyError:
pass