about summary refs log tree commit diff
path: root/src/petthecord/bot.py
blob: a7e08e38241d094d03d1d23227a734076f051e9f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
from logging import getLogger

from aiohttp.web import AppRunner, TCPSite
from discord import app_commands, Interaction, Intents, User
from discord.ext import commands

from .server import Server


class PatTheCordCog(commands.Cog):
    def __init__(self, client: commands.Bot, origin: str = "https://ptc.pwn3t.ru") -> None:
        self.client = client
        self.origin = origin

        super().__init__()

        self._logger = getLogger("petthecord.bot")

    @app_commands.allowed_installs(users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    @app_commands.command(
        name="petpet",
        description="Pat some user"
    )
    @app_commands.describe(
        user="User to pet",
        r="Some random stuff, set it if avatar is not up to date"
    )
    async def petthecord(
        self,
        interaction: Interaction,

        user: User,
        r: str = ""
    ) -> None:
        self._logger.info(f"Petting {user.id} for {interaction.user.id}")
        await interaction.response.send_message(f"{self.origin}/{user.id}.{r}.gif")


class Bot(commands.Bot):
    def __init__(
        self,

        host: str = "127.0.0.1",
        port: int = 8080,
        origin: str = "https://ptc.pwn3t.ru",
        caching: bool = True,
        cache_path: str = "/var/cache/petthecord",
        cache_lifetime: int = 86400,
        cache_gc_delay: int = 14400,
    ) -> None:
        super().__init__(
            command_prefix="!",
            intents=Intents.default()
        )
        self._host = host
        self._port = port
        self._origin = origin
        self._caching = caching
        self._cache_path = cache_path
        self._cache_lifetime = cache_lifetime
        self._cache_gc_delay = cache_gc_delay

        self._logger = getLogger("petthecord")

    async def on_ready(self) -> None:
        await self.add_cog(PatTheCordCog(self, self._origin))
        await self.tree.sync()

        server = Server(
            self,
            self._caching,
            self._cache_path,
            self._cache_lifetime,
            self._cache_gc_delay
        )
        runner = AppRunner(server)
        await runner.setup()
        site = TCPSite(runner, self._host, self._port)
        await site.start()

        getLogger("petthecord.server").info(f"Started serving on {self._host}:{self._port}")

        if self._caching:
            await server.clean_cache()