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)
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
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
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}`")
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" }
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}\"" )
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
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
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()
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
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
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)
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
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}")
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*" }
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
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
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)
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()
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
def __init__(self, bot): Logger.Log("Basic commands loaded!") self.bot: commands.Bot = bot self.LoadAllCogs()
def __init__(self, bot): Logger.Log("Miscellaneous loaded!") self.bot: commands.Bot = bot
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}")
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)
def __init__(self, Bot): Logger.Log("Images loaded!") self.Bot: commands.Bot = Bot
def __init__(self, bot): Logger.Log("Tera loaded!") self.bot: commands.Bot = bot