Skip to content

Commit 6edfb62

Browse files
committed
bot: Split into multiple compartmentalized ABC mixins
This helps accomodate the growing Bot class, since it's easily divided into several logical components anyway. Each component is an ABC (Abstract Base Class) that functions as a mixin and thus can access all the other attributes of the Bot class. Bot subclasses all the mixins to unify them. Telethon uses the same approach to divide TelegramClient into many mixins that each contain different categories of API methods. An adaptive MixinBase reference that is defined as abc.ABC during runtime and Bot during type checking is used as the subclass for each mixin to work around python/mypy#5837. Furthermore, the MixinBase reference itself has its type specified as Any to work around python/mypy#2477. The only change for outsiders should be the Bot class being moved to the `core` module. Signed-off-by: Danny Lin <[email protected]>
1 parent 1b8f07a commit 6edfb62

12 files changed

Lines changed: 537 additions & 432 deletions

‎pyrobud/bot.py‎

Lines changed: 0 additions & 429 deletions
This file was deleted.

‎pyrobud/command.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import telethon as tg
44

55
if TYPE_CHECKING:
6-
from .bot import Bot
6+
from .core import Bot
77

88
CommandFunc = Union[
99
Callable[..., Coroutine[Any, Any, None]], Callable[..., Coroutine[Any, Any, Optional[str]]],

‎pyrobud/core/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
from .bot import Bot

‎pyrobud/core/bot.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import logging
2+
3+
import aiohttp
4+
import telethon as tg
5+
6+
from ..util.config import Config
7+
from .command_dispatcher import CommandDispatcher
8+
from .database_provider import DatabaseProvider
9+
from .event_dispatcher import EventDispatcher
10+
from .module_extender import ModuleExtender
11+
from .telegram_bot import TelegramBot
12+
13+
14+
class Bot(TelegramBot, ModuleExtender, CommandDispatcher, DatabaseProvider, EventDispatcher):
15+
# Initialized during instantiation
16+
config: Config
17+
log: logging.Logger
18+
http_session: aiohttp.ClientSession
19+
client: tg.TelegramClient
20+
21+
def __init__(self, config: Config):
22+
# Save reference to config
23+
self.config = config
24+
25+
# Initialize other objects
26+
self.log = logging.getLogger("bot")
27+
self.http_session = aiohttp.ClientSession()
28+
29+
# Initialize mixins
30+
super().__init__()
31+
32+
async def stop(self) -> None:
33+
await self.dispatch_event("stop")
34+
await self.http_session.close()
35+
await self._db.close()
36+
37+
self.log.info("Running post-stop hooks")
38+
await self.dispatch_event("stopped")

‎pyrobud/core/bot_mixin_base.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
from typing import TYPE_CHECKING, Any
2+
3+
MixinBase: Any
4+
if TYPE_CHECKING:
5+
from .bot import Bot
6+
7+
MixinBase = Bot
8+
else:
9+
import abc
10+
11+
MixinBase = abc.ABC

‎pyrobud/core/command_dispatcher.py‎

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
from typing import TYPE_CHECKING, Any, MutableMapping
2+
3+
import telethon as tg
4+
5+
from .. import command, module, util
6+
from .bot_mixin_base import MixinBase
7+
8+
if TYPE_CHECKING:
9+
from .bot import Bot
10+
11+
12+
class CommandDispatcher(MixinBase):
13+
# Initialized during instantiation
14+
commands: MutableMapping[str, command.Command]
15+
16+
def __init__(self: "Bot", **kwargs: Any) -> None:
17+
# Initialize command map
18+
self.commands = {}
19+
20+
# Propagate initialization to other mixins
21+
super().__init__(**kwargs)
22+
23+
def register_command(self: "Bot", mod: module.Module, name: str, func: command.CommandFunc) -> None:
24+
cmd = command.Command(name, mod, func)
25+
26+
if name in self.commands:
27+
orig = self.commands[name]
28+
raise module.ExistingCommandError(orig, cmd)
29+
30+
self.commands[name] = cmd
31+
32+
for alias in cmd.aliases:
33+
if alias in self.commands:
34+
orig = self.commands[alias]
35+
raise module.ExistingCommandError(orig, cmd, alias=True)
36+
37+
self.commands[alias] = cmd
38+
39+
def unregister_command(self: "Bot", cmd: command.Command) -> None:
40+
del self.commands[cmd.name]
41+
42+
for alias in cmd.aliases:
43+
try:
44+
del self.commands[alias]
45+
except KeyError:
46+
continue
47+
48+
def register_commands(self: "Bot", mod: module.Module) -> None:
49+
for name, func in util.find_prefixed_funcs(mod, "cmd_"):
50+
done = False
51+
52+
try:
53+
self.register_command(mod, name, func)
54+
done = True
55+
finally:
56+
if not done:
57+
self.unregister_commands(mod)
58+
59+
def unregister_commands(self: "Bot", mod: module.Module) -> None:
60+
# Can't unregister while iterating, so collect commands to unregister afterwards
61+
to_unreg = []
62+
63+
for name, cmd in self.commands.items():
64+
# Let unregister_command deal with aliases
65+
if name != cmd.name:
66+
continue
67+
68+
if cmd.module == mod:
69+
to_unreg.append(cmd)
70+
71+
# Actually unregister the commands
72+
for cmd in to_unreg:
73+
self.unregister_command(cmd)
74+
75+
def command_predicate(self: "Bot", event: tg.events.NewMessage.Event) -> bool:
76+
if event.raw_text.startswith(self.prefix):
77+
parts = event.raw_text.split()
78+
parts[0] = parts[0][len(self.prefix) :]
79+
80+
event.segments = parts
81+
return True
82+
83+
return False
84+
85+
async def on_command(self: "Bot", msg: tg.events.NewMessage.Event) -> None:
86+
cmd = None
87+
88+
try:
89+
# Attempt to get command info
90+
try:
91+
cmd = self.commands[msg.segments[0]]
92+
except KeyError:
93+
return
94+
95+
# Construct invocation context
96+
ctx = command.Context(self, msg.message, msg.segments, len(self.prefix) + len(msg.segments[0]) + 1,)
97+
98+
if not (cmd.usage is None or cmd.usage_optional or ctx.input):
99+
err_base = f"⚠️ Missing parameters: {cmd.usage}"
100+
101+
if cmd.usage_reply:
102+
if msg.is_reply:
103+
reply_msg = await msg.get_reply_message()
104+
if reply_msg.text:
105+
ctx.input = reply_msg.text
106+
ctx.parsed_input = reply_msg.raw_text
107+
else:
108+
await ctx.respond(f"{err_base}\n__The message you replied to doesn't contain text.__")
109+
return
110+
else:
111+
await ctx.respond(f"{err_base} (replying is also supported)")
112+
return
113+
else:
114+
await ctx.respond(err_base)
115+
return
116+
117+
# Invoke command function
118+
try:
119+
ret = await cmd.func(ctx)
120+
121+
# Response shortcut
122+
if ret is not None:
123+
await ctx.respond(ret)
124+
except Exception as e:
125+
cmd.module.log.error(f"Error in command '{cmd.name}'", exc_info=e)
126+
await ctx.respond(f"⚠️ Error executing command:\n```{util.format_exception(e)}```")
127+
128+
await self.dispatch_event("command", cmd, msg)
129+
except Exception as e:
130+
if cmd is not None:
131+
cmd.module.log.error("Error in command handler", exc_info=e)
132+
133+
await self.respond(msg.message, f"⚠️ Error in command handler:\n```{util.format_exception(e)}```")

‎pyrobud/core/database_provider.py‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from typing import TYPE_CHECKING, Any
2+
3+
import plyvel
4+
5+
from .. import util
6+
from .bot_mixin_base import MixinBase
7+
8+
if TYPE_CHECKING:
9+
from .bot import Bot
10+
11+
12+
class DatabaseProvider(MixinBase):
13+
# Initialized during instantiation
14+
_db: util.db.AsyncDB
15+
db: util.db.AsyncDB
16+
17+
def __init__(self: "Bot", **kwargs: Any) -> None:
18+
# Initialize database
19+
self._db = util.db.AsyncDB(plyvel.DB(self.config["bot"]["db_path"], create_if_missing=True))
20+
self.db = self.get_db("bot")
21+
22+
# Propagate initialization to other mixins
23+
super().__init__(**kwargs)
24+
25+
def get_db(self: "Bot", prefix: str) -> util.db.AsyncDB:
26+
return self._db.prefixed_db(prefix + ".")

‎pyrobud/core/event_dispatcher.py‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import asyncio
2+
import bisect
3+
from typing import TYPE_CHECKING, Any, MutableMapping, MutableSequence
4+
5+
from .. import module, util
6+
from ..listener import Listener, ListenerFunc
7+
from .bot_mixin_base import MixinBase
8+
9+
if TYPE_CHECKING:
10+
from .bot import Bot
11+
12+
13+
class EventDispatcher(MixinBase):
14+
# Initialized during instantiation
15+
listeners: MutableMapping[str, MutableSequence[Listener]]
16+
17+
def __init__(self: "Bot", **kwargs: Any) -> None:
18+
# Initialize listener map
19+
self.listeners = {}
20+
21+
# Propagate initialization to other mixins
22+
super().__init__(**kwargs)
23+
24+
def register_listener(self: "Bot", mod: module.Module, event: str, func: ListenerFunc, priority: int = 100) -> None:
25+
listener = Listener(event, func, mod, priority)
26+
27+
if event in self.listeners:
28+
bisect.insort(self.listeners[event], listener)
29+
else:
30+
self.listeners[event] = [listener]
31+
32+
def unregister_listener(self: "Bot", listener: Listener) -> None:
33+
self.listeners[listener.event].remove(listener)
34+
35+
def register_listeners(self: "Bot", mod: module.Module) -> None:
36+
for event, func in util.find_prefixed_funcs(mod, "on_"):
37+
done = True
38+
try:
39+
self.register_listener(mod, event, func, priority=getattr(func, "_listener_priority", 100))
40+
done = True
41+
finally:
42+
if not done:
43+
self.unregister_listeners(mod)
44+
45+
def unregister_listeners(self: "Bot", mod: module.Module) -> None:
46+
# Can't unregister while iterating, so collect listeners to unregister afterwards
47+
to_unreg = []
48+
49+
for lst in self.listeners.values():
50+
for listener in lst:
51+
if listener.module == mod:
52+
to_unreg.append(listener)
53+
54+
# Actually unregister the listeners
55+
for listener in to_unreg:
56+
self.unregister_listener(listener)
57+
58+
async def dispatch_event(self: "Bot", event: str, *args: Any, **kwargs: Any) -> None:
59+
tasks = set()
60+
61+
try:
62+
listeners = self.listeners[event]
63+
except KeyError:
64+
return None
65+
66+
if not listeners:
67+
return
68+
69+
for lst in listeners:
70+
task = self.loop.create_task(lst.func(*args, **kwargs))
71+
tasks.add(task)
72+
73+
self.log.debug(f"Dispatching event '{event}' with data {args}")
74+
await asyncio.wait(tasks)
75+
76+
def dispatch_event_nowait(self: "Bot", event: str, *args: Any, **kwargs: Any) -> None:
77+
self.loop.create_task(self.dispatch_event(event, *args, **kwargs))

‎pyrobud/core/module_extender.py‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
import importlib
2+
import inspect
3+
import os
4+
from types import ModuleType
5+
from typing import TYPE_CHECKING, Any, MutableMapping, Optional, Type
6+
7+
from .. import custom_modules, module, modules, util
8+
from .bot_mixin_base import MixinBase
9+
10+
if TYPE_CHECKING:
11+
from .bot import Bot
12+
13+
14+
class ModuleExtender(MixinBase):
15+
# Initialized during instantiation
16+
modules: MutableMapping[str, module.Module]
17+
18+
def __init__(self: "Bot", **kwargs: Any) -> None:
19+
# Initialize module map
20+
self.modules = {}
21+
22+
# Propagate initialization to other mixins
23+
super().__init__(**kwargs)
24+
25+
def load_module(self: "Bot", cls: Type[module.Module], *, comment: Optional[str] = None) -> None:
26+
_comment = comment + " " if comment else ""
27+
self.log.info(
28+
f"Loading {_comment}module '{cls.name}' ({cls.__name__}) from '{os.path.relpath(inspect.getfile(cls))}'"
29+
)
30+
31+
if cls.name in self.modules:
32+
old = type(self.modules[cls.name])
33+
raise module.ExistingModuleError(old, cls)
34+
35+
mod = cls(self)
36+
mod.comment = comment
37+
self.register_listeners(mod)
38+
self.register_commands(mod)
39+
self.modules[cls.name] = mod
40+
41+
def unload_module(self: "Bot", mod: module.Module) -> None:
42+
_comment = mod.comment + " " if mod.comment else ""
43+
44+
cls = type(mod)
45+
path = os.path.relpath(inspect.getfile(cls))
46+
self.log.info(f"Unloading {_comment}module '{cls.name}' ({cls.__name__}) from '{path}'")
47+
48+
self.unregister_listeners(mod)
49+
self.unregister_commands(mod)
50+
del self.modules[cls.name]
51+
52+
def _load_modules_from_metamod(self: "Bot", metamod: ModuleType, *, comment: str = None) -> None:
53+
for _sym in getattr(metamod, "__all__", ()):
54+
module_mod: ModuleType = getattr(metamod, _sym)
55+
56+
if inspect.ismodule(module_mod):
57+
for sym in dir(module_mod):
58+
cls = getattr(module_mod, sym)
59+
if inspect.isclass(cls) and issubclass(cls, module.Module):
60+
self.load_module(cls, comment=comment)
61+
62+
def load_all_modules(self: "Bot") -> None:
63+
self.log.info("Loading modules")
64+
self._load_modules_from_metamod(modules)
65+
self._load_modules_from_metamod(custom_modules, comment="custom")
66+
self.log.info("All modules loaded.")
67+
68+
def unload_all_modules(self: "Bot") -> None:
69+
self.log.info("Unloading modules...")
70+
71+
# Can't modify while iterating, so collect a list first
72+
for mod in list(self.modules.values()):
73+
self.unload_module(mod)
74+
75+
self.log.info("All modules unloaded.")
76+
77+
async def reload_module_pkg(self: "Bot") -> None:
78+
self.log.info("Reloading base module class...")
79+
await util.run_sync(importlib.reload, module)
80+
81+
self.log.info("Reloading master module...")
82+
await util.run_sync(importlib.reload, modules)
83+
84+
self.log.info("Reloading custom master module...")
85+
await util.run_sync(importlib.reload, custom_modules)

0 commit comments

Comments
 (0)