import os import re import discord from discord.ext import commands from dotenv import load_dotenv from simpleeval import simple_eval, InvalidExpression load_dotenv() COUNTING_CHANNEL_ID = int(os.getenv("COUNTING_CHANNEL_ID")) _MATH_CHARS = re.compile(r"[^\d\+\-\*\/\(\)\^\%\.\s]") def solve_string(content: str) -> int | None: expr = _MATH_CHARS.sub("", content) expr = expr.strip() if not expr or not any(ch.isdigit() for ch in expr): return None try: value = simple_eval(expr) except (InvalidExpression, ZeroDivisionError, ValueError, SyntaxError, TypeError, KeyError): return None if isinstance(value, bool): return None try: return int(value) except (TypeError, ValueError): return None class Counting(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot @commands.Cog.listener() async def on_message(self, message: discord.Message): if not message or not message.author or message.webhook_id is not None: return if message.author.bot: return if message.channel.id != COUNTING_CHANNEL_ID: return db = await self.bot.database.get_conn() try: async with db.execute( "SELECT count, user_id FROM count ORDER BY count DESC LIMIT 1" ) as cursor: result = await cursor.fetchone() if result is None: expected = 1 previous_user_id = None else: expected = result[0] + 1 previous_user_id = result[1] parsed = solve_string(message.content) is_correct = ( parsed is not None and parsed == expected and previous_user_id != str(message.author.id) ) if not is_correct: try: await message.delete() except discord.NotFound: pass return await db.execute( "INSERT INTO count (user_id) VALUES (?)", (str(message.author.id),) ) await db.commit() await message.add_reaction("✅") except Exception as e: print(f"Database error: {e}") try: await message.delete() except discord.NotFound: pass async def setup(bot: commands.Bot): await bot.add_cog(Counting(bot))