Bot now inherits from an abstract class and added it to __init__.
authorGeorgios Atheridis <atheridis@tutamail.com>
Thu, 2 Jun 2022 07:03:38 +0000 (10:03 +0300)
committerGeorgios Atheridis <atheridis@tutamail.com>
Thu, 2 Jun 2022 07:03:38 +0000 (10:03 +0300)
aptbot/__init__.py
aptbot/bot.py
aptbot/constants.py
aptbot/main.py
aptbot/resources/main.py
examples/example_1/main.py

index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..18e029710f3f62c2033ed720e8368df71226d381 100644 (file)
@@ -0,0 +1,4 @@
+from .bot import ABCBot as Bot
+from .bot import Commands, Message
+
+__all__ = ["Bot", "Commands", "Message"]
index 0105f5ec55d986aef21d66c123c04c27c6abd24b..c4c548f9533cee154984456c804378dcc2521da8 100644 (file)
@@ -2,9 +2,10 @@ import logging
 import re
 import socket
 import time
+from abc import ABC, abstractmethod
 from dataclasses import dataclass, field
 from enum import Enum
-from typing import Optional, Union
+from typing import Iterable, Optional, Union
 
 logger = logging.getLogger(__name__)
 
@@ -33,7 +34,13 @@ class Message:
     value: str = ""
 
 
-class Bot:
+class ABCBot(ABC):
+    @abstractmethod
+    def send_message(self, channel: str, text: Union[list[str], str], reply=None):
+        pass
+
+
+class Bot(ABCBot):
     def __init__(self, nick: str, oauth_token: str):
         self._server = "irc.chat.twitch.tv"
         self._port = 6667
@@ -41,7 +48,7 @@ class Bot:
         self._oauth_token = oauth_token
         self._connected_channels = set()
 
-    def send_command(self, command: str):
+    def _send_command(self, command: str):
         if "PASS" not in command:
             logger.debug(f"< {command}")
         self._irc.send((command + "\r\n").encode())
@@ -49,25 +56,25 @@ class Bot:
     def connect(self):
         self._irc = socket.socket()
         self._irc.connect((self._server, self._port))
