Exemple #1
0
async def on_guild_update(before, after):

    old_name = before.name
    new_name = after.name
    guild_id = after.id

    filter_id = {'_id': int(guild_id)}
    temp_data = mongodb.get_database_data(COLLECTION, filter_id)

    # update data when server name changes
    if old_name != new_name:

        # remove old data once from mongodb database filtered by id
        COLLECTION.delete_one({'_id': guild_id})
        old_file_name = botfile.get_server_data_file_name(old_name, guild_id)

        # load old json data file from my github repo

        # update old server name to the new one
        temp_data['server name'] = new_name

        old_path = botfile.get_absolute_file_path('data', old_file_name)
        # remove old local file
        os.remove(old_path)
        # delete from github repo

        gh.github_delete_file(f'data/{old_file_name}',
                              f'delete file: {old_file_name}')

        # create a new local file with the new name and dump the json data in it
        new_file_name = f'{botfile.get_server_data_file_name(new_name, guild_id)}'

        new_path = botfile.get_absolute_file_path('data', new_file_name)
        json.dump(
            temp_data,
            open(new_path, 'w'),
            sort_keys=True,
            indent=4,
        )

        sorted_data = json.load(open(new_path))
        #insert the data into the database
        COLLECTION.insert_one(sorted_data)

        # create the new file name in github repository
        gh.create_file_in_github_repo(f'data/{new_file_name}', temp_data)

        #update code
        client_update()
Exemple #2
0
def delete_older_duplicate_file(folder):
    stats = {}
    duplicates = []
    only_json = list(
        filter(
            lambda f: f.endswith('.json') and '-' in f and any(i.isdigit()
                                                               for i in f),
            os.listdir(os.path.join(os.getcwd(), folder))))

    for i in range(len(only_json) - 1):
        item = only_json[i]
        next_item = only_json[i + 1]

        id_ = re.search(r'-{1}([\d]+).json', item).group(1)
        id_next = re.search(r'-{1}([\d]+).json', next_item).group(1)

        if id_ == id_next:
            duplicates.append(item)
            duplicates.append(next_item)

    for duplicate in duplicates:
        creation_time = os.stat(
            os.path.join(get_absolute_file_path(folder, duplicate))).st_ctime
        stats[duplicate] = creation_time

    if (len(stats) > 1):
        minimum = min(stats.items(), key=lambda x: x[1])
        os.remove(os.path.join(os.getcwd(), folder, minimum[0]))
Exemple #3
0
async def on_guild_remove(guild):
    # when bot get's removed
    filename = get_server_data_file_name(guild.name, guild.id)
    try:
        os.remove(get_absolute_file_path('data', filename))
        gh.github_delete_file(f'data/{filename}', f'delete file: {filename}')
    except:
        print("can't delete file")
    print("Bot has been removed")
