Exemplo n.º 1
0
    async def deletereminder_command(self, ctx):
        if await misc.is_dm(ctx) == True:
            return

        author_ID = ctx.message.author.id
        user = ctx.message.author.name + '#' + ctx.message.author.discriminator
        prefix = json.load(open('settings/config.json',
                                'r'))['bot']['prefix'][0]
        # get actual message
        args = get_args(ctx)

        rem_id = args[0]

        reminder = await mrem.get_reminder_from_id(rem_id)

        if reminder == False:
            await ctx.send(
                content=
                f"<@!{author_ID}> There's no reminder with the ID `{rem_id}`. Use [insert command here] to view all reminders created by you."
            )
            return

        if author_ID != reminder['author']:
            await ctx.send(
                content=
                f"<@!{author_ID}> Could not delete reminder with ID `{rem_id}` as you are not the creator of said reminder."
            )
            return

        await mrem.delete_reminders(rem_id, client=self.bot)
        await ctx.send(
            content=
            f"<@!{author_ID}> Reminder with ID `{rem_id}` got successfully deleted."
        )
        return
Exemplo n.º 2
0
    async def viewreminder_command(self, ctx):
        author_ID = ctx.message.author.id
        user = ctx.message.author.name + '#' + ctx.message.author.discriminator
        prefix = json.load(open('settings/config.json',
                                'r'))['bot']['prefix'][0]
        # get actual message
        args = get_args(ctx)

        rem_id = args[0]

        reminder = await mrem.get_reminder_from_id(rem_id)

        if reminder == False:
            await ctx.send(
                content=
                f"<@!{author_ID}> There's either no reminder with the ID `{rem_id}` or you are not the author of that reminder. Use [insert command here] to view all reminders created by you."
            )
            return

        if author_ID != reminder['author']:
            await ctx.send(
                content=
                f"<@!{author_ID}> There's either no reminder with the ID `{rem_id}` or you are not the author of that reminder. Use [insert command here] to view all reminders created by you."
            )
            return

        rem_date = ct.ms_to_datetime(reminder['date'])

        await ctx.send(
            content=
            f"<@!{author_ID}> Reminder with the ID `{reminder['id']}` will be posted on `{rem_date.strftime('%Y-%m-%d %H:%M (%I:%M%p) UTC')}` with the following text:\n{reminder['message']}"
        )
        return
Exemplo n.º 3
0
    async def setpresence_command(self, ctx):
        author_ID = str(ctx.message.author.id)
        user = ctx.message.author.name + '#' + ctx.message.author.discriminator
        prefix = json.load(open('settings/config.json',
                                'r'))['bot']['prefix'][0]

        if not is_owner(author_ID):
            await ctx.send(
                content=
                f'<@!{author_ID}> Owner commands can only be executed by owners.'
            )
            await log(
                f"Owner command cannot be executed by non-owners. ({prefix}setpresence used by {user}",
                'warn',
                client=self.bot)
            return

        args = get_args(ctx)

        if len(args) < 3:
            await ctx.send(
                content=
                f"<@!{author_ID}> Not enough arguments. Use `{prefix}setpresence <status> <activity> <activity name>`."
            )
            return

        status = args[0].lower()
        atype = args[1].upper()
        name = ' '.join(args[2:])

        if (status not in ('online', 'idle', 'dnd', 'invisible')):
            await ctx.send(
                content=
                f"<@!{author_ID}> **{status}** was not a valid argument. Please use one of the following: 'online', 'idle', 'dnd', 'invisible' (without the apostrophes)."
            )
            return

        if (atype not in ('PLAYING', 'WATCHING', 'LISTENING', 'STREAMING')):
            await ctx.send(
                content=
                f"<@!{author_ID}> **{atype}** was not a valid argument. Please use one of the following: 'PLAYING', 'WATCHING', 'LISTENING', 'STREAMING' (without the apostrophes)."
            )
            return

        await activity.change_activity(status=status,
                                       atype=atype,
                                       name=name,
                                       client=self.bot)

        await log(
            f"Presence was updated to '{status} - {atype} {name}' by {user}",
            'info',
            client=self.bot)
        await ctx.send(
            content=
            f"<@!{author_ID}> Presence was updated to **{status}** - **{atype} {name}**! (Note: If it doesn't update it might've got rate-limited, try again in a couple minutes in that case.)"
        )
        return
