From ea6436f0dfed550f60090eb2d19ee3b57591fb29 Mon Sep 17 00:00:00 2001 From: Snaacky Date: Mon, 23 Dec 2024 04:09:06 -0500 Subject: [PATCH] refactor: sqlalchemy is setup, bot now boots properly again --- chiya/bot.py | 4 +- chiya/cogs/listeners/autoresponder.py | 216 -------------------------- chiya/cogs/listeners/highlight.py | 12 +- chiya/cogs/tasks/reminder.py | 38 ++--- chiya/database.py | 30 +--- 5 files changed, 30 insertions(+), 270 deletions(-) delete mode 100644 chiya/cogs/listeners/autoresponder.py diff --git a/chiya/bot.py b/chiya/bot.py index 55934d77..1a80cfd5 100644 --- a/chiya/bot.py +++ b/chiya/bot.py @@ -8,10 +8,9 @@ from discord.ext import commands from loguru import logger as log -import database +from chiya import database # noqa from chiya.config import config - bot = commands.Bot( activity=discord.Activity(type=discord.ActivityType.listening, name=config.bot.status), case_insensitive=True, @@ -76,5 +75,4 @@ async def load_cogs(): if sys.platform == "win32": asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) - database.Database().setup() asyncio.run(main()) diff --git a/chiya/cogs/listeners/autoresponder.py b/chiya/cogs/listeners/autoresponder.py deleted file mode 100644 index f5cab4cc..00000000 --- a/chiya/cogs/listeners/autoresponder.py +++ /dev/null @@ -1,216 +0,0 @@ -import discord -from discord.ext import commands -from loguru import logger as log - -from chiya.config import config -from chiya.utils import embeds - - -class AutoresponderListeners(commands.Cog): - def __init__(self, bot: commands.Bot) -> None: - self.bot = bot - - @commands.Cog.listener() - async def on_message(self, message: discord.Message) -> None: - """ - Scan incoming messages for autoresponder invokes (case-insensitive) - and replies with the appopriate embed. Currently only when invoked - by a staff member. - """ - # Ignore messages from bots to avoid infinite loops and other fuckery. - if message.author.bot: - return - - # Ignore DMs between users and the bot because .roles below will throw an exception. - if isinstance(message.channel, discord.channel.DMChannel): - return - - staff = [x for x in message.author.roles if x.id == config.roles.staff or x.id == config.roles.trial] - if not staff: - return - - rules_message = "https://discord.com/channels/974468300304171038/974483470548099104/984329857007747094" - match message.clean_content.lower(): - case "rule1": - await message.reply( - embed=embeds.make_embed( - title="Rule 1: Do not share content that violates anyone's intellectual property or other rights", - description=( - "Sharing illegal streaming sites, downloads, torrents, magnet links, trackers, " - "NZBs, or any other form of warez puts our community at risk of being shut down. " - "We are a discussion community, not a file-sharing hub." - ), - color=0x7D98E9, - thumbnail_url="https://i.imgur.com/X0upMFa.png", - title_url=rules_message, - ) - ) - case "rule2": - await message.reply( - embed=embeds.make_embed( - title="Rule 2: Do not spread any form of hate speech. Irony or jokes are not an excuse", - description=( - "Any form of prejudice, including but not limited to race, " - "religion, gender, sexual identity, or ethnic background, will not be tolerated." - ), - color=0x7D98E9, - thumbnail_url="https://i.imgur.com/Q9HVxLK.png", - title_url=rules_message, - ) - ) - case "rule3": - await message.reply( - embed=embeds.make_embed( - title="Rule 3: Do not attack others, troll, or instigate drama", - description=( - "Attacking, belittling, or instigating drama with others will result in your removal " - "from the community." - ), - color=0x7D98E9, - thumbnail_url="https://i.imgur.com/7OLIuky.png", - title_url=rules_message, - ) - ) - case "rule4": - await message.reply( - embed=embeds.make_embed( - title="Rule 4: Do not spam (text, images, links, Tenor gifs) or disrupt the flow of chat", - description=( - "Avoid spamming, derailing conversations, trolling, posting in the incorrect channel, " - "or disregarding channel rules. We expect you to make a basic attempt to fit in and " - "not cause problems." - ), - color=0x7D98E9, - thumbnail_url="https://i.imgur.com/37s6rUa.png", - title_url=rules_message, - ) - ) - case "rule5": - await message.reply( - embed=embeds.make_embed( - title="Rule 5: Do not ghost ping, spam ping, ping VIPs for support, or abuse pings in any way", - description=( - "Attempting to mass ping, spam ping, ghost ping, or harassing users with pings is not " - "allowed. VIPs should not be pinged for help with their service. <@&974483014967001119> " - "should only be pinged when the situation calls for their immediate attention." - ), - color=0x7D98E9, - thumbnail_url="https://i.imgur.com/4a5K4c6.png", - title_url=rules_message, - ) - ) - case "rule6": - await message.reply( - embed=embeds.make_embed( - title="Rule 6: Do not ask for, giveaway, or attempt to buy/sell/trade tracker invites", - description=( - "Invites are intended for personal acquaintances. " - "Publicly offering, requesting, or giving away invites to private trackers, " - "DDL communities, or Usenet indexers is not allowed." - ), - color=0x7D98E9, - thumbnail_url="https://i.imgur.com/W17MO9d.png", - title_url=rules_message, - ) - ) - case "rule7": - await message.reply( - embed=embeds.make_embed( - title="Rule 7: Do not advertise other Discord servers or services", - description=( - "We are not a billboard for you to advertise your Discord server, social media " - "channels, referral links, personal projects, or services. " - "Unsolicited spam via DMs will result in an immediate ban." - ), - color=0x7D98E9, - thumbnail_url="https://i.imgur.com/7cJCnh0.png", - title_url=rules_message, - ) - ) - case "rule8": - await message.reply( - embed=embeds.make_embed( - title="Rule 8: Do not use offensive or edgy text or imagery on your profile", - description=( - "Users with excessively offensive usernames, nicknames, avatars, server " - "profiles, or statuses may be asked to change the offending content or may be " - "preemptively banned in more severe cases." - ), - color=0x7D98E9, - thumbnail_url="https://i.imgur.com/xbvjFRq.png", - title_url=rules_message, - ) - ) - case "rule9": - await message.reply( - embed=embeds.make_embed( - title="Rule 9: Do not attempt to evade automod or mod actions", - description=( - "Abusing the rules, such as our automod system, will not be tolerated. Subsequently, " - "trying to find loopholes in the rules to evade mod action is not allowed and " - "will result in a permanent ban." - ), - color=0x7D98E9, - thumbnail_url="https://i.imgur.com/Nfcrq1N.png", - title_url=rules_message, - ) - ) - case "rule10": - await message.reply( - embed=embeds.make_embed( - title="Rule 10: Spoilers must be marked in spoiler tags and be clearly labeled", - description=( - "Be considerate and use spoiler tags when discussing plot elements. " - "Specify which title, series, or episode your spoiler is referencing outside the spoiler tag " - "so that people don't blindly click a spoiler." - ), - color=0x7D98E9, - thumbnail_url="https://i.imgur.com/wNZxV36.png", - title_url=rules_message, - ) - ) - case "rule11": - await message.reply( - embed=embeds.make_embed( - title="Rule 11: References to banned users or banned communities are not allowed", - description=( - "Do not discuss or reference any banned users or banned communities as " - "they have been banned for a reason already discussed by staff with no " - "need for further discussions." - ), - color=0x7D98E9, - thumbnail_url="https://i.imgur.com/2ZxCttO.png", - title_url=rules_message, - ) - ) - case "rule12": - await message.reply( - embed=embeds.make_embed( - title="Rule 12: All conversations must be in English", - description=( - "No language other than English is permitted. We appreciate other languages " - "and cultures, but we can only moderate the content we understand." - ), - color=0x7D98E9, - thumbnail_url="https://i.imgur.com/EQvl6Lm.png", - title_url=rules_message, - ) - ) - case "rule13": - await message.reply( - embed=embeds.make_embed( - title="Rule 13: Do not discuss your sexual endeavors or relationships", - description=( - "Discussion of NSFW topics like sex and fetishes are not allowed " - "outside of NSFW channels. " - ), - color=0x7D98E9, - thumbnail_url="https://i.imgur.com/GgL8pPz.png", - title_url=rules_message, - ) - ) - - -async def setup(bot: commands.Bot) -> None: - await bot.add_cog(AutoresponderListeners(bot)) - log.info("Listeners Loaded: autoresponder") diff --git a/chiya/cogs/listeners/highlight.py b/chiya/cogs/listeners/highlight.py index 65b8b963..55eee7c5 100644 --- a/chiya/cogs/listeners/highlight.py +++ b/chiya/cogs/listeners/highlight.py @@ -6,8 +6,8 @@ from discord.ext import commands from loguru import logger as log -from chiya import database from chiya.config import config +from chiya.database import Highlight, Session from chiya.utils import embeds @@ -17,12 +17,10 @@ def __init__(self, bot: commands.Bot) -> None: self.refresh_highlights() def refresh_highlights(self): - db = database.Database().get() - self.highlights = [ - {"term": highlight["term"], "users": orjson.loads(highlight["users"])} - for highlight in db["highlights"].find() - ] - db.close() + with Session() as session: + self.highlights = [ + {"term": row.term, "users": orjson.loads(row.users)} for row in session.query(Highlight).all() + ] async def active_members(self, channel: discord.TextChannel) -> set: """ diff --git a/chiya/cogs/tasks/reminder.py b/chiya/cogs/tasks/reminder.py index 09f4a83c..5db56987 100644 --- a/chiya/cogs/tasks/reminder.py +++ b/chiya/cogs/tasks/reminder.py @@ -1,10 +1,9 @@ -from datetime import datetime, timezone +import arrow import discord - from discord.ext import commands, tasks from loguru import logger as log -from chiya import database +from chiya.database import RemindMe, Session from chiya.utils import embeds @@ -23,27 +22,26 @@ async def check_for_reminder(self) -> None: """ await self.bot.wait_until_ready() - db = database.Database().get() - result = db["remind_me"].find( - sent=False, date_to_remind={"<": datetime.now(tz=timezone.utc).timestamp()} - ) + with Session() as session: + result = session.query(RemindMe).filter(RemindMe.date_to_remind < arrow.utcnow().timestamp()) if not result: - return db.close() + return for reminder in result: try: - user = await self.bot.fetch_user(reminder["author_id"]) + user = await self.bot.fetch_user(reminder.author_id) except discord.errors.NotFound: - db["remind_me"].update(dict(id=reminder["id"], sent=True), ["id"]) - log.warning( - f"Reminder entry with ID {reminder['id']} has an invalid user ID: {reminder['author_id']}." - ) + with Session() as session: + result = session.query(RemindMe).filter_by(id=reminder.id).first() + result.sent = True + session.commit() + log.warning(f"Reminder entry with ID {reminder.id} has an invalid user ID: {reminder.author_id}.") continue embed = embeds.make_embed( title="Here is your reminder", - description=reminder["message"], + description=reminder.message, color="blurple", ) @@ -51,14 +49,12 @@ async def check_for_reminder(self) -> None: channel = await user.create_dm() await channel.send(embed=embed) except discord.Forbidden: - log.warning( - f"Unable to post or DM {user}'s reminder {reminder['id']=}." - ) - - db["remind_me"].update(dict(id=reminder["id"], sent=True), ["id"]) + log.warning(f"Unable to post or DM {user}'s reminder {reminder.id=}.") - db.commit() - db.close() + with Session() as session: + result = session.query(RemindMe).filter_by(id=reminder.id).first() + result.sent = True + session.commit() async def setup(bot: commands.Bot) -> None: diff --git a/chiya/database.py b/chiya/database.py index fde2b9ad..95ddda56 100644 --- a/chiya/database.py +++ b/chiya/database.py @@ -6,33 +6,12 @@ Base = declarative_base() -engine = create_engine(config.database.url, connect_args={"check_same_thread": False}) -session = sessionmaker(autocommit=False, autoflush=False, bind=engine) - - -class BaseModel(Base): - __abstract__ = True - - def save(self): - session.add(self) - session.commit() - return self - - def delete(self): - session.delete(self) - session.commit() - return self - - def flush(self): - session.add(self) - session.flush() - return self class ModLog(Base): __tablename__ = "mod_logs" - id = Column(Integer, primar_key=True) + id = Column(Integer, primary_key=True) user_id = Column(BigInteger, nullable=False) mod_id = Column(BigInteger, nullable=False) timestamp = Column(BigInteger, nullable=False) @@ -44,7 +23,7 @@ class ModLog(Base): class RemindMe(Base): __tablename__ = "remind_me" - id = Column(Integer, primar_key=True) + id = Column(Integer, primary_key=True) reminder_location = Column(BigInteger, nullable=False) author_id = Column(BigInteger, nullable=False) date_to_remind = Column(BigInteger, nullable=False) @@ -80,3 +59,8 @@ class Highlight(Base): id = Column(Integer, primary_key=True) term = Column(Text, nullable=False) users = Column(Text, nullable=False) + + +engine = create_engine(config.database.url, connect_args={"check_same_thread": False}) +Session = sessionmaker(bind=engine) +Base.metadata.create_all(engine)