|
| 1 | +"""MIT License |
| 2 | +
|
| 3 | +Copyright (c) 2021-Present PythonistaGuild |
| 4 | +
|
| 5 | +Permission is hereby granted, free of charge, to any person obtaining a copy |
| 6 | +of this software and associated documentation files (the "Software"), to deal |
| 7 | +in the Software without restriction, including without limitation the rights |
| 8 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 9 | +copies of the Software, and to permit persons to whom the Software is |
| 10 | +furnished to do so, subject to the following conditions: |
| 11 | +
|
| 12 | +The above copyright notice and this permission notice shall be included in all |
| 13 | +copies or substantial portions of the Software. |
| 14 | +
|
| 15 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 16 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 17 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 18 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 19 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 20 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 21 | +SOFTWARE. |
| 22 | +""" |
| 23 | +import json |
| 24 | +import pathlib |
| 25 | +from collections import deque |
| 26 | +from typing import Any |
| 27 | + |
| 28 | +import aiohttp |
| 29 | +import asyncpg |
| 30 | +import discord |
| 31 | +from discord.ext import commands |
| 32 | + |
| 33 | +from core import CONFIG |
| 34 | +from core.utils.logging import LogHandler |
| 35 | +from modules import EXTENSIONS |
| 36 | + |
| 37 | + |
| 38 | +class Bot(commands.Bot): |
| 39 | + session: aiohttp.ClientSession |
| 40 | + pool: asyncpg.Pool[asyncpg.Record] |
| 41 | + log_handler: LogHandler |
| 42 | + |
| 43 | + __slots__ = ( |
| 44 | + "session", |
| 45 | + "pool", |
| 46 | + "log_handler", |
| 47 | + ) |
| 48 | + |
| 49 | + def __init__(self): |
| 50 | + super().__init__( |
| 51 | + command_prefix=commands.when_mentioned_or(CONFIG["BOT"]["prefix"]), |
| 52 | + intents=discord.Intents.all(), |
| 53 | + ) |
| 54 | + self._previous_websocket_events: deque[Any] = deque(maxlen=10) |
| 55 | + |
| 56 | + async def on_ready(self) -> None: |
| 57 | + """On Bot ready - cache is built.""" |
| 58 | + assert self.user |
| 59 | + print(f"Online. Logged in as {self.user.name} || {self.user.id}") |
| 60 | + |
| 61 | + async def on_socket_response(self, message: Any) -> None: |
| 62 | + """Quick override to log websocket events.""" |
| 63 | + self._previous_websocket_events.append(message) |
| 64 | + |
| 65 | + async def setup_hook(self) -> None: |
| 66 | + self.session = aiohttp.ClientSession() |
| 67 | + |
| 68 | + async def start(self, token: str, *, reconnect: bool = True) -> None: |
| 69 | + try: |
| 70 | + await super().start(token=token, reconnect=reconnect) |
| 71 | + finally: |
| 72 | + path = pathlib.Path("logs/prev_events.log") |
| 73 | + with path.open("w+", encoding="utf-8") as f: |
| 74 | + for event in self._previous_websocket_events: |
| 75 | + try: |
| 76 | + last_log = json.dumps(event, ensure_ascii=True, indent=2) |
| 77 | + except Exception: |
| 78 | + f.write(f"{event}\n") |
| 79 | + else: |
| 80 | + f.write(f"{last_log}\n") |
| 81 | + |
| 82 | + async def close(self) -> None: |
| 83 | + """Closes the Bot. It will also close the internal :class:`aiohttp.ClientSession`.""" |
| 84 | + await self.session.close() |
| 85 | + await super().close() |
| 86 | + |
| 87 | + |
| 88 | +async def main() -> None: |
| 89 | + async with Bot() as bot, aiohttp.ClientSession() as session, asyncpg.create_pool( |
| 90 | + user=CONFIG["DATABASE"]["user"], |
| 91 | + host=CONFIG["DATABASE"]["host"], |
| 92 | + database=CONFIG["DATABASE"]["database"], |
| 93 | + password=CONFIG["DATABASE"]["password"], |
| 94 | + port=CONFIG["DATABASE"]["port"], |
| 95 | + ) as pool, LogHandler() as handler: |
| 96 | + bot.session = session |
| 97 | + bot.pool = pool |
| 98 | + bot.log_handler = handler |
| 99 | + |
| 100 | + await bot.load_extension("jishaku") |
| 101 | + for extension in EXTENSIONS: |
| 102 | + await bot.load_extension(extension.name) |
| 103 | + bot.log_handler.log.info( |
| 104 | + "Loaded %sextension: %s", |
| 105 | + "module " if extension.ispkg else "", |
| 106 | + extension.name, |
| 107 | + ) |
| 108 | + |
| 109 | + await bot.start(CONFIG["BOT"]["token"]) |
0 commit comments