Exemplo n.º 4
0
    async def checkdailyreminders_command(self, ctx):
        author_ID = ctx.message.author.id
        user = ctx.message.author.name + '#' + ctx.message.author.discriminator
        prefix = json.load(open('settings/config.json',
                                'r'))['bot']['prefix'][0]
        # get actual message
        args = get_args(ctx)

        await mrem.daily_reminder_check(author=author_ID, client=self.bot)
        return
Exemplo n.º 5
0
    async def delayscan_command(self, ctx):
        author_ID = str(ctx.message.author.id)
        user = ctx.message.author.name + '#' + ctx.message.author.discriminator
        prefix = json.load(open('settings/config.json',
                                'r'))['bot']['prefix'][0]

        if not is_owner(author_ID):
            await ctx.send(
                content=
                f'<@!{author_ID}> Owner commands can only be executed by owners.'
            )
            await log(
                f"Owner command cannot be executed by non-owners. ({prefix}delayscan used by {user}",
                'warn',
                client=self.bot)
            return

        args = get_args(ctx)

        try:
            args[0]
        except IndexError:
            await ctx.send(
                content=
                f"<@!{author_ID}> Missing argument. Use `{prefix}delayscan <hours>`."
            )
            return

        if args[0].isdigit() == False:
            await ctx.send(
                content=
                f"<@!{author_ID}> Invalid argument. Use `{prefix}delayscan <hours>`."
            )
            return

        args[0] = int(args[0])

        with open('settings/database.json', 'r+') as f:
            database = json.load(f)
            database['general']['lastChecked'] = database['general'][
                'lastChecked'] + (args[0] * 3600000)

            # reset file position to the beginning - stackoverflow copy, dont ask
            f.seek(0)
            json.dump(database, f, indent=4)
            f.truncate()

        await log(f"Next scan got delayed by {args[0]} hours.",
                  'info',
                  client=self.bot)
        await ctx.send(
            content=
            f"<@!{author_ID}> Next scan successfully delayed by {args[0]} hours."
        )
        return
Exemplo n.º 6
0
    async def converttime_command(self, ctx):
        author_ID = ctx.message.author.id
        prefix = json.load(open('settings/config.json',
                                'r'))['bot']['prefix'][0]
        # get arguments
        args = get_args(ctx)

        await log(f"{prefix}converttime executed.", 'spamInfo')

        if len(args) < 2:
            await ctx.send(
                content=
                f"<@!{author_ID}> Missing argument. Please use `{prefix}converttime <time/date to convert> <timezone>` where timezone can be in the format of either `CEST` or `Europe/Berlin`."
            )
            return

        timezone = args[len(args) - 1]
        date_to_convert = ' '.join(args[:len(args) - 1])

        if timezone == 'local':
            timezone = json.load(open('settings/config.json',
                                      'r'))['reminders']['timezone']

        if timezone == '':
            await ctx.send(
                content=
                f"<@!{author_ID}> `local` argument can only be used if a timezone is entered in `config.json`>`reminders`>`timezone`."
            )
            return

        # Convert time (simply let dateparser handle it)
        date = parse(date_to_convert,
                     settings={
                         'TO_TIMEZONE': timezone,
                         'RETURN_AS_TIMEZONE_AWARE': False
                     })

        if date == None:
            await ctx.send(
                content=
                f"<@!{author_ID}> Something went wrong when trying to convert `{date_to_convert}` to the timezone `{timezone}`. Please use `{prefix}converttime <time/date to convert> <timezone>` where timezone can be in the format of either `CEST` or `Europe/Berlin`."
            )
            return

        print(date)
        await ctx.send(
            content=
            f"<@!{author_ID}> `{date.strftime('%Y-%m-%d %H:%M (%I:%M%p)')}` (converted from `{date_to_convert}` to `{timezone}`)"
        )
        return