Exemple #4
0
async def on_guild_join(guild):
    # when the bot join a server (guild)
    file_name = botfile.get_server_data_file_name(guild.name, guild.id)
    file_path = botfile.get_absolute_file_path('data', file_name)
    data = {'_id': int(guild.id), 'server name': guild.name}

    if not os.path.exists(file_path):

        # create local file with the data
        json.dump(
            data,
            open(file_path, 'w'),
            sort_keys=True,
            indent=4,
        )
    if not COLLECTION.find_one({'_id': int(guild.id)}):
        # insert the data to database and create a file in the github repo
        COLLECTION.insert_one(data)
        load_original_data_to(COLLECTION, f'{guild.name}-{guild.id}.json')

    client_update()
    async def update_command(self, ctx):
        embed_color = discord.Colour.blue()
        text = f'Enter a **trigger** name : (Or type **c** To **Cancel**)'

        embed = get_embed(name='Update', value=text, color=embed_color)

        cancel_response = 'Command **cancelled!**'
        current_user = ctx.author

        file_name = get_server_data_file_name(ctx.guild.name, ctx.guild.id)
        path = get_absolute_file_path('data', file_name)

        collection = get_database('triggers')[1]
        id_filter = {'_id': ctx.guild.id}
        cursor = get_database_data(collection, id_filter)

        trigger_response = {}
        #if database exists
        if cursor:
            trigger_response = dict(cursor)
        self.client.unload_extension(BASIC_COG)

        await ctx.send(embed=embed, delete_after=get_guild_delete_timer())

        trigger = await self.client.wait_for(
            'message', check=lambda m: m.author == current_user)
        message = trigger
        trigger = trigger.content.strip()

        if trigger.lower() == 'c':
            self.client.load_extension(BASIC_COG)
            embed = get_embed(name='Cancelled!',
                              value=cancel_response,
                              color=embed_color)
            await ctx.send(embed=embed, delete_after=get_guild_delete_timer())
            await ctx.message.delete(delay=get_guild_delete_timer())
            await message.delete(delay=get_guild_delete_timer())
            return
        elif trigger in trigger_response.keys():
            text = f'''The actual **response** of your **trigger** is "**{trigger_response[trigger]}**"
            Enter a new **response** to update the **trigger**: (Or type **c** To **Cancel**)'''

            embed = get_embed(name="Updating Trigger",
                              value=text,
                              color=embed_color)

            await ctx.send(embed=embed, delete_after=get_guild_delete_timer())
            await ctx.message.delete(delay=get_guild_delete_timer())
            await message.delete(delay=get_guild_delete_timer())

            response = await self.client.wait_for(
                'message', check=lambda m: m.author == current_user)
            message = response

            if response.content.lower().strip() == 'c':
                embed = get_embed(name='Cancelled!',
                                  value=cancel_response,
                                  color=embed_color)

                await ctx.send(embed=embed,
                               delete_after=get_guild_delete_timer())
                await ctx.message.delete(delay=get_guild_delete_timer())
                await message.delete(delay=get_guild_delete_timer())

                self.client.load_extension(BASIC_COG)
                return

            response = response.content.strip()
            trigger_response[trigger] = response

            update_database_data(filter_id=id_filter,
                                 value=response,
                                 key=trigger)
            update_file_in_github_repo(
                f'data/{ctx.guild.name}-{ctx.guild.id}.json',
                trigger_response,
            )
            update_local_server_file(trigger_response, path)
            self.client.load_extension(BASIC_COG)

            text = f'Updated **trigger**: "**{trigger}**" with new **response**: "**{trigger_response[trigger]}**"'
            embed = get_embed(name='Updated!', value=text, color=embed_color)

            await ctx.send(embed=embed, delete_after=get_guild_delete_timer())
            await ctx.message.delete(delay=get_guild_delete_timer())
            await message.delete(delay=get_guild_delete_timer())
        else:
            embed = get_embed(
                name='Error!',
                value=f'**trigger** name "{trigger}" does not exist',
                color=discord.Colour.red())

            await ctx.send(embed=embed, delete_after=get_guild_delete_timer())
            await ctx.message.delete(delay=get_guild_delete_timer())
            await message.delete(delay=get_guild_delete_timer())
            self.client.load_extension(BASIC_COG)
    async def add_command(self, ctx):

        cancel_response = 'command **cancelled!**'
        # admin to add a trigger, response to the (key) trigger and (value) response dictionary
        current_user = ctx.author
        file_name = get_server_data_file_name(ctx.guild.name, ctx.guild.id)
        path = get_absolute_file_path('data', file_name)

        collection = get_database('triggers')[1]
        id_filter = {'_id': ctx.guild.id}
        cursor = get_database_data(collection, id_filter)

        trigger_response = {}

        if cursor:
            trigger_response = dict(cursor)

        color = discord.Colour.green()
        text = f'**Add** a new **trigger**: (Or type **c** To **Cancel**)'
        embed = get_embed(name="Add", value=text, color=color)

        await ctx.send(embed=embed, delete_after=get_guild_delete_timer())
        self.client.unload_extension(BASIC_COG)
        trigger = await self.client.wait_for(
            'message', check=lambda m: m.author == current_user)

        message = trigger
        trigger = trigger.content.strip()

        if (trigger.lower() == 'c'):

            embed = get_embed(name='Cancelled!',
                              value=cancel_response,
                              color=color)
            await ctx.send(embed=embed, delete_after=get_guild_delete_timer())
            await ctx.message.delete(delay=get_guild_delete_timer())
            await message.delete(delay=get_guild_delete_timer())

            self.client.load_extension(BASIC_COG)
            return
        else:
            if trigger in trigger_response.keys():
                embed = get_embed(
                    name='Error!',
                    value=f'*Trigger**: "{trigger}" already exists!',
                    color=color)

                await ctx.send(embed=embed,
                               delete_after=get_guild_delete_timer())
                await ctx.message.delete(delay=get_guild_delete_timer())
                await message.delete(delay=get_guild_delete_timer())

                self.client.load_extension(BASIC_COG)
                return
            else:

                text = f'**Add** a **response** to the **trigger**: (Or type **c** to **Cancel**):'
                embed = get_embed(name="Adding a Response",
                                  value=text,
                                  color=color)

                await ctx.send(embed=embed,
                               delete_after=get_guild_delete_timer())
                await ctx.message.delete(delay=get_guild_delete_timer())
                await message.delete(delay=get_guild_delete_timer())

                response = await self.client.wait_for(
                    'message', check=lambda m: m.author == current_user)
                message = response
                response = response.content.strip()

                if (response.lower() == 'c'):
                    embed = get_embed(name='Cancelled!',
                                      value=cancel_response,
                                      color=color)

                    await ctx.send(embed=embed,
                                   delete_after=get_guild_delete_timer())
                    await ctx.message.delete(delay=get_guild_delete_timer())
                    await message.delete(delay=get_guild_delete_timer())

                    self.client.load_extension(BASIC_COG)
                    return
                else:

                    text = f'Trigger: "{trigger}"\nResponse: "{response}" added with success!!'
                    embed = get_embed(name="Added!", value=text, color=color)

                    await ctx.send(embed=embed,
                                   delete_after=get_guild_delete_timer())
                    await ctx.message.delete(delay=get_guild_delete_timer())
                    await message.delete(delay=get_guild_delete_timer())

                    trigger_response[trigger] = response
                    post = {'_id': int(ctx.guild.id)}

                    update_file_in_github_repo(
                        f'data/{ctx.guild.name}-{ctx.guild.id}.json',
                        trigger_response)
                    update_local_server_file(trigger_response, path)

                    collection.update_one(post, {'$set': {trigger: response}})
                    self.client.load_extension(BASIC_COG)
    async def delete_command(self, ctx):
        self.client.unload_extension(BASIC_COG)
        # delete an entry (key) trigger and (value) response from the dictionary
        cancel_response = 'command **cancelled!**'
        file_name = get_server_data_file_name(ctx.guild.name, ctx.guild.id)
        path = get_absolute_file_path('data', file_name)

        collection = get_database('triggers')[1]
        id_filter = {'_id': ctx.guild.id}

        cursor = get_database_data(collection, id_filter)
        trigger_response = {}

        if cursor:
            trigger_response = dict(cursor)

        current_user = ctx.author

        text = f'Enter the **trigger\'s** name to **delete** it\'s entry (Or type **c** to **Cancel**):'
        color = discord.Colour.red()
        embed = get_embed(name="Delete", value=text, color=color)

        await ctx.send(embed=embed, delete_after=get_guild_delete_timer())
        await ctx.message.delete(delay=get_guild_delete_timer())

        trigger = await self.client.wait_for(
            'message', check=lambda m: m.author == current_user)

        message = trigger
        trigger = trigger.content.strip()
        if (trigger.lower() == 'c'):
            embed = get_embed(name='Cancelled!',
                              value=cancel_response,
                              color=color)
            await ctx.send(embed=embed, delete_after=get_guild_delete_timer())
            await ctx.message.delete(delay=get_guild_delete_timer())
            await message.delete(delay=get_guild_delete_timer())

            self.client.load_extension(BASIC_COG)
            return
        else:
            if trigger in trigger_response.keys():
                response = trigger_response[trigger]
                post = {'_id': int(ctx.guild.id)}
                #delete one entry by id from database
                collection.update_one(post, {'$unset': {trigger: response}})
                del trigger_response[trigger]
                msg = 'delete'

                update_file_in_github_repo(
                    f'data/{ctx.guild.name}-{ctx.guild.id}.json',
                    trigger_response, msg)
                update_local_server_file(trigger_response, path)

                text = f'**Trigger**: "{trigger}"\n**Response**: "{response}" was **deleted** with success'
                embed = get_embed(name="Deleted!", value=text, color=color)

                await ctx.send(embed=embed,
                               delete_after=get_guild_delete_timer())
                await ctx.message.delete(delay=get_guild_delete_timer())
                await message.delete(delay=get_guild_delete_timer())
            else:

                embed = get_embed(name="Error!",
                                  value=f'**{trigger}** does not exist!',
                                  color=color)
                await ctx.send(embed=embed,
                               delete_after=get_guild_delete_timer())
                await ctx.message.delete(delay=get_guild_delete_timer())
                await message.delete(delay=get_guild_delete_timer())
        self.client.load_extension(BASIC_COG)
    async def delete_time(self, ctx):

        cancel_response = 'command **cancelled!**'
        global delete_time
        delete_time = get_delete_timer('data', 'timer.json', ctx.guild.id)

        text = f'Your current timer is set to {get_guild_delete_timer()} \n Enter the **seconds** delay for me to **delete** messages or **c** to **Cancel**'
        embed = discord.Embed(colour=discord.Colour.dark_orange())
        embed.add_field(name="Delete timer", value=text)

        await ctx.send(embed=embed, delete_after=get_guild_delete_timer())

        time = await self.client.wait_for(
            'message', check=lambda m: m.author == ctx.author)
        message = time
        if time.content.lower() == 'c':
            embed.clear_fields()
            embed.add_field(name='Cancelled!', value=cancel_response)

            await ctx.send(embed=embed, delete_after=get_guild_delete_timer())
            await ctx.message.delete(delay=get_guild_delete_timer())
            await message.delete(delay=get_guild_delete_timer())
            return

        error = 'Please enter only **positive** **integer** numbers '
        embed = discord.Embed(colour=discord.Colour.red())
        embed.add_field(name="Error", value=error)

        try:
            time = int(time.content.lower().strip())

        except:
            await ctx.send(embed=embed, delete_after=get_guild_delete_timer())
            await ctx.message.delete(delay=get_guild_delete_timer())
            await message.delete(delay=get_guild_delete_timer())
            return
        else:
            if time <= 0:
                await ctx.send(embed=embed,
                               delete_after=get_guild_delete_timer())
                await ctx.message.delete(delay=get_guild_delete_timer())
                await message.delete(delay=get_guild_delete_timer())
                return

        delete_time = time
        data = get_json_data('data', 'timer.json')
        guild_id = str(ctx.guild.id)
        data[guild_id] = get_guild_delete_timer()

        json.dump(data,
                  open(get_absolute_file_path('data', 'timer.json'), 'w'),
                  indent=4)

        text = f'You put {time} seconds delay for me to delete messages'
        embed = discord.Embed(colour=discord.Colour.dark_orange())
        embed.add_field(name="Timer Updated!", value=text)

        await ctx.send(embed=embed, delete_after=get_guild_delete_timer())
        await ctx.message.delete(delay=get_guild_delete_timer())
        await message.delete(delay=get_guild_delete_timer())

        return delete_time
