From 74df9e928742803b2a1db89a77f1fa0f5dd528a1 Mon Sep 17 00:00:00 2001 From: Stefan Harmuth Date: Sat, 18 Dec 2021 20:48:01 +0100 Subject: [PATCH] general irc bot interface --- tools/irc.py | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/tools/irc.py b/tools/irc.py index 865fae9..44150af 100644 --- a/tools/irc.py +++ b/tools/irc.py @@ -1,4 +1,8 @@ +from time import sleep + +from .schedule import Scheduler from .simplesocket import ClientSocket +from datetime import timedelta from enum import Enum from typing import Callable, Dict, List, Union @@ -365,3 +369,43 @@ class Client: def getChannelList(self) -> List[Channel]: return list(self.__channellist.values()) + + +class IrcBot(Client): + def __init__(self, server: str, port: int, nick: str, username: str, realname: str = "Python Bot"): + super().__init__(server, port, nick, username, realname) + self._scheduler = Scheduler() + self._channel_commands = {} + self._privmsg_commands = {} + self.subscribe(ServerMessage.MSG_PRIVMSG, self.on_privmsg) + + def on(self, *args, **kwargs): + self.subscribe(*args, **kwargs) + + def schedule(self, name: str, every: timedelta, func: Callable): + self._scheduler.schedule(name, every, func) + + def register_channel_command(self, command: str, channel: str, func: Callable): + if channel not in self._channel_commands: + self._channel_commands[channel] = {} + + self._channel_commands[channel][command] = func + + def register_privmsg_command(self, command: str, func: Callable): + self._privmsg_commands[command] = func + + def on_privmsg(self, msg_from, msg_to, message): + if not message: + return + command = message.split()[0] + if msg_to in self._channel_commands and command in self._channel_commands[msg_to]: + self._channel_commands[msg_to][command](msg_from, " ".join(message.split()[1:])) + + if msg_to == self.getUser().nickname and command in self._privmsg_commands: + self._privmsg_commands[command](msg_from, " ".join(message.split()[1:])) + + def run(self): + while True: + self._scheduler.run_pending() + self.receive() + sleep(0.01)