Exemplo n.º 7
0
    async def find_command(self, ctx):
        if await misc.is_dm(ctx) == True:
            return

        author_ID = ctx.message.author.id
        prefix = json.load(open('settings/config.json',
                                'r'))['bot']['prefix'][0]
        # get actual message
        text = get_args(ctx, combine=True)

        await log(f"{prefix}find executed.", 'spamInfo')

        results = manage_feeds.get_feed_by_name(text, ctx.message.guild.id)

        embed_dict = {}

        embed_dict['color'] = misc.get_embed_color(
            default_color=self.bot.get_guild(ctx.message.guild.id).me.color)

        embed_dict['description'] = f"All feeds named **{text}**:"

        embed = discord.Embed(**embed_dict)

        if len(results) == 0:
            embed.add_field(
                name=f"No items available.",
                value=f"Note: Only exact matches in this server are shown.",
                inline=False)
        else:
            results_length = len(results)

            count = 0

            for r in results:
                count += 1
                if count > 12:
                    embed.add_field(
                        name=f"...and {len(results) - count} more",
                        value=
                        f"Use {prefix}rmall <name> to remove all feeds matching a certain name.",
                        inline=False)
                    break
                embed.add_field(name=r['feedName'],
                                value=f"<#{r['channelID']}>\n{r['url']}")

        await ctx.send(embed=embed)

        return
Exemplo n.º 8
0
    async def listreminders_command(self, ctx):
        author_ID = ctx.message.author.id
        prefix = json.load(open('settings/config.json',
                                'r'))['bot']['prefix'][0]

        # get actual message
        args = get_args(ctx)

        await log(f"{prefix}listreminders executed.", 'spamInfo')

        page = 0
        try:
            page = int(args[0])
        except IndexError:
            pass

        # make sure page is valid
        if page < 1:
            page = 1

        messages = {}
        messages['item_title_type'] = 'reminders'
        messages['item_desc_type'] = 'reminders'

        messages['all_items_from'] = 'All reminders from'
        messages[
            'no_items_available'] = f"Use `{prefix}addrem` to add a new reminder"
        messages[
            'no_items_on_page'] = f"Use `{prefix}listrem {page - 1}` to view the previous page."
        messages[
            'and_more'] = f"Use `{prefix}listrem [page]` to view a different page."

        results = await mrem.get_all_reminders_from_user(author_ID)
        title = f"**{ctx.message.author.name}**"

        embed = misc.create_embed_from_list(client=self.bot,
                                            dm=True,
                                            results=results,
                                            title=title,
                                            messages=messages,
                                            page=page,
                                            multi_columns=False)

        await ctx.send(embed=embed)
        return
Exemplo n.º 9
0
    async def setactivity_command(self, ctx):
        author_ID = str(ctx.message.author.id)
        user = ctx.message.author.name + '#' + ctx.message.author.discriminator
        prefix = json.load(open('settings/config.json',
                                'r'))['bot']['prefix'][0]

        if not is_owner(author_ID):
            await ctx.send(
                content=
                f"<@!{author_ID}> Owner commands can only be executed by owners."
            )
            await log(
                f'Owner command cannot be executed by non-owners. ({prefix}setactivity used by {user}',
                'warn',
                client=self.bot)
            return

        args = get_args(ctx)
        atype = args[0].upper()
        name = ' '.join(args[1:])

        if atype in ('PLAYING', 'WATCHING', 'LISTENING', 'STREAMING'):
            await activity.change_activity(atype=atype,
                                           name=name,
                                           client=self.bot)

            await log(f"Activity was updated to '{atype} {name}' by {user}",
                      'info',
                      client=self.bot)
            await ctx.send(
                content=
                f"<@!{author_ID}> Activity was updated to **{atype} {name}**! (Note: If it doesn't update it might've got rate-limited, try again in a couple minutes in that case.)"
            )
        else:
            await ctx.send(
                content=
                f"<@!{author_ID}> **{atype}** was not a valid argument. Please use one of the following: 'PLAYING', 'WATCHING', 'LISTENING', 'STREAMING' (without the apostrophes)."
            )
        return
