From 0fb04604dc1fbd863c16a8f53137260bf21b4380 Mon Sep 17 00:00:00 2001 From: klemek Date: Wed, 13 Nov 2019 14:19:22 +0100 Subject: [PATCH] v1.0 stable features --- bot.py | 31 ++++++++-- emotes.py | 178 ++++++++++++++++++++++++++---------------------------- help.py | 23 +++++++ utils.py | 21 +++++++ 4 files changed, 156 insertions(+), 97 deletions(-) create mode 100644 help.py create mode 100644 utils.py diff --git a/bot.py b/bot.py index 52e52c5..1ad9864 100644 --- a/bot.py +++ b/bot.py @@ -1,21 +1,27 @@ import os import discord -import emotes +from datetime import datetime from dotenv import load_dotenv +import emotes +import help +from utils import debug load_dotenv() token = os.getenv('DISCORD_TOKEN') client = discord.Client() +VERSION = "1.0" + +t0 = datetime.now() @client.event async def on_ready(): await client.change_presence( - activity=discord.Game("%emotes help"), + activity=discord.Game(f"v{VERSION} | %help"), status=discord.Status.online ) - print(f'{client.user} has connected to Discord\nto the following guilds:') + print(f'{client.user} v{VERSION} has connected to Discord\nto the following guilds:') for guild in client.guilds: print(f'- {guild.name}(id: {guild.id})') @@ -25,9 +31,26 @@ async def on_message(message): if message.author == client.user: return + permissions = message.channel.permissions_for(message.guild.me) + if not permissions.send_messages: + debug(message, f"missing 'send_messages' permission") + await message.author.create_dm() + await message.author.dm_channel.send( + f"Hi, this bot doesn\'t have the permission to send a message to" + f" #{message.channel} in server '{message.guild}'") + return + args = message.content.split(" ") + if args[0] == "%info": + debug(message, f"command '{message.content}'") + await message.channel.send(f"Discord Analyst v{VERSION} started at {t0.isoformat()}") + + if args[0] == "%help": + await help.compute(message, args) + if args[0] == "%emotes": - await emotes.compute(client, message, args) + await emotes.compute(message, args) + client.run(token) diff --git a/emotes.py b/emotes.py index 453e920..3c646bb 100644 --- a/emotes.py +++ b/emotes.py @@ -1,10 +1,8 @@ from datetime import datetime import discord import re - - -def debug(message, txt): - print(f"{message.guild} > #{message.channel}: {txt}") +import help +from utils import debug, aggregate, no_duplicate # CLASSES @@ -17,6 +15,10 @@ class Emote: self.reactions = 0 self.last_used = None + def update_use(self, date): + if self.last_used is None or date > self.last_used: + self.last_used = date + def used(self): return self.usages > 0 or self.reactions > 0 @@ -36,34 +38,62 @@ class Emote: # ANALYSIS -async def analyse_channel(client, channel, emotes, member, progress, delta, nc): +async def analyse_channel(channel, emotes, members, progress, delta, nc): nm = 0 + nmm = 0 try: async for m in channel.history(limit=None): - if member is None and m.author != client.user or m.author == member: + if not m.author.bot and (len(members) == 0 or m.author in members): found = [name for name in re.findall(r"(<:\w+:\d+>)", m.content) if name in emotes] for name in found: emotes[name].usages += 1 - if emotes[name].last_used is None: - emotes[name].last_used = m.created_at - if member is None: - for reaction in m.reactions: - name = str(reaction.emoji) - if not (isinstance(reaction.emoji, str)) and name in emotes: - emotes[name].reactions += reaction.count - if emotes[name].last_used is None: - emotes[name].last_used = m.created_at - nm += 1 - if (delta + nm) % 1000 == 0: - await progress.edit(content=f"```{(delta + nm) // 1000}k messages and {nc} channels analysed```") - return nm + emotes[name].update_use(m.created_at) + nmm += 1 + if len(members) == 0: + for reaction in m.reactions: + name = str(reaction.emoji) + if not (isinstance(reaction.emoji, str)) and name in emotes: + emotes[name].reactions += reaction.count + emotes[name].update_use(m.created_at) + nm += 1 + if (delta + nm) % 1000 == 0: + await progress.edit(content=f"```{(delta + nm) // 1000}k messages and {nc} channels analysed```") + return nm, nmm except discord.errors.Forbidden: - return -1 + return -1, -1 # RESULTS +def get_message(emotes, full, channels, members, nmm, nc): + if len(members) == 0: + if full: + return f"{len(emotes)} emotes in this server ({nc} channels, {nmm} messages):" + elif len(channels) < 5: + return f"{aggregate([c.mention for c in channels])} emotes usage in {nmm} messages:" + else: + return f"These {len(channels)} channels emotes usage in {nmm} messages:" + elif len(members) < 5: + if full: + return f"{aggregate([m.mention for m in members])} emotes usage in {nmm} messages:" + elif len(channels) < 5: + return f"{aggregate([m.mention for m in members])} on {aggregate([c.mention for c in channels])} " \ + f"emotes usage in {nmm} messages:" + else: + return f"{aggregate([m.mention for m in members])} on these {len(channels)} channels " \ + f"emotes usage in {nmm} messages:" + else: + if full: + return f"These {len(members)} members emotes usage in {nmm} messages:" + elif len(channels) < 5: + return f"These {len(members)} members on {aggregate([c.mention for c in channels])} " \ + f"emotes usage in {nmm} messages:" + else: + return f"These {len(members)} members on these {len(channels)} channels " \ + f"emotes usage in {nmm} messages:" + + def get_place(n): if n == 0: return ":first_place:" @@ -110,16 +140,19 @@ def get_last_used(emote): return f"(last used {emote.use_days()} days ago)" -def get_total(emotes): +def get_total(emotes, nmm): nu = 0 nr = 0 for name in emotes: nu += emotes[name].usages nr += emotes[name].reactions - return f"Total: {nu} times and {nr} reactions" + if nr > 0: + return f"Total: {nu} times ({round(nu / nmm, 4)} / message) and {nr} reactions" + else: + return f"Total: {nu} times ({round(nu / nmm, 4)} / message)" -async def tell_results(first, emotes, channel, *, allow_unused, show_life): +async def tell_results(first, emotes, channel, nmm, *, allow_unused, show_life): names = [name for name in emotes] names.sort(key=lambda name: emotes[name].score(), reverse=True) res = [first] @@ -127,10 +160,10 @@ async def tell_results(first, emotes, channel, *, allow_unused, show_life): f"{get_place(names.index(name))} {name} - " f"{get_usage(emotes[name])}" f"{get_reactions(emotes[name])}" - # f"{get_life(emotes[name], show_life)}" + f"{get_life(emotes[name], show_life)}" f"{get_last_used(emotes[name])}" for name in names if allow_unused or emotes[name].used()] - res += [get_total(emotes)] + res += [get_total(emotes, nmm)] response = "" for r in res: if len(response + "\n" + r) > 2000: @@ -144,79 +177,38 @@ async def tell_results(first, emotes, channel, *, allow_unused, show_life): # MAIN -async def compute(client, message, args): +async def compute(message, args): debug(message, f"command '{message.content}'") guild = message.guild - permissions = message.channel.permissions_for(guild.me) - if not permissions.send_messages: - debug(message, f"missing 'send_messages' permission") - await message.author.create_dm() - await message.author.dm_channel.send( - f"Hi, this bot doesn\'t have the permission to send a message to" - f" #{message.channel} in server '{message.guild}'") + if len(args) > 1 and args[1] == "help": + await help.compute(message, ["%help", "emotes"]) return emotes = {str(emoji): Emote(emoji) for emoji in guild.emojis} - if len(args) == 1: - async with message.channel.typing(): - nm = 0 - nc = 0 - t0 = datetime.now() - progress = await message.channel.send(f"```starting analysis...```") - for channel in guild.text_channels: - nm1 = await analyse_channel(client, channel, emotes, None, progress, nm, nc) - if nm1 >= 0: - nm += nm1 - nc += 1 - await progress.delete() - await tell_results(f"{len(emotes)} emotes in this server ({nc} channels, {nm} messages):", - emotes, message.channel, allow_unused=True, show_life=True) - dt = (datetime.now() - t0).total_seconds() - debug(message, f"response sent {dt} s -> {nm / dt} m/s") - elif len(message.mentions) > 0: - if len(args) > 2: - await message.channel.send("Too many arguments") - else: - member = message.mentions[0] - nm = 0 - nc = 0 - progress = await message.channel.send(f"```starting analysis...```") - for channel in guild.text_channels: - nm1 = await analyse_channel(client, channel, emotes, member, progress, nm, nc) - if nm1 >= 0: - nm += nm1 - nc += 1 - await progress.delete() - await tell_results( - f"{member.mention} emotes usage in {nm} messages:", emotes, - message.channel, allow_unused=False, show_life=False) - debug(message, f"response sent") - elif len(message.channel_mentions) > 0: - if len(args) > 2: - await message.channel.send("too many arguments") - else: - channel = message.channel_mentions[0] - progress = await message.channel.send(f"```starting analysis...```") - nm = await analyse_channel(client, channel, emotes, None, progress, 0, 0) - await progress.delete() - if nm < 0: - await message.channel.send(f"I'm sorry I could not read messages in {channel.mention}") - debug(message, f"cannot read channel") - return - await tell_results( - f"{channel.mention} emotes usage in {nm} messages:", emotes, - message.channel, allow_unused=False, show_life=False) - debug(message, f"response sent") - elif args[1] == "help": - await message.channel.send( - "Emotes Analysis:\n" - "```" - "%emotes : Rank emotes by their usage\n" - "%emotes @user : // for a specific user" - "%emotes #channel : // for a specific channel" - "```") - else: - await message.channel.send(f"Unknown command : type `%emotes help` for more info") + channels = no_duplicate(message.channel_mentions) + full = len(channels) == 0 + if full: + channels = guild.text_channels + + members = no_duplicate(message.mentions) + + async with message.channel.typing(): + nm = 0 + nmm = 0 + nc = 0 + t0 = datetime.now() + progress = await message.channel.send(f"```starting analysis...```") + for channel in channels: + nm1, nmm1 = await analyse_channel(channel, emotes, members, progress, nm, nc) + if nm1 >= 0: + nm += nm1 + nmm += nmm1 + nc += 1 + await progress.delete() + await tell_results(get_message(emotes, full, channels, members, nmm, nc), + emotes, message.channel, nmm, allow_unused=full and len(members) == 0, show_life=False) + dt = (datetime.now() - t0).total_seconds() + debug(message, f"response sent {dt} s -> {nm / dt} m/s") diff --git a/help.py b/help.py new file mode 100644 index 0000000..c3d56c2 --- /dev/null +++ b/help.py @@ -0,0 +1,23 @@ +from utils import debug + + +async def compute(message, args): + debug(message, f"command '{message.content}'") + if len(args) > 1 and args[1] == "emotes": + await message.channel.send( + "Emotes Analysis:\n" + "```" + "%emotes : Rank emotes by their usage\n" + "%emotes @user : // for a specific user\n" + "%emotes #channel : // for a specific channel\n" + "(Add more @user or #channel to be more selective)" + "```") + return + else: + await message.channel.send( + "Discord Analyst commands:\n" + "```" + "%help (command) : Info on commands\n" + "%info : This bot info\n" + "%emotes : Emotes analysis" + "```") diff --git a/utils.py b/utils.py new file mode 100644 index 0000000..339c0b5 --- /dev/null +++ b/utils.py @@ -0,0 +1,21 @@ +# DISCORD API + +def debug(message, txt): + print(f"{message.guild} > #{message.channel}: {txt}") + + +# LISTS + +def no_duplicate(seq): + return list(dict.fromkeys(seq)) + + +# MESSAGE FORMATTING + +def aggregate(names): + if len(names) == 0: + return "" + elif len(names) == 1: + return names[0] + else: + return ", ".join(names[:-1]) + " & " + names[-1]