Exemple #1
0
    async def todo_list(self, ctx, *, member: discord.Member = None):
        try:
            await ctx.message.delete()
        except discord.HTTPException:
            pass

        if member is None:
            member = ctx.author

        async with self.bot.todo_cache.acquire() as conn:
            entries = await conn.zrange(member.id, 0, -1)

        if not entries:
            return await ctx.send(f'{member.name} has no TODOs.',
                                  delete_after=15)

        entries = [
            f'**{index}:** {entry.decode()}'
            for index, entry in enumerate(entries, 1)
        ]
        pagey = buttons.Paginator(timeout=300,
                                  entries=entries,
                                  embed=True,
                                  title=f'{member.name} - TODOs',
                                  thumbnail=member.avatar_url,
                                  colour=0xbcf379)

        await pagey.start(ctx)
Exemple #2
0
    async def queue(self, ctx: commands.Context):
        player = self.get_player(ctx=ctx)

        if not player.queue:
            return await ctx.send('No more songs are queued.')

        entries = []
        if player._current.repeats:
            entries.append(
                f'**({player._current.repeats}x)** `{player._current.title}`')

        for song in player.queue[player.index + 1:]:
            entry = f'`{song.title}`'

            entries.append(entry)

        if not entries:
            return await ctx.send('No more songs are queued!', delete_after=10)

        pagey = buttons.Paginator(
            timeout=180,
            colour=0xebb145,
            length=10,
            title=f'Player Queue | Upcoming ({len(player.queue)}) songs.',
            entries=entries,
            use_defaults=True)

        await pagey.start(ctx)
Exemple #3
0
    async def last(self, ctx, days: int = None):
        """Used to get the last x days profit

        eg. `{prefix}last 7` (days has to be an integer)"""
        async with ctx.typing():
            data = load(open('Login_details/profit_graphing.json', 'r'))
            if days is None or days > len(data):
                days = len(data)
            ignored = len(data) - days
            await self.bot.loop.run_in_executor(None, self.gen_graph, days)

            last = buttons.Paginator(
                title=f'Last {days} days profit',
                colour=self.bot.color,
                embed=True,
                timeout=90,
                use_defaults=True,
                length=10,
                entries=[
                    f'__**{date}**__ - Days profit **{value[0]}** keys. Total profit '
                    f'**{value[1]}** keys. Predicted profit **{value[2]}** keys. '
                    f'Total trades **{value[3]}**'
                    for date, value in reversed(list(data.items())[ignored:])
                ])

            await last.start(ctx)
            f = File(self.location, filename="graph.png")
            await ctx.send(file=f)
Exemple #4
0
    async def reload(self, ctx, *, extension=None):
        """Reload an extension

        eg. `{prefix}reload staff`"""
        await ctx.trigger_typing()
        if extension is None:
            reloaded = []
            failed = []
            for extension in self.bot.initial_extensions:
                try:
                    self.bot.reload_extension(f'Cogs.{extension}')
                    self.bot.dispatch('extension_reload', extension)
                except commands.ExtensionNotLoaded:
                    try:
                        self.bot.load_extension(f'Cogs.{extension}')

                    except Exception as e:
                        self.bot.dispatch('extension_fail', ctx, extension, e, send=False)
                        failed.append((extension, e))

                    else:
                        self.bot.dispatch('extension_load', extension)
                        reloaded.append(extension)
                except Exception as e:
                    self.bot.dispatch('extension_fail', ctx, extension, e, send=False)
                    failed.append((extension, e))
                else:
                    self.bot.dispatch('extension_load', extension)
                    reloaded.append(extension)
            exc = f'\nFailed to load {len(failed)} cog{"s" if len(failed) > 1 else ""} ' \
                  f'(`{"`, `".join(fail[0] for fail in failed)}`)' if len(failed) > 0 else ""
            entries = ['\n'.join([f'{ctx.emoji.tick} `{r}`' for r in reloaded])]
            for f in failed:
                entries.append(f'{ctx.emoji.cross} `{f[0]}` - Failed\n```py\n{format_error(f[1])}```')
            reload = buttons.Paginator(
                title=f'Reloaded `{len(reloaded)}` cog{"s" if len(reloaded) != 1 else ""} {exc}',
                colour=get_colour(ctx), entries=entries, length=1
            )
            return await reload.start(ctx)
        try:
            self.bot.reload_extension(f'Cogs.{extension}')
        except commands.ExtensionNotLoaded:
            if extension in self.bot.initial_extensions:
                try:
                    self.bot.load_extension(f'Cogs.{extension}')
                    self.bot.dispatch('extension_reload', extension)

                except Exception as e:
                    self.bot.dispatch('extension_fail', ctx, extension, e)
                else:
                    await ctx.send(f'**`SUCCESS`** {ctx.emoji.tick} `{extension}` has been loaded')

        except Exception as e:
            self.bot.dispatch('extension_fail', ctx, extension, e)
        else:
            await ctx.send(f'**`SUCCESS`** {ctx.emoji.tick} `{extension}` has been reloaded')
