diff --git a/db.py b/db.py index fcd286c9..5cec329a 100644 --- a/db.py +++ b/db.py @@ -7,6 +7,7 @@ import requests from errors import RequestError, NotFoundError, AlreadyExistingError import re import enum +from discord import User as DiscordUser # Init the config reader import configparser @@ -452,7 +453,25 @@ class Discord(Base): return f"{self.username}#{self.discriminator}" def __repr__(self): - return f"" + return f"" + + @staticmethod + def create(royal_username, discord_user: DiscordUser): + d = session.query(Discord).filter(Discord.discord_id == discord_user.id).first() + if d is not None: + raise AlreadyExistingError(repr(d)) + r = session.query(Royal).filter(Royal.username == royal_username).first() + if r is None: + raise NotFoundError("No Royal exists with that username") + d = session.query(Discord).filter(Discord.royal_id == r.id).first() + if d is not None: + raise AlreadyExistingError(repr(d)) + d = Discord(royal=r, + discord_id=discord_user.id, + name=discord_user.name, + discriminator=discord_user.discriminator, + avatar_hex=discord_user.avatar) + return d def mention(self): return f"<@{self.id}>" diff --git a/discordbot.py b/discordbot.py new file mode 100644 index 00000000..40cd9177 --- /dev/null +++ b/discordbot.py @@ -0,0 +1,38 @@ +import discord +from discord.ext import commands +import db +import re +import errors + +# Init the event loop +import asyncio +loop = asyncio.get_event_loop() + +# Init the config reader +import configparser +config = configparser.ConfigParser() +config.read("config.ini") + +# Init the discord bot +client = discord.Client() + +@client.event +async def on_message(message: discord.Message): + if message.content.startswith("!register"): + try: + username = message.content.split(" ", 1)[1] + except IndexError: + await client.send_message(message.channel, "⚠️ Non hai specificato un username!") + return + try: + d = db.Discord.create(royal_username=username, + discord_user=message.author) + except errors.AlreadyExistingError: + await client.send_message(message.channel, "⚠ Il tuo account Discord è già collegato a un account RYG o l'account RYG che hai specificato è già collegato a un account Discord.") + return + db.session.add(d) + db.session.commit() + await client.send_message(message.channel, "✅ Sincronizzazione completata!") + +client.run(config["Discord"]["bot_token"]) +db.session.close() \ No newline at end of file