예제 #1
0
    async def on_message(self, message: discord.Message):

        # Ignore other bot messages
        if (message.author.bot):
            return

        # If server isnt in the database, then create it
        if BotUtils.isPublicChannel(type(message.channel)) and not self.Database.GetFromTable("Guilds", f"ID = {message.guild.id}"):
            newGuild = self.Database.AddToTable(
                "Guilds",
                ID = message.guild.id,
                OwnerId = message.guild.owner_id,
                EnabledCommands = (True, True),
                commands_prefix = "~"
            )
            if newGuild:
                Logger.Log("Created new guild entry into the database.")

        if BotUtils.isPublicChannel(type(message.channel)) and not self.Database.GetFromTable("Users", f"ID = {message.author.id}"):
            self.AddUserToDatabase(message.author, message.guild)
            Logger.Log("Added user to database")
        
        # On user message, handle exp and level
        if BotUtils.isPublicChannel(type(message.channel)):
            if Level.CheckIfExpOnCooldown(self.Database, message.author.id, message):
                newLevel = self.Database.GetFromTable("Users", f"ID = {message.author.id}")[0][4]
                await message.channel.send(f"Congratulations {message.author.mention}! you are now **level {newLevel}**! <:peepoHappy:617113235828637721>")


        # Process command
        await self.process_commands(message)
예제 #2
0
 def UpdateUserColor(self, user_id: int, new_color: str) -> bool:
     query = "UPDATE Users SET cardColor = %s WHERE ID = %s;"
     try:
         self.Cursor.execute(query, (new_color, user_id))
         self.Connection.commit()
         Logger.Log(f"Updated user {user_id} color")
         return True
     except Exception as err:
         Logger.Log(err)
         self.Cursor.execute('rollback;')
         return False
예제 #3
0
 def UpdateUserDescription(self, user_id: int,
                           new_description: str) -> bool:
     query = "UPDATE Users SET description = %s WHERE ID = %s;"
     try:
         self.Cursor.execute(query, (new_description, user_id))
         self.Connection.commit()
         Logger.Log(f"Updated user {user_id} description.")
         return True
     except Exception as err:
         Logger.Log(err)
         self.Cursor.execute('rollback;')
         return False
예제 #4
0
 async def say(self, ctx: commands.Context, channel_id: str, *,
               message: str):
     if self.isOwner(ctx.message.author.id):
         try:
             channel_id = int(channel_id)
         except Exception as err:
             Logger.Log(err, Logger.ERROR)
             await ctx.send(f"`{channel_id}` is not a valid channel!")
         targetChannel = self.bot.get_channel(channel_id)
         try:
             await targetChannel.send(message)
         except Exception as err:
             Logger.Log(err, Logger.ERROR)
             await ctx.send(f"Failed to send a message to `{channel_id}`")
예제 #5
0
 def __init__(self, bot):
     Logger.Log("SKWiki loaded!")
     self.bot: commands.Bot = bot
     self.SKHelp = {
         "sk gear** *<name>*":
         "Returns info about weapon, armor, helm and shield"
     }
예제 #6
0
 async def playgame(self, ctx: commands.Context, *, gameName: str):
     if self.isOwner(ctx.message.author.id):
         newGameName = discord.Game(gameName)
         await self.bot.change_presence(activity=newGameName)
         await ctx.send(f"Changed game to `{gameName}`")
         Logger.Log(
             f"{ctx.message.author.name} changed bot status message to \"{gameName}\""
         )
예제 #7
0
 def disconnect(self):
     '''
         Disconnects from PostgreSQL database
     '''
     if self.Connection:
         self.Cursor.close()
         self.Connection.close()
         Logger.Log("Connection to database closed!")
         self.Connection = None
예제 #8
0
 def isConnected(self) -> bool:
     '''
         Returns status of current connection
     '''
     if self.Connection:
         return True
     else:
         Logger.Log(f"You must connect to the database first!")
         return False
