Skip to content

Commit b2758e6

Browse files
committed
Fix Stuff
1 parent c78a3f9 commit b2758e6

File tree

10 files changed

+143
-24
lines changed

10 files changed

+143
-24
lines changed

.gitignore

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,6 @@ __pycache__
1212

1313
pdm.lock
1414
type_info.json
15-
.pdm-python
15+
.pdm-python
16+
17+
.mypy_cache

pyproject.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ requires-python = ">=3.12"
1010
dependencies = [
1111
"discord.py>=2.3.2",
1212
"asyncpg>=0.29.0",
13+
"openai>=1.37.0",
1314
]
1415
classifiers = [
1516
"Programming Language :: Python :: 3",
@@ -31,3 +32,5 @@ dev = [
3132

3233
[tool.mypy]
3334
disallow_incomplete_defs = true
35+
36+
[tool.pdm]

src/SideBot/__init__.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
from discord.ext import commands
1111
from discord.ext.commands import AutoShardedBot, Bot, when_mentioned_or
1212

13+
from SideBot.db.tags import Tag
14+
1315
from .utils import ButtonLink, DiscordUser
1416

1517

@@ -54,6 +56,8 @@ async def on_ready(self) -> None:
5456
)
5557
self.connection: asyncpg.Connection = await self.setup_connection()
5658

59+
await Tag.write_schema(self.connection)
60+
5761
await self.connection.set_type_codec(
5862
"discorduser",
5963
encoder=DiscordUser.to_tuple,

src/SideBot/cogs/admin.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Admin cog with commands for moderation."""
22

33
import asyncio
4+
import logging
45
from datetime import timedelta
56

67
import discord
@@ -69,6 +70,12 @@ def get_channel(self, i: int) -> SpamChannel | None:
6970
class Admin(BaseCog):
7071
"""Admin cog with commands for moderation."""
7172

73+
@classmethod
74+
async def setup(cls, bot: Bot) -> None:
75+
"""Initialize the cog and add it to the bot."""
76+
logging.getLogger(__name__).info("Initialized %s", cls.__name__)
77+
await bot.add_cog(cls(bot))
78+
7279
def __init__(self, bot: Bot, channels_max: int = 4) -> None:
7380
"""Initialize the cog with the bot and the maximum channels to check."""
7481
self.spammers: list[SpamUser] = []

src/SideBot/cogs/basecog.py

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,3 @@ def __init__(self, bot: Bot) -> None:
1212
"""Initialize the base cog with the bot."""
1313
self.bot = bot
1414
self.logger = logging.getLogger(__name__)
15-
16-
@classmethod
17-
async def setup(cls, bot: Bot) -> None:
18-
"""Initialize the cog and add it to the bot."""
19-
logging.getLogger(__name__).info("Initialized %s", cls.__name__)
20-
await bot.add_cog(cls(bot))

src/SideBot/cogs/developer.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""The developer cog for loading/reloading/unloading cogs and syncing app commands."""
22

3+
import logging
34
from typing import Literal
45

56
import discord
@@ -25,6 +26,12 @@
2526
class Developer(BaseCog):
2627
"""Developer cog with developer only commands."""
2728

29+
@classmethod
30+
async def setup(cls, bot: Bot) -> None:
31+
"""Initialize the cog and add it to the bot."""
32+
logging.getLogger(__name__).info("Initialized %s", cls.__name__)
33+
await bot.add_cog(cls(bot))
34+
2835
def __init__(self, bot: Bot) -> None:
2936
"""Initialize the developer cog."""
3037
super().__init__(bot)

src/SideBot/cogs/mod.py

Lines changed: 89 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,91 @@
1-
# ruff: noqa
1+
import logging
22

3-
# from .basecog import BaseCog
3+
import openai
4+
from discord import Embed, Message
5+
from discord.ext.commands import Bot, Cog
46

5-
# class MessageLogger(BaseCog):
6-
# def __init__():
7+
from .basecog import BaseCog
8+
9+
10+
class CheckMessage(BaseCog):
11+
"""CheckMessage cog with commands for moderation."""
12+
13+
def __init__(self, bot: Bot) -> None:
14+
"""Initialize the checkmessage cog."""
15+
super().__init__(bot)
16+
self.openai = openai.AsyncOpenAI(base_url="http://localhost:8080", api_key="none")
17+
self.logger.info("Connected to OpenAI API")
18+
19+
@Cog.listener()
20+
async def on_message(self, message: Message) -> None:
21+
"""Check the message for spam."""
22+
if message.channel.id == 1200508244909621289:
23+
return
24+
else:
25+
logging.info(message.channel.id)
26+
if message.author.bot:
27+
return
28+
if message.guild and message.guild.id != 949183273383395328:
29+
return
30+
if len(message.content) <= 1:
31+
return
32+
self.logger.info("Checking message %s", message.content)
33+
history_to_give = ""
34+
async for messages in message.channel.history(limit=3):
35+
if messages.id == message.id:
36+
continue
37+
history_to_give += f"{messages.author!s}: Start-Of-Message\n{messages.content}\nEnd-Of-Message\n\n"
38+
response = await self.openai.chat.completions.create(
39+
model="idk",
40+
messages=[
41+
{
42+
"role": "system",
43+
"content": 'You are a moderation bot checking if messages defame gender identities. Please respond with only a "YES", "MAYBE", or "NO" with a short reasoning',
44+
},
45+
{
46+
"role": "user",
47+
"content": "context:",
48+
},
49+
{
50+
"role": "user",
51+
"content": f"{history_to_give}",
52+
},
53+
{
54+
"role": "user",
55+
"content": "message:",
56+
},
57+
{
58+
"role": "user",
59+
"content": f"{message.author!s}: Start-Of-Message\n{message.content}\nEnd-Of-Message\n\n",
60+
},
61+
],
62+
n=1,
63+
max_tokens=10,
64+
)
65+
self.logger.info("Response: %s", response.choices[0].message)
66+
if "YES" in response.choices[0].message.content:
67+
self.logger.info("Message breaks rules")
68+
await self.bot.get_channel(1200508244909621289).send(
69+
embed=Embed(
70+
title="Message Breaks Rules",
71+
description=f"Jump To Message: [Here]({message.jump_url}), Reasoning: {response.choices[0].message.content}",
72+
),
73+
)
74+
elif "MAYBE" in response.choices[0].message.content:
75+
self.logger.info("Message possibly breaks rules")
76+
await self.bot.get_channel(1200508244909621289).send(
77+
embed=Embed(
78+
title="Message Possibly Breaks Rules",
79+
description=f"Jump To Message: [Here]({message.jump_url}), Reasoning: {response.choices[0].message.content}",
80+
),
81+
silent=True,
82+
)
83+
84+
@classmethod
85+
async def setup(cls, bot: Bot) -> None:
86+
"""Initialize the cog and add it to the bot."""
87+
logging.getLogger(__name__).info("Initialized %s", cls.__name__)
88+
await bot.add_cog(cls(bot))
89+
90+
91+
setup = CheckMessage.setup

src/SideBot/cogs/tags.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""prelimitary tags cog, will be updated later."""
22

33
import datetime
4+
import logging
45
import re
56
import traceback
67
import typing
@@ -9,13 +10,13 @@
910
from discord import app_commands
1011
from discord.app_commands import command as acommand
1112
from discord.app_commands import guild_only
13+
from discord.ext.commands import Bot
1214

1315
from SideBot import SideBot
16+
from SideBot.cogs.basecog import BaseCog
1417
from SideBot.db.tags import Tag as DBTag
1518
from SideBot.utils import ButtonLink, DiscordUser
1619

17-
from .basecog import BaseCog
18-
1920

2021
class UpdateTagsModal(discord.ui.Modal, title="Update a Tag"):
2122
"""Modal for updating tags."""
@@ -183,6 +184,12 @@ async def on_error(
183184
class Tags(BaseCog):
184185
"""Tags cog with commands for tags."""
185186

187+
@classmethod
188+
async def setup(cls, bot: Bot) -> None:
189+
"""Initialize the cog and add it to the bot."""
190+
logging.getLogger(__name__).info("Initialized %s", cls.__name__)
191+
await bot.add_cog(cls(bot))
192+
186193
def prepare_tag_view(self, button_links: list[ButtonLink]) -> discord.ui.View:
187194
"""Prepare the tag view."""
188195
view = discord.ui.View()

src/SideBot/cogs/utility.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,25 @@
11
"""The utility cog with various utility commands, listeners, etc."""
22

3+
import logging
34
import random as randomorg
45

56
import discord
67
from discord import Interaction
78
from discord.app_commands import command
89
from discord.ext.commands import Bot, Cog
910

11+
from SideBot.cogs.basecog import BaseCog
1012

11-
class Utility(Cog):
13+
14+
class Utility(BaseCog):
1215
"""The utility cog with various utility commands, listeners, etc."""
1316

17+
@classmethod
18+
async def setup(cls, bot: Bot) -> None:
19+
"""Initialize the cog and add it to the bot."""
20+
logging.getLogger(__name__).info("Initialized %s", cls.__name__)
21+
await bot.add_cog(cls(bot))
22+
1423
def __init__(
1524
self,
1625
bot: Bot,
@@ -21,7 +30,7 @@ def __init__(
2130
self.bot = bot
2231
self.rare_threshold = rare_threshold
2332
self.ultra_rare_threshold = ultra_rare_threshold
24-
super().__init__()
33+
super().__init__(bot)
2534

2635
@command(name="status", description="Get how the bot is currently feeling")
2736
async def status(self, inter: Interaction) -> None:

src/SideBot/db/tags.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""Tags database module."""
22

3+
import contextlib
34
import datetime
45
from collections.abc import AsyncGenerator
56
from typing import Any
@@ -12,7 +13,7 @@
1213
class _Tags:
1314
"""Internal DB class for tags."""
1415

15-
async def write_schema(self) -> None:
16+
async def write_schema(self: asyncpg.Connection) -> None:
1617
for x in [
1718
"""
1819
CREATE TYPE public.discorduser AS (
@@ -41,9 +42,10 @@ async def write_schema(self) -> None:
4142
""",
4243
"CREATE INDEX IF NOT EXISTS tags_guild_id_idx ON tags (guild_id, name)",
4344
]:
44-
await self.conn.execute(
45-
x,
46-
)
45+
with contextlib.suppress(asyncpg.exceptions.DuplicateObjectError):
46+
await self.execute(
47+
x,
48+
)
4749

4850
def __init__(self, conn: asyncpg.Connection) -> None:
4951
"""Tag database operations."""
@@ -171,12 +173,11 @@ def __init__(
171173
self.id = ident
172174
self.tags = _Tags(conn)
173175

174-
async def finish(
175-
self,
176-
) -> "Tag":
176+
async def write_schema(
177+
self: asyncpg.Connection,
178+
) -> None:
177179
"""Tag class."""
178-
await self.tags.write_schema()
179-
return self
180+
await _Tags.write_schema(self)
180181

181182
@classmethod
182183
async def get(

0 commit comments

Comments
 (0)