Exemple #5
0
 async def mutelist(self, ctx):
     """Get a list of the currently muted members the reason for their mute and how long they will be muted for"""
     # todo add time until they are unmuted and sort by that along with the reason
     muted = discord.utils.get(ctx.guild.roles, name='Muted')
     muted_list = [
         member for member in ctx.guild.members if muted in member.roles
     ]
     paginator = buttons.Paginator(
         title=
         f'{len(muted_list)} Muted member{"s" if len(muted_list) > 1 else ""}',
         colour=discord.Colour.blurple(),
         length=5,
         entries=[f'{i}. {e}' for i, e in enumerate(muted_list, start=1)])
     await paginator.start(ctx)
Exemple #6
0
    async def history(self, ctx, days: int = 30):
        _sorted = {}
        file = load(open(f'{self.bot.files}/history.json', 'r'))
        try:
            black_list = open('Login_details/blacklist',
                              'r').read().splitlines()
        except FileNotFoundError:
            black_list = []

        for trade in file.values():
            try:
                if trade['time_sold'] + 60 * 60 * 24 * days > datetime.utcnow(
                ).timestamp():
                    if trade['time_sold'] and trade['name'] not in black_list:
                        profit = trade['bought'] - trade['sold']

                        human_time_to_sell = ago.human(
                            self.unix_parse(trade['time_bought']) -
                            self.unix_parse(trade['time_sold']))
                        _sorted[profit] = [trade['name'], human_time_to_sell]
            except KeyError:
                pass
        checker = buttons.Paginator(
            title='History checker',
            colour=self.bot.color,
            embed=True,
            timeout=90,
            use_defaults=True,
            entries=[
                f'**{index}.** {trade[1][0]}, was sold {trade[1][1]} for '
                f'{floor((trade[0] / 9) * 100) / 100 if trade[0] > 0 else -1 * floor(abs(trade[0]) / 9 * 100) / 100} '
                f'ref {"profit" if trade[0] > 0 else "loss"}' for index, trade
                in enumerate(sorted(_sorted.items(), reverse=True), start=1)
            ],
            length=10)
        await checker.start(ctx)
Exemple #7
0
    async def played(self, ctx, *args):
        """
        Check played games stats
        Usage:
        {prefix}played [enable|disable|delete|(user)]
        """
        user = ctx.author
        if len(args) > 0 and args[0] not in ('enable', 'disable', 'delete'):
            user = await commands.MemberConverter().convert(ctx, args[0])
            if user and not any(map(lambda x: x[0] == user.id, self.toTrack)):
                await ctx.send(
                    'Tagged person does not have played tracking enabled')
                return
        elif not any(map(lambda x: x[0] == user.id, self.toTrack)):
            if ctx.guild is None:
                await ctx.send(
                    'You can only enable the played command within a guild')
                return
            elif len(args) == 0 or args[0] != 'enable':
                await ctx.send(
                    f'I\'m currently not tracking your games, do `{self.bot.command_prefix}played enable` to enable'
                )
                return
            else:
                self.track(ctx.author.id, ctx.guild.id)
                await ctx.send(
                    f'Your games will now be tracked forever!!! >:) :smiling_imp:\ndo `{self.bot.command_prefix}played disable` to opt out *or `delete` to disable and delete all data*'
                )
                return

        if len(args) > 0 and args[0] in ('disable', 'delete'):
            self.stopTracking(ctx.author.id, args[0] == 'delete')
            await ctx.send('Game tracking is now disabled')
            return

        games = self.getUserPlayed(user.id)
        if games is None or len(games) < 1:
            await ctx.send(
                f'{"You" if user == ctx.author else "They"} haven\'t played any games yet!'
            )
            return

        games.sort(key=lambda x: x[1], reverse=True)
        pages = []
        page = ''
        i = 0
        for game in games:
            page += f'**{game[0]}** - {self.formatTime(game[1], game[2])}\n'
            i += 1
            if i > 10:
                i = 0
                pages.append(page)
                page = ''
        if i != 0: pages.append(page)
        p = buttons.Paginator(title=f'{user.name}\'s played stats',
                              colour=0x61C7C3,
                              embed=True,
                              timeout=10,
                              use_defaults=True,
                              entries=pages,
                              length=1)
        await p.start(ctx)
