Esempio n. 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)
Esempio n. 2
0
    def __init__(self, cache_name):

        self.__cache_name = cache_name

        if ES.connection('es') is None:
            Logger.log(__name__, 'could not connect to elasticsearch', type='error')
            return

        ESService.create_index(self.__cache_name, Config.get('elasticsearch')['indices_settings'][self.__cache_name])
Esempio n. 3
0
def clear_backedoff_storage():

    storage_path = Data.get(
        Config.get('CTI')['backed_off_search']['storage_name'])

    if os.path.isfile(storage_path):
        os.remove(storage_path)
        Logger.log(__name__, 'the backedoff search storage is now empty')
    else:
        Logger.log(__name__, 'the backedoff search storage is already empty')
Esempio n. 4
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
Esempio n. 5
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
Esempio n. 6
0
def bootstrap_knowledge_base(dump_directory):

    Logger.log(__name__, 'bootstrapping knowledge base...')

    contexts_cache = ContextsCache.create(
        Config.get('CTI')['knowledge_base']['contexts_cache'])

    for article in WikipediaUtils.get_articles(dump_directory,
                                               attributes=['title',
                                                           'context']):
        contexts_cache.set(article['title'], article['context'])
        Logger.log(__name__,
                   'bootstrapping got context for: ' + article['title'])
Esempio n. 7
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}`")
Esempio n. 8
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"
     }
Esempio n. 9
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}\""
         )
Esempio n. 10
0
    def delete_index(name):

        try:

            if not ES.connection('es').indices.exists(name):
                Logger.log(__name__,
                           'index ' + name + ' does not exist',
                           type='error')
                return False

            ES.connection('es').indices.delete(index=name)

        except Exception as ex:
            Logger.log(__name__,
                       'could not delete index ' + name + '\t' + str(ex),
                       type='error')
            return False
Esempio n. 11
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
Esempio n. 12
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
Esempio n. 13
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
Esempio n. 14
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()
Esempio n. 15
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
Esempio n. 16
0
    def create_index(name, config):

        try:

            if ES.connection('es').indices.exists(name):
                Logger.log(__name__,
                           'index ' + name + ' already exists',
                           type='warning')
                return True

            ES.connection('es').indices.create(index=name, body=config)

        except Exception as ex:
            Logger.log(__name__,
                       'could not create index ' + name + '\t' + str(ex),
                       type='error')
            return False

        return True
Esempio n. 17
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)
Esempio n. 18
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
Esempio n. 19
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}")
Esempio n. 20
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*"
     }
Esempio n. 21
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
Esempio n. 22
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
Esempio n. 23
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)
Esempio n. 24
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()
Esempio n. 25
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
Esempio n. 26
0
def backed_off_search():

    config = Config.get('CTI')['backed_off_search']

    contexts_cache = ContextsCache.create(
        Config.get('CTI')['knowledge_base']['contexts_cache'])
    search_engine = SearchEngine()

    Logger.log(__name__, 'backed off search process started')
    Logger.log(
        __name__, 'backed off search storage has ' +
        str(len(SQLiteDict.storage(config['storage_name']))) + ' items')

    c = 0

    while True:

        try:
            title = SQLiteDict.storage(config['storage_name']).popitem()[0]
        except KeyError:
            sleep(config['empty_storage_wait_seconds'])
            continue

        contexts_cache.set(title, search_engine.context(title))

        Logger.log(__name__, 'backed off search got context for: ' + title)

        c += 1
        if c > 30:
            c = 0
            Logger.log(
                __name__, 'backed off search storage has ' +
                str(len(SQLiteDict.storage(config['storage_name']))) +
                ' items')

        sleep(config['seconds_between_searches'])
Esempio n. 27
0
 def __init__(self, Bot):
     Logger.Log("Images loaded!")
     self.Bot: commands.Bot = Bot
Esempio n. 28
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}")
Esempio n. 29
0
 def __init__(self, bot):
     Logger.Log("Basic commands loaded!")
     self.bot: commands.Bot = bot
     self.LoadAllCogs()
Esempio n. 30
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)