generalized the cancellation leaderboard

This commit is contained in:
2021-08-11 17:11:30 -05:00
parent 89d9bdcf7b
commit b6d41b6ba5
2 changed files with 49 additions and 35 deletions

43
msg.py
View File

@@ -88,23 +88,28 @@ class MsgData:
LOGGER.info(f'\n{str(new)}')
def emoji_messages(self, emoji_name: str, days: int):
return emoji_messages(msg_df=self.msgs, react_df=self.reactions, emoji_name=emoji_name, days=days)
res = emoji_messages(msg_df=self.msgs, react_df=self.reactions, emoji_name=emoji_name, days=days)
if res is None:
raise KeyError(f'No emojis found for {emoji_name}')
else:
return res
def emoji_totals(self, emoji_name: str, days: int):
return emoji_totals(edf=self.emoji_messages(emoji_name, days))
def cancellation_leaderboard(self, days, top: int = None):
df = self.emoji_totals('cancelled', days)
if top is not None:
df = df.iloc[:top]
def emoji_leaderboard(self, emoji_name: str, days: int):
df = self.emoji_totals(emoji_name, days)
width = max(list(map(lambda s: len(str(s)), df.index.values)))
res = f'Cancellation totals, past {days} days\n'
res = f'{emoji_name} totals, past {days} days\n'
res += '\n'.join(
f"`{name.ljust(width + 1)}with {row['total']:<2.0f} total`"
f"`{str(name).ljust(width + 1)}with {row['total']:<2.0f} total`"
for name, row in df.iterrows()
)
return res
def cancellation_leaderboard(self, days):
return self.emoji_leaderboard(emoji_name='cancelled', days=days)
def worst_offsenses(self, user: str, days: int):
cdf = self.emoji_messages('cancelled', days=days)
cdf = cdf[cdf['display_name'].str.contains(user, case=False)]
@@ -139,6 +144,7 @@ class MsgData:
LOGGER.info(f'User: {user.mention}')
return f'{user.mention} with {data.iloc[0]["total"]:.0f} over the past {int(days)} days'
def convert_emoji(emoji):
try:
emoji.name.encode('ascii')
@@ -146,6 +152,7 @@ def convert_emoji(emoji):
emoji.name = emoji.name.encode('unicode-escape').decode('ascii')
return emoji
async def message_df(client: discord.Client, **kwargs):
return pd.DataFrame(
[message_dict(m) async for m in message_gen(client, **kwargs)]
@@ -182,7 +189,8 @@ def message_dict(m: discord.Message) -> Dict:
async def reaction_df(msgs: Iterable[discord.Message]):
return pd.concat([await reaction_series(msg) for msg in msgs if len(msg.reactions) > 0]).set_index(['msg id', 'emoji'])
return pd.concat([await reaction_series(msg) for msg in msgs if len(msg.reactions) > 0]).set_index(
['msg id', 'emoji'])
async def reaction_series(msg: discord.Message):
@@ -205,23 +213,28 @@ async def reaction_dict(r: discord.Reaction) -> Dict:
def emoji_messages(msg_df, react_df, emoji_name: str, days: int = 10) -> pd.DataFrame:
# get reactions with a cancellation emoji
try:
cached_emojis = react_df.index.get_level_values(1).drop_duplicates().values
if emoji_name in cached_emojis:
reactions = react_df.loc[pd.IndexSlice[:, emoji_name], :]
except KeyError as e:
LOGGER.error(f'Emoji not found in reactions DataFrame: {emoji_name}')
else:
reacted_msgs = msg_df.loc[reactions.index.get_level_values(0).to_list()]
if reacted_msgs.shape[0] == 0:
LOGGER.error(f'No messages found with {emoji_name} reactions')
else:
LOGGER.info(
f'Found {reacted_msgs.shape[0]} messages for the leaderboard, {reactions["count"].sum():.0f} reactions total')
reacted_msgs['count'] = reacted_msgs.index.to_series().apply(
lambda idx: reactions.loc[pd.IndexSlice[idx, emoji_name], 'count'])
# filter outdated messages
reacted_msgs = reacted_msgs[reacted_msgs['created'] >= (datetime.today() - timedelta(days=days)).astimezone()]
reacted_msgs = reacted_msgs[
reacted_msgs['created'] >= (datetime.today() - timedelta(days=days)).astimezone()]
reacted_msgs = reacted_msgs.sort_values('count', ascending=False)
return reacted_msgs
else:
LOGGER.error(f'Emoji not found in reactions DataFrame: {emoji_name}')
def emoji_totals(edf: pd.DataFrame) -> pd.DataFrame:

View File

@@ -25,7 +25,8 @@ class RoboPage(discord.Client):
attrs = map(lambda n: getattr(jokes, n)(), attrs)
self.jokes = list(attrs)
self.lock = Lock()
self.emoji_regex = re.compile("^who is the most (?P<emoji>\w+)(?: in the past (?P<days>\d+) days)?\??$", re.IGNORECASE)
self.emoji_regex = re.compile("^who is the most (?P<emoji>\w+)(?: in the past (?P<days>\d+) days)?\??$",
re.IGNORECASE)
self.leaderboard_regex = re.compile('^most (?P<emoji>\w+) leaderboard$', re.IGNORECASE)
def run(self):
@@ -50,12 +51,9 @@ class RoboPage(discord.Client):
await self.data.add_msg(message)
if message.author != self.user:
if 'most cancelled' in message.content:
await message.reply(self.data.cancellation_leaderboard(days=14))
elif (m := re.search('top cancelled (?P<name>\w+)', message.content)) is not None:
async with self.data.lock:
await message.reply(self.data.worst_offsenses(user=m.group('name'), days=14))
try:
if (m := self.leaderboard_regex.match(message.content)) is not None:
await message.reply(self.data.emoji_leaderboard(emoji_name=m.group('emoji'), days=14))
elif (m := self.emoji_regex.match(message.content)) is not None:
days = m.group('days') or 14
@@ -67,6 +65,9 @@ class RoboPage(discord.Client):
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)
except Exception as e:
# await message.reply('oops')
raise
if __name__ == '__main__':