Exemple #8
0
    async def money(self, ctx, curFrom=None, curTo=None, amount=None):
        """
        Converts an amount of one currency to another
        <example>
        <cmd></cmd>
        <res>*Starts paginator with all the available currencies*</res>
        <cmd>currency</cmd>
        <res>Sends info about currency</res>
        <cmd>a b [amount]</cmd>
        <res>Converts amount of a to b</res>        
        </example>
        """
        now = pendulum.now().timestamp()
        needs_update = lambda x: True if x is None else now - x > self.update_time
        # No arguments were passed, and should display all available currencies
        if curFrom is None:
            if needs_update(self.currencies[1]):
                async with aiohttp.ClientSession() as session:
                    usage = await self.get_usage(session)
                    if usage < 90: await self.update_currencies(session)
            # Get a list of all currencies and sort it
            keys = list(self.currencies[0].keys())
            keys.sort()
            formatted = []
            for key in keys:
                c = self.currencies[0][key]
                # Format so its like "USD - United States Dollar"
                formatted.append(f"{key} - {c['currencyName']}")
            
            nperpage = 30
            pages = []
            while len(formatted):
                msg = ''
                for _ in range(nperpage):
                    if len(formatted) == 0: break
                    msg += formatted[0]+'\n'
                    formatted.pop(0)
                pages.append(msg)
            
            p = buttons.Paginator(title='List of available currencies', colour=0x8BF488, embed=True, timeout=30, use_defaults=True,
                entries=pages, length=1, format='```')
            await p.start(ctx)
        # If curFrom is not None and curTo is, display info about given currency
        # {currencyName} - {currencySymbol}
        elif curTo is None:
            if needs_update(self.currencies[1]):
                async with aiohttp.ClientSession() as session:
                    usage = await self.get_usage(session)
                    if usage < 90: await self.update_currencies(session)
            curFrom = curFrom.upper()
            info = self.currencies[0].get(curFrom)
            if info is None:
                await ctx.send(f'Unknown currency! do `{self.bot.command_prefix}money` to see a list of all available ones.')
            else:
                name = info['currencyName']
                symbol = info.get('currencySymbol')
                await ctx.send(f"{name}{' - '+symbol if symbol else ''}")
        # Converts curFrom to curTo, as they both aren't None
        else:
            curFrom = curFrom.upper()
            curTo = curTo.upper()
            if curFrom == curTo:
                return await ctx.send('no')

            if needs_update(self.currencies[1]):
                async with aiohttp.ClientSession() as session:
                    usage = await self.get_usage(session)
                    if usage < 90: await self.update_currencies(session)

            # Check if they are valid currencies
            if curFrom not in self.currencies[0] or curTo not in self.currencies[0]:
                return await ctx.send(f'Unknown currency! do `{self.bot.command_prefix}money` to see a list of all available ones.')
           
            amount = amount or 1
            try:
                amount = float(amount)
            except ValueError:
                return await ctx.send('Invalid amount')

            if amount == 0 or not math.isfinite(amount):
                return await ctx.send('no')

            async with aiohttp.ClientSession() as session:
                # Updating curFrom
                tmp = self.currency_rates.get(curFrom)
                if needs_update(tmp[1] if tmp is not None else None):
                    usage = await self.get_usage(session)
                    if usage < 90: await self.update_currency(session, curFrom)
                # Updating curTo
                tmp = self.currency_rates.get(curTo)
                if needs_update(tmp[1] if tmp is not None else None):
                    usage = await self.get_usage(session)
                    if usage < 90: await self.update_currency(session, curTo)
                    
                val = self.convert_currency(curFrom, curTo, amt=amount)
                await ctx.send(f'{amount} {curFrom} is about {val:.2f} {curTo}')