Exemple #9
0
def client_update():
    # update live the code to get last data
    servers = client.guilds

    if not servers:
        print('no server yet')
        return

    server_ids = {}
    names = []

    server_id_file = 'clients-server-id.json'
    folder = 'data'
    users_file = 'clients-server-name-id.txt'

    if not os.path.exists(users_file):
        open(f'{get_absolute_file_path(folder, users_file)}', 'w')

    if not os.path.exists(server_id_file):
        open(f'{get_absolute_file_path(folder, server_id_file)}', 'w')

    timer = {}

    for server in servers:
        name = f'{server.name}-{server.id}'
        names.append(name)
        server_ids[server.name] = server.id
        timer[server.id] = 30

    if not os.path.exists(get_absolute_file_path('data', 'timer.json')):
        print('not in')
        json.dump(timer,
                  open(os.path.join(os.getcwd(), folder, 'timer.json'), 'w'),
                  indent=4)

    #update timer for servers
    updated_timers = json.load(
        open(get_absolute_file_path('data', 'timer.json')))
    for server in servers:
        if str(server.id) not in updated_timers.keys():
            updated_timers[server.id] = 30

    json.dump(updated_timers,
              open(os.path.join(os.getcwd(), folder, 'timer.json'), 'w'),
              indent=4)

    json.dump(
        server_ids,
        open(get_absolute_file_path(folder, server_id_file), 'w'),
        indent=4,
    )

    with open(f'{get_absolute_file_path(folder, users_file)}', 'w+') as f:
        for name in names:
            if name not in f.readlines():
                f.write(name + '\n')
        ids = json.load(
            open(get_absolute_file_path('data', 'clients-server-id.json')))

    collections = []

    for id in server_ids.values():
        filter_id = {'_id': int(id)}

        guildname = client.get_guild(id).name

        coll = mongodb.get_database_data(COLLECTION, filter_id)

        if coll:
            if coll['server name'] != guildname:
                update_database_data(filter_id, guildname, 'server name')

            collections.append(mongodb.get_database_data(
                COLLECTION, filter_id))

    for collection in collections:

        if collection:

            server_name, server_id = collection['server name'], collection[
                '_id']
            filename = get_server_data_file_name(server_name, server_id)
            if not os.path.exists(get_absolute_file_path(folder, filename)):
                open(f'{get_absolute_file_path(folder, filename)}', 'w')
            else:
                update_local_server_file(
                    collection, get_absolute_file_path(folder, filename))
            json.dump(collection,
                      open(get_absolute_file_path(
                          folder,
                          filename,
                      ), 'w'),
                      indent=4)
            try:
                gh.create_file_in_github_repo(f'data/{filename}', collection)
            except:
                print('File exists')
                continue
    #check local files has the same id if yes delete the older one
    delete_older_duplicate_file(folder)