Exemplo n.º 10
0
    async def setstatus_command(self, ctx):
        author_ID = str(ctx.message.author.id)
        user = ctx.message.author.name + '#' + ctx.message.author.discriminator
        prefix = json.load(open('settings/config.json',
                                'r'))['bot']['prefix'][0]

        if not is_owner(author_ID):
            await ctx.send(
                content=
                f"<@!{author_ID}> Owner commands can only be executed by owners."
            )
            await log(
                f"Owner command cannot be executed by non-owners. ({prefix}setstatus used by {user}",
                'warn',
                client=self.bot)
            return

        args = get_args(ctx)
        status = args[0].lower()

        if status in ('online', 'idle', 'dnd', 'invisible'):
            await activity.change_activity(status=status, client=self.bot)

            await log(f"Online status was updated to '{status}' by {user}",
                      'info',
                      client=self.bot)
            await ctx.send(
                content=
                f"<@!{author_ID}> Status was updated to **{status}**! (Note: If it doesn't update it might've got rate-limited, try again in a couple minutes in that case.)"
            )
        else:
            await ctx.send(
                content=
                f"<@!{author_ID}> **{status}** was not a valid argument. Please use one of the following: 'online', 'idle', 'dnd', 'invisible' (without the apostrophes)."
            )
        return