예제 #9
0
 def __init__(self, bot):
     self.Bot: commands.Bot = bot
     Logger.Log("Loaded Family mechanics!")
     self.Database = Database(username=os.getenv("DATABASE_USER"),
                              password=os.getenv("DATABASE_PASSWORD"),
                              host=os.getenv("DATABASE_HOST"),
                              port=os.getenv("DATABASE_PORT"),
                              db_name=os.getenv("DATABASE_NAME"))
     self.Database.connect()
예제 #10
0
 def AddToTable(self, tableName: str, **kwargs):
     '''
         Adds values to a table
         :param tableName: Table name
         :param kwargs: Table column values
         :return: True if values were added, false if not
     '''
     queryBase = f"INSERT INTO {tableName} VALUES ({', '.join(['%s' for arg in range(len(kwargs))])})"
     if self.isConnected():
         try:
             self.Cursor.execute(queryBase, tuple(kwargs.values()))
             self.Connection.commit()
             Logger.Log(f"Added {tuple(kwargs.values())} to {tableName}")
             return True
         except Exception as err:
             Logger.Log(err, Logger.ERROR)
             self.Connection.rollback()
             return False
예제 #11
0
 def DeleteTable(self, tableName):
     '''
         Deletes table
         :param tableName: Table to delete
         :return: True if table was deleted, false if not
     '''
     query = f'''
         DROP TABLE {tableName};
     '''
     if self.isConnected():
         try:
             self.Cursor.execute(query)
             self.Connection.commit()
             Logger.Log(f"Deleted table: {tableName}")
             return True
         except Exception as err:
             Logger.Log(err, Logger.ERROR)
             self.Connection.rollback()
             return False
예제 #12
0
 def LoadAllCogs(self):
     Cogs = [
         "Core.Mechanics.Level", "Core.Mechanics.Economy",
         "Core.Mechanics.Family", "Core.Cogs.Admin", "Core.Cogs.SKWiki",
         "Core.Cogs.Misc", "Core.Cogs.Tera", "Core.Cogs.Images"
     ]
     for cog in Cogs:
         try:
             self.bot.load_extension(cog)
         except Exception as err:
             Logger.Log(str(err), Logger.ERROR)
예제 #13
0
 def CreateNewTable(self, tableName: str, values: str):
     '''
         Create new table
         :param tableName: Table name
         :param values: String with the values and its types
         :return: True if table was created, false if it failed
     '''
     query = f'''
         CREATE TABLE {tableName} {values};
     '''
     if self.isConnected():
         try:
             self.Cursor.execute(query)
             self.Connection.commit()
             Logger.Log(f"Created table {tableName} with values {values}")
             return True
         except Exception as err:
             Logger.Log(err, Logger.ERROR)
             self.Connection.rollback()
             return False
예제 #14
0
 def connect(self):
     '''
         Connects to PostgreSQL database
     '''
     if self.Connection == None:
         self.Connection = PostgreSQL.connect(user=self.username,
                                              password=self.password,
                                              host=self.host,
                                              port=self.port,
                                              database=self.db_name)
         self.Cursor = self.Connection.cursor()
         Logger.Log(f"Connected to database: {self.db_name}")
예제 #15
0
 def __init__(self, bot):
     Logger.Log("Admin loaded!")
     self.bot: commands.Bot = bot
     self.Owners: list = [183067754784358400]
     self.AdminCommands = {
         "shutdown**":
         "Shuts the bot down.",
         "playgame** *<game name>*":
         "Changes the bot message status.",
         "servers**":
         "Returns the name of every server the bot is in.",
         "say** *<channel_id>* *<message>*":
         "Sends a message to the target *channel_id*"
     }
예제 #16
0
 def CommitCommand(self, command: str):
     '''
         Executes command
         :param command: PostgreSQL command to execute and commit
         :return: True if the command was executed, False if not
     '''
     if self.isConnected():
         try:
             self.Cursor.execute(command)
             self.Connection.commit()
             return True
         except Exception as err:
             Logger.Log(err, Logger.ERROR)
             self.Connection.rollback()
             return False
