|
| 1 | +import asyncio |
| 2 | + |
| 3 | +import aiomonitor as aiomonitor |
| 4 | + |
| 5 | +import interactions |
| 6 | +from interactions import Extension |
| 7 | + |
| 8 | +__all__ = ("Console",) |
| 9 | + |
| 10 | + |
| 11 | +class Console(Extension): |
| 12 | + """ |
| 13 | + Extension that starts the bot with the aiomonitor console active - notably giving you REPL for the bot |
| 14 | +
|
| 15 | + To access the console, you need to connect to the port specified in the constructor, by default 501. |
| 16 | + On linux, you can do this with `nc localhost 501`, on windows you can use `telnet localhost 501`. |
| 17 | +
|
| 18 | + For both platforms you can also use "python -m aiomonitor.cli -p 501" as a replacement for the above commands. |
| 19 | +
|
| 20 | + Args: |
| 21 | + port: The port to start the aiomonitor on |
| 22 | + console_port: The port to start the aiomonitor console on |
| 23 | + **kwargs: The locals to make available in the console, by default this includes `client`, `bot` and `interactions` |
| 24 | +
|
| 25 | + """ |
| 26 | + |
| 27 | + def __init__(self, client: interactions.Client, port: int = 501, console_port: int = 502, **kwargs) -> None: |
| 28 | + self.client.astart = self.async_start_bot |
| 29 | + self.port = port # 501 was chosen as windows throws a massive fit if you try to use the default port |
| 30 | + self.console_port = console_port |
| 31 | + self.locals = kwargs |
| 32 | + |
| 33 | + async def async_start_bot(self, token: str | None = None) -> None: |
| 34 | + """Starts the bot with the console active""" |
| 35 | + old_start = interactions.Client.astart |
| 36 | + |
| 37 | + _locals = self.locals | { |
| 38 | + "client": self.client, |
| 39 | + "bot": self.client, |
| 40 | + "interactions": interactions, |
| 41 | + } |
| 42 | + |
| 43 | + with aiomonitor.start_monitor( |
| 44 | + loop=asyncio.get_event_loop(), port=self.port, console_port=self.console_port, locals=_locals |
| 45 | + ) as monitor: |
| 46 | + self.client.logger.info(f"Started aiomonitor on {monitor._host}:{monitor._port}") # noqa |
| 47 | + |
| 48 | + await old_start(self.client, token) |
0 commit comments