Exemplo n.º 11
0
    async def addreminder_command(self, ctx):
        if await misc.is_dm(ctx) == True:
            return

        author_ID = ctx.message.author.id
        user = ctx.message.author.name + '#' + ctx.message.author.discriminator
        prefix = json.load(open('settings/config.json',
                                'r'))['bot']['prefix'][0]
        # get actual message
        args = get_args(ctx)

        reminder_interval = json.load(open('settings/config.json',
                                           'r'))['reminders']['interval']
        current_time = ct.struct_to_datetime(ct.get_current_time())

        timezone = json.load(open('settings/config.json',
                                  'r'))['reminders']['timezone']

        public = None
        public_aliases = ['p', 'pc', 'pub', 'public', 'open', 'privatent']
        private_aliases = ['pv', 'priv', 'private', 'unlisted', 'publicnt']

        #aliases used to specify 'use this channel'
        this_channel_aliases = ['_']

        channel = None
        channel_arg = 0

        rem_type = None

        #everything in this try except is based around figuring out where the date & time string starts and ends as it doesn't follow any easy to follow rules
        #this is mainly because relative time inputs are allowed like "tomorrow" or "in 5 minutes", this is also the whole reason why channel has to be input
        #as the channel plays the biggest part in figuring out where the date & time string ends
        try:
            if args[0] in ['reminder']:
                rem_type = 'reminder'

            #check which arg is the channel
            for i in range(len(args)):
                if args[i].startswith('<#'):
                    if await misc.is_valid_channel(
                            ctx=ctx,
                            channel=self.bot.get_channel(int(args[i][2:-1])),
                            send_message=False) == True:
                        channel = self.bot.get_channel(int(args[i][2:-1]))
                        channel_arg = i
                        break

            #check if user simply wanted to use the current channel by entering _
            if channel == None:
                for i in range(len(args)):
                    if args[i] in this_channel_aliases:
                        channel = ctx.message.channel
                        channel_arg = i
                        break

            if channel == None:
                #throw error so try except catches it and sends the 'invalid arguments' message
                raise IndexError()
                return

            # private/public always has to be specified before channel so that's where were checking if it exists
            if args[channel_arg - 1] in public_aliases:
                public = True
            elif args[channel_arg - 1] in private_aliases:
                public = False

            #get the date string
            #this checks if type or public/private or both got specified in order to figure out where the date string starts and ends
            if rem_type != None:
                if public == None:
                    rem_date_input = ' '.join(args[1:channel_arg])
                else:
                    rem_date_input = ' '.join(args[1:(channel_arg - 1)])
            else:
                if public == None:
                    rem_date_input = ' '.join(args[0:channel_arg])
                else:
                    rem_date_input = ' '.join(args[0:(channel_arg - 1)])

            #print(f"Date string to parse: '{rem_date_input}'")

            #TO_TIMEZONE makes sure it converts the time to UTC which is what the bot uses
            if timezone == '':
                rem_date = parse(rem_date_input,
                                 settings={
                                     'TO_TIMEZONE': 'etc/UTC',
                                     'RETURN_AS_TIMEZONE_AWARE': False
                                 })
            else:
                rem_date = parse(rem_date_input,
                                 settings={
                                     'TO_TIMEZONE': 'etc/UTC',
                                     'RETURN_AS_TIMEZONE_AWARE': False,
                                     'TIMEZONE': timezone
                                 })

            print(rem_date)

            if rem_date == None:
                await ctx.send(
                    content=
                    f"<@!{author_ID}> Could not parse date `{rem_date_input}`. This might also be caused by using the command wrong (or the bot being broken), try using `{prefix}add {self.addreminder_command.usage}`"
                )
                await log(
                    f"Failed to create a reminder as the date '{rem_date_input}' could not be parsed (timezone: '{timezone}').",
                    'spamInfo',
                    client=self.bot)
                return

            if rem_date <= (current_time + dt.timedelta(minutes=1)):
                await ctx.send(
                    content=
                    f"<@!{author_ID}> Reminder has to be more than 1 minute in the future."
                )
                await log(
                    f"Failed to create a reminder on '{rem_date.strftime('%Y-%m-%d %H:%M')}' (current time: '{current_time.strftime('%Y-%m-%d %H:%M')}' | parsed string: '{rem_date_input}').",
                    'spamInfo',
                    client=self.bot)
                return

            #use defaults if not specified by the user
            if rem_type == None:
                rem_type = 'reminder'

            if public == None:
                public = False

            message = ' '.join(args[channel_arg + 1:])

        except IndexError:
            await ctx.send(
                content=
                f"<@!{author_ID}> Invalid arguments. Use `{prefix}add {self.addreminder_command.usage}`"
            )
            return

        # create actual reminder and get the ID of the created reminder
        reminder_id = mrem.add_reminder(rem_type='reminder',
                                        author=author_ID,
                                        dt=rem_date,
                                        channel=channel.id,
                                        message=message,
                                        public=public)

        if public != True:
            await ctx.message.delete()

        await log(
            f"Created a reminder on '{rem_date.strftime('%Y-%m-%d %H:%M')}' (string parsed: '{rem_date_input}' | timezone: '{timezone}') with the ID '{reminder_id} by user {user}",
            'spamInfo',
            client=self.bot)

        if type(reminder_id) == str:
            await ctx.send(
                content=
                f"<@!{author_ID}> A reminder has been created with the ID `{reminder_id}` and will be posted on `{rem_date.strftime('%Y-%m-%d %H:%M (%I:%M%p) UTC')}`."
            )
            return

        await ctx.send(
            content=
            f"<@!{author_ID}> Something has gone wrong while creating a reminder. The reminder might've still been created though, check `[insert command here]` to see if it exists."
        )
        return
