Quality of life improvments

This commit is contained in:
Luis Mayo Valbuena 2021-05-27 21:23:18 +02:00
parent 6ac1759d58
commit 9ff8b0e7c5
4 changed files with 81 additions and 49 deletions

2
.gitignore vendored
View File

@ -10,4 +10,4 @@ db.json
# Ignore the assets # Ignore the assets
assets/ assets/
token.txt config.yaml

2
config.yaml Normal file
View File

@ -0,0 +1,2 @@
token: ""
prefix: "!"

125
main.py
View File

@ -1,71 +1,100 @@
import random
import os
import sys import sys
sys.path.insert(0, './ace-attorney-bot') sys.path.insert(0, './ace-attorney-bot')
import anim import anim
import yaml
import discord import discord
import re from discord.ext import commands
from message import Message from message import Message
from collections import Counter from collections import Counter
from comment_bridge import Comment from comment_bridge import Comment
import os
if not os.path.isfile("config.yaml"):
sys.exit("'config.yaml' is missing!")
else:
with open("config.yaml") as file:
configuration = yaml.load(file, Loader=yaml.FullLoader)
token = configuration["token"].strip()
prefix = configuration["prefix"].strip()
with open('token.txt', 'r') as tokenFile: if not token:
token = tokenFile.read().replace('\r', '').replace('\n', '') sys.exit("The 'token' is missing in the 'config.yaml' file!")
if not prefix:
sys.exit("The 'prefix' is missing in the 'config.yaml' file!")
client = commands.Bot(command_prefix=prefix, intents=discord.Intents.default())
# Removing default help command
client = discord.Client() client.remove_command("help")
@client.event @client.event
async def on_ready(): async def on_ready():
game = discord.Game("use: !render <number of messages> | !render 2") print("Bot is ready!")
await client.change_presence(activity=game) print(f"Logged in as {client.user.name}#{client.user.discriminator} ({client.user.id})")
activity = discord.Game(f"{prefix}help")
await client.change_presence(activity=activity)
@client.event @client.event
async def on_message(mention: discord.Message): async def on_message(message):
if mention.author == client.user: # Ignore message if the author is a bot (or the client's logged user)
if message.author is client.user or message.author.bot:
return
if message.channel.type is discord.ChannelType.private:
embedResponse = discord.Embed(description="I won't process any messages via PM.\nIf you have any problem please go to [the support server](https://discord.gg/pcS4MPbRDU).", color=0xff0000)
await message.channel.send(embed=embedResponse)
return return
if mention.guild == None: await client.process_commands(message)
await mention.channel.send(content='I can\'t process any messages via PM. If you have any problem please go to the support server. https://discord.gg/pcS4MPbRDU')
return
match = re.match(r'!render (\d+)', mention.content) @client.command()
if match: async def help(context):
async with mention.channel.typing(): dummyAmount = random.randint(2, 150)
number = int(match.group(1)) embedHelp = discord.Embed(description="Discord bot that turns message chains into ace attorney scenes.", color=0x3366CC, footer="Do not include these symbols (\"<\" and \">\") when using this command")
if (number < 2 or number > 150): embedHelp.set_author(name=client.user.name, icon_url=client.user.avatar_url)
await mention.channel.send(content='Number of messages must be between 2 and 150') embedHelp.add_field(name="How to use?", value=f"`{prefix}render <number_of_messages>`", inline=False)
return embedHelp.add_field(name="Example", value=f"Turn the last {dummyAmount} messages into an ace attorney scene: `{prefix}render {dummyAmount}`", inline=False)
messages = [] embedHelp.add_field(name="Starting message", value="By default the bot will load the specified number of messages from the last message (before using the command) going backwards, if you want the message count to start from another message, reply to it when using the command.", inline=False)
async for message in mention.channel.history(limit=number, oldest_first=False, before=mention.reference.resolved if mention.reference else mention): await context.send(embed=embedHelp)
msg = Message(message)
if msg.text.strip(): @client.command()
messages.insert(0, msg) async def render(context, numberOfMessages):
if numberOfMessages.isdigit() and int(numberOfMessages) in range (2, 151):
messages = []
async for message in context.channel.history(limit=int(numberOfMessages), oldest_first=False, before=context.message.reference.resolved if context.message.reference else context.message):
msg = Message(message)
if msg.text.strip():
messages.insert(0, msg)
thread = [] thread = []
users_to_names = {} users_to_names = {}
counter = Counter() counter = Counter()
for message in messages: for message in messages:
thread.append(Comment(message)) thread.append(Comment(message))
users_to_names[message.user.id] = message.user.name users_to_names[message.user.id] = message.user.name
counter.update({message.user.id: 1}) counter.update({message.user.id: 1})
if (len(users_to_names) >= 2): if (len(users_to_names) >= 2):
most_common = [users_to_names[t[0]] for t in counter.most_common()] most_common = [users_to_names[t[0]] for t in counter.most_common()]
characters = anim.get_characters(most_common) characters = anim.get_characters(most_common)
output_filename = str(mention.id) + '.mp4' output_filename = str(context.message.id) + '.mp4'
anim.comments_to_scene(thread, characters, output_filename=output_filename) anim.comments_to_scene(thread, characters, output_filename=output_filename)
try:
await context.send(file=discord.File(output_filename))
except Exception as e:
try: try:
await mention.channel.send(file=discord.File(output_filename)) embedResponse = discord.Embed(description=f"Error: {e}", color=0xff0000)
except Exception as e: await context.send(embed=embedResponse, mention_author=False)
try: except Exception:
await mention.channel.send("Error: {e}".format(e=e)) pass
except Exception: clean(thread, output_filename)
pass else:
clean(thread, output_filename) embedResponse = discord.Embed(description="There should be at least two people in the conversation", color=0xff0000)
else: await context.send(embed=embedResponse, mention_author=False)
await mention.channel.send(content='There should be at least two people in the conversation') else:
embedResponse = discord.Embed(description="Number of messages must be between 2 and 150", color=0xff0000)
await context.reply(embed=embedResponse, mention_author=False)
return
def clean(thread, output_filename): def clean(thread, output_filename):
try: try:
@ -79,4 +108,4 @@ def clean(thread, output_filename):
except Exception as second_e: except Exception as second_e:
print(second_e) print(second_e)
client.run(token) client.run(configuration["token"])

View File

@ -1,2 +1,3 @@
discord.py discord.py
emoji emoji
pyyaml