-        self.send_command(f"PASS oauth:{self._oauth_token}")
-        self.send_command(f"NICK {self._nick}")
-        self.send_command(
+        self._send_command(f"PASS oauth:{self._oauth_token}")
+        self._send_command(f"NICK {self._nick}")
+        self._send_command(
             f"CAP REQ :twitch.tv/membership twitch.tv/tags twitch.tv/commands"
         )
 
     def join_channel(self, channel: str):
-        self.send_command(f"{Commands.JOIN.value} #{channel}")
+        self._send_command(f"{Commands.JOIN.value} #{channel}")
         self._connected_channels.add(channel)
 
-    def join_channels(self, channels: set[str]):
+    def join_channels(self, channels: Iterable):
         for channel in channels:
             self.join_channel(channel)
 
     def leave_channel(self, channel: str):
-        self.send_command(f"{Commands.PART.value} #{channel}")
+        self._send_command(f"{Commands.PART.value} #{channel}")
         self._connected_channels.remove(channel)
 
-    def send_privmsg(self, channel: str, text: Union[list[str], str], reply=None):
+    def send_message(self, channel: str, text: Union[list[str], str], reply=None):
         if reply:
             replied_command = f"@reply-parent-msg-id={reply} "
         else:
@@ -75,10 +82,10 @@ class Bot:
         if isinstance(text, list):
             for t in text:
                 command = replied_command + f"{Commands.PRIVMSG.value} #{channel} :{t}"
-                self.send_command(command)
+                self._send_command(command)
         else:
             command = replied_command + f"{Commands.PRIVMSG.value} #{channel} :{text}"
-            self.send_command(command)
+            self._send_command(command)
 
     @staticmethod
     def _replace_escaped_space_in_tags(tag_value: str) -> str:
@@ -103,7 +110,7 @@ class Bot:
         return new_tag_value
 
     @staticmethod
-    def parse_message(received_msg: str) -> Message:
+    def _parse_message(received_msg: str) -> Message:
         split = re.search(
             r"(?:(?:@(.+))\s)?:(?:(?:(\w+)!\w+@\w+\.)?.+)\s(\w+)\s\#(\w+)\s:?(.+)?",
             received_msg,
@@ -139,11 +146,11 @@ class Bot:
     def _handle_message(self, received_msg: str) -> Message:
         logger.debug(received_msg)
         if received_msg == "PING :tmi.twitch.tv":
-            self.send_command("PONG :tmi.twitch.tv")
+            self._send_command("PONG :tmi.twitch.tv")
             return Message()
         elif not received_msg:
             return Message()
-        return Bot.parse_message(received_msg)
+        return Bot._parse_message(received_msg)
 
     def receive_messages(self) -> list[Message]:
         messages = []
@@ -169,3 +176,6 @@ class Bot:
         self.connect()
         self.join_channels(self._connected_channels)
         time.sleep(2)
+
+    # Aliasing method names for backwards compatibility
+    send_privmsg = send_message
index eb5ef1cec1f2bffe4f0e66d2073c510a3f4e4ae4..77ac5206e1cf8b2752a4994713f2aa0c210511d5 100644 (file)
@@ -11,6 +11,16 @@ elif os.name == "nt":
     if "APPDATA" in os.environ:
         CONFIG_PATH = os.path.join(os.environ["APPDATA"], "aptbot/accounts")
         CONFIG_LOGS = os.path.join(os.environ["APPDATA"], "aptbot/logs")
+    else:
+        print(
+            "APPDATA is not set, something must be very wrong.",
+            file=sys.stderr,
+        )
+        sys.exit(1)
+else:
+    print("Your OS is not supported", file=sys.stderr)
+    sys.exit(1)
+
 
 PORT = 26538
 LOCALHOST = "127.0.0.1"
@@ -33,7 +43,7 @@ LOGGING_DICT = {
         },
         "file": {
             "class": "logging.handlers.TimedRotatingFileHandler",
-            "level": "DEBUG",
+            "level": "INFO",
             "formatter": "simple",
             "filename": CONFIG_FILE,
             "when": "w0",
index 376ed84ba562afb9b8e9a3797684fa82acc764dd..8b0bc9ab13d7e8fa086664216f99b487c988ca17 100644 (file)
@@ -105,9 +105,7 @@ def initialize(bot: Bot):
         if os.path.isdir(os.path.join(CONFIG_PATH, c))
     ]
     channels = filter(lambda x: not x.startswith("."), channels)
-    for channel in channels:
-        if not channel.startswith("."):
-            bot.join_channel(channel)
+    bot.join_channels(channels)
 
 
 def listener():
@@ -152,7 +150,7 @@ def listener():
             if args_logic.BotCommands.JOIN.value in command:
                 bot.join_channel(channel)
             elif args_logic.BotCommands.SEND.value in command:
-                bot.send_privmsg(channel, msg)
+                bot.send_message(channel, msg)
             elif args_logic.BotCommands.KILL.value in command:
                 bot.disconnect()
                 c.close()
index 166f8820e9005797ae976dd0e9900a47f24ace2d..6c7bc6acbcb92cb75ca2d5252c82b5620fb9bc31 100644 (file)
@@ -1,4 +1,4 @@
-from aptbot.bot import Bot, Commands, Message
+from aptbot import Bot, Commands, Message
 
 
 def start(bot: Bot, message: Message):
@@ -15,7 +15,7 @@ def main(bot: Bot, message: Message):
         # but then the message sent back
         # will contain the name of the user in all lowercase
         if message.value.split()[0] == "!hello":
-            bot.send_privmsg(
+            bot.send_message(
                 message.channel,
                 f"hello {message.tags['display-name']}",
                 reply=message.tags["id"],
index 166f8820e9005797ae976dd0e9900a47f24ace2d..6614e5ddba04ce5f0592b325d4bd2e07fab0c76f 100644 (file)
@@ -1,4 +1,4 @@
-from aptbot.bot import Bot, Commands, Message
+from aptbot import Bot, Commands, Message
 
 
 def start(bot: Bot, message: Message):