Exemplo n.º 12
0
    async def list_command(self, ctx):
        if await misc.is_dm(ctx) == True:
            return

        author_ID = ctx.message.author.id
        prefix = json.load(open('settings/config.json',
                                'r'))['bot']['prefix'][0]

        # get actual message
        args = get_args(ctx)
        list_channel = False
        client = self.bot

        await log(f"{prefix}list executed.", 'spamInfo')

        # check if an argument is used
        arg1_available = False
        try:
            args[0]
            arg1_available = True
        except IndexError:
            pass

        page = 0
        try:
            page = int(args[1])
        except IndexError:
            pass

        list_channel = False

        if arg1_available == True:
            # get channel from name
            if args[0].startswith('<#'):
                channel = client.get_channel(int(args[0][2:-1]))
                list_channel = True

                # check if channel is valid
                if await misc.is_valid_channel(
                        ctx=ctx,
                        channel=channel,
                        author_ID=author_ID,
                        command=f'{prefix}list [channel]') == False:
                    return

            # check if only digits - if yes, use as page number instead
            elif args[0].isdigit():
                page = int(args[0])
            # error
            else:
                await ctx.send(
                    content=
                    f"<@!{author_ID}> Channel entered was invalid. Please use `{prefix}list [channel]`"
                )
                return

        # make sure page is valid
        if page < 1:
            page = 1

        messages = {}
        messages['item_title_type'] = 'feeds'
        messages['item_desc_type'] = 'feeds'

        messages['all_items_from'] = 'All feeds from'
        messages[
            'no_items_available'] = f"Use `{prefix}list` to see all items in the entire server.\nUse `{prefix}list [channel]` to view a different channel.\nOr use `{prefix}add <channel> <url> <name>` to add a new feed."
        messages[
            'no_items_on_page'] = f"Use `{prefix}list [channel] {page - 1}` to view the previous page."

        if list_channel == True:
            messages[
                'and_more'] = f"Use `{prefix}list [channel] [page]` to view a different page."
        else:
            messages[
                'and_more'] = f"Use `{prefix}list [page]` to view a different page."

        if list_channel == True:
            results = manage_feeds.get_feed_by_channel(channel.id)
            title = f"<#{channel.id}>"
        else:
            results = manage_feeds.get_feed_by_guild(ctx.message.guild.id)
            title = f"**{ctx.message.guild.name}**"

        embed = misc.create_embed_from_list(client=self.bot,
                                            guild=ctx.message.guild.id,
                                            results=results,
                                            title=title,
                                            messages=messages,
                                            page=page)

        await ctx.send(embed=embed)
        return
Exemplo n.º 13
0
    async def remove_command(self, ctx):
        if await misc.is_dm(ctx) == True:
            return

        author_ID = ctx.message.author.id
        prefix = json.load(open('settings/config.json',
                                'r'))['bot']['prefix'][0]
        # get actual message
        text = get_args(ctx, combine=True)

        await log(f"{prefix}remove executed.", 'spamInfo')

        user_permissions = ctx.message.author.guild_permissions
        if await misc.check_permission(ctx=ctx,
                                       required='editFeeds',
                                       user=user_permissions,
                                       author_ID=author_ID) == False:
            return

        if text == '':
            await ctx.send(
                content=
                f"<@!{author_ID}> Invalid or missing arguments. Use `{prefix}rmurl <url>`."
            )
            return

        results = manage_feeds.get_feed_by_name(text,
                                                ctx.message.guild.id,
                                                return_path=True)

        if len(results) == 1:
            with open('settings/database.json', 'r+') as f:
                database = json.load(f)
                feeds = database['feeds']

                feed_entry = int(results[0].split('-')[0])
                channels_entry = int(results[0].split('-')[1])

                del feeds[feed_entry]['channels'][channels_entry]

                if len(feeds[feed_entry]['channels']) == 0:
                    del feeds[feed_entry]

                # reset file position to the beginning - stackoverflow copy, dont ask
                f.seek(0)
                json.dump(database, f, indent=4)
                f.truncate()

            await ctx.send(
                content=
                f"<@!{author_ID}> Successfully deleted the entry **{text}**!")
            await log(f'**{text}** was removed.', 'info', client=self.bot)
            return
        elif len(results) > 1:
            await ctx.send(
                content=
                f"<@!{author_ID}> There are more results than one.\nUse `{prefix}removeall <name>` to remove all entries with a certain name.\nUse `{prefix}removeurl <url>` to remove all feeds with a certain url.\nUse `{prefix}find <name>` to find all entries with a certain name."
            )
            return
        elif len(results) < 1:
            await ctx.send(
                content=
                f"<@!{author_ID}> Could not find any feed with that name in this server. Use `{prefix}list` to list all entries in this server."
            )
            return

        await ctx.send(
            content=
            f"<@!{author_ID}> Something went wrong while trying delete the entry."
        )

        return
