import logging import os import re from threading import Lock import discord from dotenv import load_dotenv from jokes import CumJoke, BlackJoke, AssJoke, DominosJoke from msg import get_and_save, cancellations, cancelled_totals, report_string logging.basicConfig(level=logging.INFO) LIL_STINKY_ID = 704043422276780072 class RoboPage(discord.Client): db_path: str = 'messages.db' def __init__(self, *args, **kwargs): super(RoboPage, self).__init__(*args, **kwargs) self.jokes = [ CumJoke(), BlackJoke(), AssJoke(), DominosJoke() ] self.lock = Lock() def run(self): return super().run(os.getenv('DISCORD_TOKEN')) async def handle_ready(self): channel: discord.TextChannel = discord.utils.get(self.get_all_channels(), name='robotics-facility') await channel.send(f"I'm aliiiiiive {discord.utils.get(self.emojis, name='kaylon')}") async def handle_message(self, message): if message.author != self.user: if 'most cancelled' in message.content: msg: discord.Message = await message.reply('Hold please...') await message.reply(await self.get_cancelled_totals(limit=1000, days=14)) elif (m := re.search('top cancelled (?P\w+)', message.content)) is not None: if self.lock.acquire(blocking=False): msg: discord.Message = await message.reply('Hold please...') await message.reply(await self.top_cancellations(user=m.group('name'), limit=1000, days=14)) self.lock.release() else: await message.reply("I'm busy!") for joke in self.jokes: if (scan_res := joke.scan(message)): print(f'{joke.__class__.__name__} detected:\n{message.content}\n{scan_res}') await joke.respond(message, self, scan_res) async def get_cancelled_totals(self, limit=1000, days: int = 90): msg_df, react_df = await get_and_save(self.db_path, client=self, limit=limit, days=days) res = cancelled_totals(cancellations(msg_df, react_df, days=days)) res = f'Cancellation totals, past {days} days\n' + report_string(res.iloc[:5]) return res async def top_cancellations(self, user: str, limit: int, days: int): msg_df, react_df = await get_and_save(self.db_path, client=self, limit=limit, days=days) cdf = cancellations(msg_df, react_df, days=days) cdf = cdf[cdf['display_name'].str.contains(user, case=False)] if cdf.shape[0] > 0: res = f'{user}\'s top 5 cancellations in the last {days} days:\n' res += f'\n'.join(f'`{row["count"]} cancellations`\n{row["link"]}' for idx, row in cdf.iloc[:5].iterrows()) else: res = f'No cancellations in the past {days} days' return res if __name__ == '__main__': load_dotenv() client = RoboPage() @client.event async def on_ready(): print(f'{client.user} has connected to Discord!') # await client.handle_ready() # await get_and_save(RoboPage.db_path, client=client, limit=5000, days=7) # msg_df, react_df = await get_and_save('messages.db', client=client, limit=5000, days=90) @client.event async def on_message(message: discord.Message): await client.handle_message(message) client.run()