reworked update_reaction and emoji calculation. Should work with unicode emojis now

This commit is contained in:
2021-08-15 11:55:49 -05:00
parent 1fd0699d8e
commit 9d41c2bdf1
2 changed files with 32 additions and 31 deletions

View File

@@ -82,9 +82,9 @@ class MsgData:
LOGGER.info(f'Added message id {message.id} from {message.author}: {message.content}') LOGGER.info(f'Added message id {message.id} from {message.author}: {message.content}')
async def update_reaction(self, msg: discord.Message): async def update_reaction(self, msg: discord.Message):
async with self.lock:
# Drop all the reactions for this message id, if there are any # Drop all the reactions for this message id, if there are any
try: try:
async with self.lock:
self.reactions.drop(msg.id, level=0, axis=0, inplace=True) self.reactions.drop(msg.id, level=0, axis=0, inplace=True)
except KeyError as e: except KeyError as e:
pass pass
@@ -92,6 +92,7 @@ class MsgData:
# If there are reactions on the message after the change # If there are reactions on the message after the change
if len(msg.reactions) > 0: if len(msg.reactions) > 0:
new = reaction_df(msg) new = reaction_df(msg)
async with self.lock:
self.reactions = pd.concat([self.reactions, new]) self.reactions = pd.concat([self.reactions, new])
LOGGER.info(str(new.droplevel(level=0, axis=0).loc[:, 'count'])) LOGGER.info(str(new.droplevel(level=0, axis=0).loc[:, 'count']))
@@ -102,7 +103,7 @@ class MsgData:
def emoji_messages(self, emoji_name: str, days: int = None) -> pd.DataFrame: def emoji_messages(self, emoji_name: str, days: int = None) -> pd.DataFrame:
"""Creates a DataFrame of the messages that have reactions with a certain emoji. Includes a 'count' column""" """Creates a DataFrame of the messages that have reactions with a certain emoji. Includes a 'count' column"""
counts: pd.DataFrame = self.emoji_counts(emoji_name) counts: pd.Series = self.emoji_counts(emoji_name)
# Get the ids of messages that that have the targeted emoji # Get the ids of messages that that have the targeted emoji
message_id_counts: pd.Index = counts.index.drop_duplicates() message_id_counts: pd.Index = counts.index.drop_duplicates()
@@ -117,10 +118,11 @@ class MsgData:
res['count'] = counts res['count'] = counts
if days is not None: if days is not None and days > 0:
res = res[res['created'] >= (datetime.today() - timedelta(days=days)).astimezone()] res = res[res['created'] >= (datetime.today() - timedelta(days=days)).astimezone()]
return res.sort_values('created', ascending=False) return res.sort_values('created', ascending=False)
else: else:
raise KeyError(f'No messages found with {emoji_name} reactions') raise KeyError(f'No messages found with {emoji_name} reactions')

View File

@@ -1,9 +1,8 @@
import json
import logging import logging
import os import os
import re import re
from pathlib import Path
from typing import Union from typing import Union
import discord import discord
from discord import RawReactionActionEvent, RawReactionClearEmojiEvent from discord import RawReactionActionEvent, RawReactionClearEmojiEvent
from dotenv import load_dotenv from dotenv import load_dotenv
@@ -28,16 +27,13 @@ class RoboPage(discord.Client):
self.jokes = list(attrs) self.jokes = list(attrs)
self.most_regex = re.compile( self.most_regex = re.compile(
"^who is the most (?P<emoji>\w+)(?: in the past (?P<days>\d+) days)?\??$", "^who is the most (?P<emoji>\w+)(?: in the past (?P<days>\d+) days)?\??$",
re.IGNORECASE re.IGNORECASE & re.UNICODE,
) )
self.leaderboard_regex = re.compile( self.leaderboard_regex = re.compile(
'^most (?P<emoji>\w+)(?=(?:.+)?leaderboard)(?:.+(?P<days>\d+) days)?', '^most (?P<emoji>.+)(?=(?:.+)?leaderboard)(?:.+(?P<days>\d+) days)?',
re.IGNORECASE re.IGNORECASE & re.UNICODE
) )
with Path('gifs.json').open('r') as file:
self.gifs = json.load(file)
def run(self): def run(self):
return super().run(os.getenv('DISCORD_TOKEN')) return super().run(os.getenv('DISCORD_TOKEN'))
@@ -48,9 +44,10 @@ class RoboPage(discord.Client):
self.data: data.MsgData = await data.MsgData.create( self.data: data.MsgData = await data.MsgData.create(
client=self, client=self,
# limit=5000, limit=5000,
limit=20, days=30,
# days=30, # limit=500,
# days=3,
) )
self.data.to_sql('messages.db') self.data.to_sql('messages.db')
LOGGER.info(f'{self.data.msgs.shape[0]} messages total') LOGGER.info(f'{self.data.msgs.shape[0]} messages total')
@@ -62,11 +59,11 @@ class RoboPage(discord.Client):
await self.data.add_msg(message) await self.data.add_msg(message)
if (m := self.leaderboard_regex.match(message.content)) is not None: if (m := self.leaderboard_regex.match(message.content)) is not None:
days = int(m.group('days')) or 14 days = m.group('days') or 14
emoji = m.group('emoji').lower() emoji = m.group('emoji').lower().strip()
try: try:
await message.reply( await message.reply(
await self.data.emoji_leaderboard(client=self, emoji_name=emoji, days=days) await self.data.emoji_leaderboard(client=self, emoji_name=emoji, days=int(days))
) )
except KeyError as e: except KeyError as e:
LOGGER.exception(e) LOGGER.exception(e)
@@ -74,14 +71,16 @@ class RoboPage(discord.Client):
return return
elif (m := self.most_regex.match(message.content)) is not None: elif (m := self.most_regex.match(message.content)) is not None:
days = int(m.group('days')) or 14 days = m.group('days') or 14
emoji = m.group('emoji').lower() emoji = m.group('emoji').lower().strip()
try: try:
await message.reply( await message.reply(
await self.data.biggest_single(client=self, emoji=emoji, days=days)) await self.data.biggest_single(client=self, emoji=emoji, days=int(days)))
except IndexError as e: except IndexError as e:
await message.reply('NObody') await message.reply('NObody')
return return
else:
LOGGER.warning(f'No self.data attribute')
for joke in self.jokes: for joke in self.jokes:
if (scan_res := joke.scan(message)): if (scan_res := joke.scan(message)):