Exemplo n.º 14
0
    async def move_command(self, ctx):
        if await misc.is_dm(ctx) == True:
            return

        author_ID = ctx.message.author.id
        prefix = json.load(open('settings/config.json',
                                'r'))['bot']['prefix'][0]
        # get actual message
        args = get_args(ctx)

        await log(f"{prefix}move executed.", 'spamInfo')

        user_permissions = ctx.message.author.guild_permissions
        if await misc.check_permission(ctx=ctx,
                                       required='editFeeds',
                                       user=user_permissions,
                                       author_ID=author_ID) == False:
            return

        try:
            name = ' '.join(args[0:-1])
            channel = args[-1]

            if channel.startswith('<#'):
                channel = self.bot.get_channel(int(channel[2:-1]))
            else:
                await ctx.send(
                    content=
                    f"<@!{author_ID}> Invalid channel. Use `{prefix}move {self.add_command.usage}`."
                )
                return
        except IndexError:
            await ctx.send(
                content=
                f"<@!{author_ID}> Invalid or missing arguments. Use `{prefix}move <name> <new channel>`."
            )
            return

        results = manage_feeds.get_feed_by_name(name,
                                                ctx.message.guild.id,
                                                return_path=True)

        if len(results) == 1:
            with open('settings/database.json', 'r+') as f:
                database = json.load(f)
                feeds = database['feeds']

                feed_entry = int(results[0].split('-')[0])
                channels_entry = int(results[0].split('-')[1])

                for c in feeds[feed_entry]['channels']:
                    if c['channelID'] == channel.id:
                        await ctx.send(
                            content=
                            f"<@!{author_ID}> **{name}** is already registered in <#{c['channelID']}>. Use `{prefix}remove <name>` to remove the entry."
                        )
                        return

                feeds[feed_entry]['channels'][channels_entry][
                    'channelID'] = channel.id

                # reset file position to the beginning - stackoverflow copy, dont ask
                f.seek(0)
                json.dump(database, f, indent=4)
                f.truncate()

            await ctx.send(
                content=
                f"<@!{author_ID}> Successfully moved the entry **{name}** to <#{channel.id}>!"
            )
            await log(f'**{name}** was moved to <#{channel.id}>.',
                      'info',
                      client=self.bot)
            return
        elif len(results) > 1:
            await ctx.send(
                content=f"<@!{author_ID}> There are more results than one.")
            return
        elif len(results) < 1:
            await ctx.send(
                content=
                f"<@!{author_ID}> Could not find any feed with that name in this server. Use `{prefix}list` to list all entries in this server."
            )
            return

        await ctx.send(
            content=
            f"<@!{author_ID}> Something went wrong while trying to move the entry."
        )

        return