예제 #17
0
    def GiveUserMoney(self, user_id: int, new_amount: float) -> bool:
        '''
            Updates the user's money
            :param user_id: User to update
            :param new_amount: New money amount

            e.g:
                # Updates user 123 to $500
                GiveUserMoney(123, 500.0)

            > Note: If new_amount is higher than MAX_AMOUNT, user's money will be updated to MAX_AMOUNT
        '''
        query = "UPDATE Users SET Credits = %s WHERE ID = %s;"
        if new_amount > Database.MAX_MONEY:
            new_amount = Database.MAX_MONEY
        try:
            self.Cursor.execute(query, (new_amount, user_id))
            self.Connection.commit()
            Logger.Log(f"Updated user {user_id} credits to {new_amount}")
            return True
        except Exception as err:
            Logger.Log(err)
            self.Cursor.execute('rollback;')
            return False
예제 #18
0
 async def on_guild_join(self, guild: discord.Guild):
     '''
         Creates a guild config to the database whenever Heeto joins a server
     '''
     Logger.Log(f"Joined new server: {guild.name} [{guild.id}]\nCreating Database entry...")
     self.Database.AddToTable(
         "Guilds",
         ID = int(guild.id),
         OwnerID = int(guild.owner_id),
         EnabledCommands = (True, True),
         commands_prefix = "~"
     )
     for user in guild.members:
         # For each member in the server, creates an entry in Heeto's database
         if not user.bot:
             self.AddUserToDatabase(user, guild)
예제 #19
0
    def GetFromTable(self, tableName: str, comp: str):
        '''
            Returns all table entries that has the comp
            :param tableName: Table name
            :param comp: Comparision to be made

            e.g:
                # Gets all entries where ID is 123
                GetFromTable("Users", "ID = 123")
        '''

        query = f'''
            SELECT * FROM {tableName} WHERE {comp};
        '''
        if self.isConnected():
            try:
                self.Cursor.execute(query)
                return self.Cursor.fetchall()
            except Exception as err:
                Logger.Log(err, Logger.ERROR)
                self.Connection.rollback()
예제 #20
0
    def DeleteFromTable(self, tableName: str, comp: str):
        '''
            Deletes element from an existing table
            :param tableName: Table name
            :param comp: Comparision to be made

            e.g:
                # Deletes all entries where ID is 123
                DeleteFromTable("Users", "ID = 123")
        '''
        query = f'''
            DELETE FROM {tableName} WHERE {comp};
        '''
        if self.isConnected():
            try:
                self.Cursor.execute(query)
                self.Connection.commit()
                return True
            except Exception as err:
                Logger.Log(err, Logger.ERROR)
                self.Connection.rollback()
                return False
예제 #21
0
 def __init__(self, bot):
     Logger.Log("Basic commands loaded!")
     self.bot: commands.Bot = bot
     self.LoadAllCogs()
예제 #22
0
 def __init__(self, bot):
     Logger.Log("Miscellaneous loaded!")
     self.bot: commands.Bot = bot
예제 #23
0
 async def on_member_remove(self, member: discord.Member):
     user: discord.User = self.get_user(member.id)
     if not user.bot:
         query = f"UPDATE Users SET Servers = array_remove(Servers, {member.guild.id}) WHERE ID = {user.id};"
         if self.Database.CommitCommand(query):
             Logger.Log(f"Updated user: {user.name}")
예제 #24
0
 async def on_ready(self):
     Logger.Log(f"{self.user.name} is now connected to Discord!")
     #Sets bot activity
     Activity = discord.Game(name=self.statusMessage, start=datetime.now())
     await self.change_presence(status=discord.Status.online, activity=Activity)
예제 #25
0
 def __init__(self, Bot):
     Logger.Log("Images loaded!")
     self.Bot: commands.Bot = Bot
예제 #26
0
 def __init__(self, bot):
     Logger.Log("Tera loaded!")
     self.bot: commands.Bot = bot