Exemplo n.º 15
0
    async def removeurl_command(self, ctx):
        if await misc.is_dm(ctx) == True:
            return

        author_ID = ctx.message.author.id
        prefix = json.load(open('settings/config.json',
                                'r'))['bot']['prefix'][0]
        # get actual message
        text = get_args(ctx, combine=True)

        await log(f"{prefix}removeurl executed.", 'spamInfo')

        user_permissions = ctx.message.author.guild_permissions
        if await misc.check_permission(ctx=ctx,
                                       required='editFeeds',
                                       user=user_permissions,
                                       author_ID=author_ID) == False:
            return

        if text == '':
            await ctx.send(
                content=
                f"<@!{author_ID}> Invalid or missing arguments. Use `{prefix}rmurl <url>`."
            )
            return

        results = manage_feeds.get_feed_by_url(text,
                                               ctx.message.guild.id,
                                               return_path=True)

        if len(results) >= 1:
            with open('settings/database.json', 'r+') as f:
                database = json.load(f)
                feeds = database['feeds']

                # reverse results
                # this is import because if entry #12 and #13 both have to be removed and entry #12 is removed first then the old #13 would be #12 now so it's important to start with #13 first and then go to #12
                results = results[::-1]

                for r in results:

                    feed_entry = int(r.split('-')[0])
                    channels_entry = int(r.split('-')[1])

                    del feeds[feed_entry]['channels'][channels_entry]

                    if len(feeds[feed_entry]['channels']) == 0:
                        del feeds[feed_entry]

                # reset file position to the beginning - stackoverflow copy, dont ask
                f.seek(0)
                json.dump(database, f, indent=4)
                f.truncate()

            await ctx.send(
                content=
                f"<@!{author_ID}> Successfully deleted all entries with the url {text}!"
            )
            await log(f"All entries with the url **{text}** were removed.",
                      'info',
                      client=self.bot)
            return
        elif len(results) < 1:
            await ctx.send(
                content=
                f"<@!{author_ID}> Could not find any feed with that url in this server. Use `{prefix}list` to list all entries in this server."
            )
            return

        await ctx.send(
            content=
            f"<@!{author_ID}> Something went wrong while trying delete the entry."
        )

        return
Exemplo n.º 16
0
    async def add_command(self, ctx):
        if await misc.is_dm(ctx) == True:
            return

        author_ID = ctx.message.author.id
        prefix = json.load(open('settings/config.json',
                                'r'))['bot']['prefix'][0]
        # get actual message
        args = get_args(ctx)

        await log(f"{prefix}add executed.", 'spamInfo')

        user_permissions = ctx.message.author.guild_permissions
        if await misc.check_permission(ctx=ctx,
                                       required='editFeeds',
                                       user=user_permissions,
                                       author_ID=author_ID) == False:
            return

        # make sure arguments exists and are valid
        try:
            if args[0].startswith('<#'):
                channel = self.bot.get_channel(int(args[0][2:-1]))
            else:
                await ctx.send(
                    content=
                    f"<@!{author_ID}> Invalid channel. Use `{prefix}add {self.add_command.usage}`"
                )
                return

            # check if channel is valid
            if await misc.is_valid_channel(
                    ctx=ctx,
                    channel=channel,
                    author_ID=author_ID,
                    command=f'{prefix}list [channel]') == False:
                return

            url = args[1]
            name = ' '.join(args[2:])
        except (IndexError, ValueError):
            await ctx.send(
                content=
                f"<@!{author_ID}> Invalid arguments. Use `{prefix}add {self.add_command.usage}`"
            )
            return

        result = manage_feeds.add_feed(channel=channel, url=url, name=name)

        if result == 'added':
            await ctx.send(
                content=
                f"<@!{author_ID}> **{name}** was successfully added to <#{channel.id}>!"
            )
            await log(f"**{name}** was added to <#{channel.id}>.",
                      'info',
                      client=self.bot)
        elif result == 'exists':
            await ctx.send(
                content=
                f"<@!{author_ID}> **{name}** is already registered in <#{channel.id}>. Use `{prefix}edit <name>` to edit the entry."
            )
            await log(f"**{name}** was already added to <#{channel.id}>.",
                      'spamInfo',
                      client=self.bot)
        else:
            await ctx.send(
                content=
                f"<@!{author_ID}> Something went wrong while adding **{name}**, it might\'ve been added, it might\'ve not. Use {prefix}list <#{channel}> to check whether it has been added or not."
            )

        return