Exemplo n.º 1
0
    async def _list(self, ctx):
        """ Check your todo list """
        todos = []
        for num, todo, in enumerate(await self.bot.db.fetch(
                'SELECT todo FROM todolist WHERE user_id = $1 ORDER BY time ASC',
                ctx.author.id),
                                    start=0):
            if len(todo['todo']) > 195:
                yourtodo = todo['todo'][:190] + '...'
            elif len(todo['todo']) < 195:
                yourtodo = todo['todo']
            todos.append(f"`[{num + 1}]` {yourtodo}\n")

        if len(todos) == 0:
            return await ctx.send(f"{emotes.red_mark} You don't have any todos"
                                  )

        paginator = Pages(ctx,
                          title=f"Your todo list:",
                          entries=todos,
                          thumbnail=None,
                          per_page=10,
                          embed_color=self.color['embed_color'],
                          show_entry_count=True)
        try:
            await paginator.paginate()
        except discord.HTTPException:
            paginators = Pages(ctx,
                               title=f"Your todo list:",
                               entries=todos,
                               thumbnail=None,
                               per_page=5,
                               embed_color=self.color['embed_color'],
                               show_entry_count=True)
            await paginators.paginate()
Exemplo n.º 2
0
    async def permissions(self, ctx, member: discord.Member = None):
        """ See what permissions member has in the guild. """

        member = member or ctx.author
        
        sperms = dict(member.guild_permissions)

        perm = []
        for p in sperms.keys():
            if sperms[p] == True and member.guild_permissions.administrator == False:
                perm.append(f"{emotes.white_mark} {p}\n")
            if sperms[p] == False and member.guild_permissions.administrator == False:
                perm.append(f"{emotes.red_mark} {p}\n")

        if member.guild_permissions.administrator == True:
            perm = [f'{emotes.white_mark} Administrator']

        
        paginator = Pages(ctx,
                          title=f"{member.name} guild permissions",
                          entries=perm,
                          thumbnail=None,
                          per_page = 20,
                          embed_color=ctx.bot.embed_color,
                          show_entry_count=False,
                          author=ctx.author)
        await paginator.paginate()
Exemplo n.º 3
0
    async def remind_list(self, ctx):
        """ Check your reminders list """
        check_reminders = CM.get(self.bot, 'reminders', ctx.author.id)

        if not check_reminders:
            return await ctx.send(
                _("{0} You have no reminders.").format(
                    self.bot.settings['emojis']['misc']['warn']))

        reminders = []
        for result in check_reminders:
            when = btime.human_timedelta(check_reminders[result]['time'],
                                         source=ctx.message.created_at)
            content = check_reminders[result]['content']
            reminders.append(
                _("`[{0}]` Reminding in **{1}**\n{2}\n").format(
                    result, when,
                    content[:150] + '...' if len(content) > 150 else content))

        paginator = Pages(
            ctx,
            entries=reminders,
            thumbnail=None,
            per_page=10,
            embed_color=ctx.bot.settings['colors']['embed_color'],
            embed_author=_("{0}'s Reminders").format(ctx.author),
            show_entry_count=True)
        await paginator.paginate()
Exemplo n.º 4
0
    async def queue(self, ctx):
        """Retrieve information on the next 5 songs from the queue."""
        player = self.bot.wavelink.get_player(ctx.guild.id,
                                              cls=Player,
                                              context=ctx)

        if not player.current or not player.queue._queue:
            return await ctx.send(
                _('There are no songs currently in the queue.'),
                delete_after=20)

        upcoming = []
        total_duration = 0
        for num, item in list(
                enumerate(itertools.islice(player.queue._queue, 0,
                                           player.queue.qsize()),
                          start=1)):
            upcoming.append(
                f"`[{num}]` {item} ({str(datetime.timedelta(milliseconds=int(item.length)))})\n"
            )
            total_duration += item.length

        paginator = Pages(
            ctx,
            title=_("{0} Queue. Duration: {1}").format(
                ctx.guild.name,
                str(datetime.timedelta(milliseconds=int(total_duration)))),
            entries=upcoming,
            thumbnail=None,
            per_page=10,
            embed_color=self.bot.settings['colors']['embed_color'],
            footertext=_("Total songs in the queue: {0}").format(
                player.queue.qsize()),
            author=ctx.author)
        await paginator.paginate()
Exemplo n.º 5
0
    async def roles(self, ctx, *, role: discord.Role = None):
        """ List of all the roles in the server

        Providing a role mention will show all the members in that role. """
        allroles = []

        if not role:
            for num, roles in enumerate(sorted(ctx.guild.roles, reverse=True), start=1):
                if roles.is_default():
                    continue
                allroles.append(f"`[{str(num).zfill(2)}]` {roles.mention} | {roles.id} | **[ Users : {len(roles.members)} ]**\n")
        elif role:
            for num, member in enumerate(role.members, start=1):
                allroles.append(f"`[{str(num).zfill(2)}]` {member.mention} | {member.id} | **[ Total Roles : {len(member.roles)} ]**\n")

        if len(allroles) == 0:
            return await ctx.send(_("{0} Server has no roles").format(self.bot.settings['emojis']['misc']['warn']))

        # data = BytesIO(allroles.encode('utf-8'))
        paginator = Pages(ctx,
                          title=_("Roles in {0}").format(ctx.guild.name) if not role else _("Members in {0}").format(role.name),
                          entries=allroles,
                          thumbnail=None,
                          per_page=15,
                          embed_color=self.bot.settings['colors']['embed_color'],
                          show_entry_count=True,
                          author=ctx.author)
        await paginator.paginate()
Exemplo n.º 6
0
    async def cases(self, ctx, member: converters.UserConverter):
        """View all mod cases for a member."""

        query = 'SELECT * FROM mod_cases WHERE user_id = $1 ORDER BY issued DESC;'
        records = await self.bot.pool.fetch(query, member.id)

        if len(records) == 0:
            return await ctx.send("None found.")

        entries = []
        for record in records:
            id = record['id']
            action = record['action']
            issued = time.human_timedelta(datetime.datetime.utcnow() -
                                          record['issued'],
                                          largest_only=True)
            duration = record['duration']
            duration = time.human_timedelta(
                duration) if duration is not None else None
            reason = record['reason']

            if duration is None:
                entries.append(
                    f'#{id} • *{action.capitalize()}* • {reason} • {issued} ago'
                )
            else:
                entries.append(
                    f'#{id} • *{action.capitalize()}* ({duration}) • {reason} • {issued} ago'
                )

        p = Pages(ctx, entries=entries)
        p.embed.set_author(name=f'{member} Cases', icon_url=member.avatar_url)
        p.embed.colour = discord.Colour.red()
        await p.paginate()
Exemplo n.º 7
0
    async def todo_list(self, ctx):
        """ Once you've added todos to your todo list you can use this command to check them. """
        todos = await self.bot.db.fetch(
            "SELECT DISTINCT todo, time, ROW_NUMBER () OVER (ORDER BY time) FROM todos WHERE user_id = $1 ORDER BY time",
            ctx.author.id)
        if not todos:
            return await ctx.send(
                _("{0} You don't have any items in your todo list.").format(
                    self.bot.settings['emojis']['misc']['warn']))
        todol = []
        for res in todos:
            if len(res['todo']) > 195:
                yourtodo = res['todo'][:190] + '...'
            elif len(res['todo']) < 195:
                yourtodo = res['todo']
            todol.append(f"`[{res['row_number']}]` {yourtodo}\n")

        paginator = Pages(
            ctx,
            entries=todol,
            thumbnail=None,
            per_page=10,
            embed_color=ctx.bot.settings['colors']['embed_color'],
            embed_author=_("{0}'s Todo List").format(ctx.author),
            show_entry_count=True)
        await paginator.paginate()
Exemplo n.º 8
0
    async def permissions(self, ctx, member: discord.Member = None):
        """ See what permissions member has in the server. """

        member = member or ctx.author

        sperms = dict(member.guild_permissions)
        del sperms['admin']

        perm = []
        for p in sperms.keys():
            if sperms[p] is True and not member.guild_permissions.administrator:
                perm.append(
                    f"{self.bot.settings['emojis']['misc']['enabled']} {p.replace('_', ' ').title()}\n"
                )
            if sperms[
                    p] is False and not member.guild_permissions.administrator:
                perm.append(
                    f"{self.bot.settings['emojis']['misc']['disabled']} {p.replace('_', ' ').title()}\n"
                )

        if member.guild_permissions.administrator:
            perm = [
                f"{self.bot.settings['emojis']['misc']['enabled']} Administrator"
            ]

        paginator = Pages(
            ctx,
            title=_("{0}'s Server Permissions").format(member.name),
            entries=perm,
            thumbnail=None,
            per_page=20,
            embed_color=ctx.bot.settings['colors']['embed_color'],
            show_entry_count=False,
            author=ctx.author)
        await paginator.paginate()
Exemplo n.º 9
0
	async def seenon(self, ctx, *, user:discord.User=None):
		if user is None:
			user = ctx.author
		elif not await self.bot.is_owner(ctx.author) \
		and (user == self.bot.user or await self.bot.is_owner(user)):
			return await ctx.send('no')
		resp = await self.bot.rpc.seen_on(
			ctx.message.id,
			shards=True,
			guild=ctx.guild.id if ctx.guild else None,
			user=user.id
		)
		seen_on = list(resp)
		try:
			p = Pages(ctx, entries=seen_on, per_page=30,
				extra_info='# at the end of each name refers to the shard.'
			)
			p.embed.title = 'Guilds Seen On'
			if self.bot._connection.guild_subscriptions is False:
				p.embed.description = "Member cache is disabled," \
					"this will only show if they've been added to the cache."
			p.embed.color = 0x738bd7
			p.embed.set_author(name=user.display_name, icon_url=user.avatar_url or user.default_avatar_url)
			await p.paginate()
		except CannotPaginate:
			joined = ', '.join(seen_on)
			if len(joined) >= 2000:
				return await ctx.send(
					'\N{NO ENTRY} `Too many seen on guilds for non-embed response, please allow me to post embeds!`'
				)
			await ctx.send(f"**Guilds Seen On for __{user}__**\n`{joined}`")
Exemplo n.º 10
0
    async def temprole_list(self, ctx, member: discord.Member = None):
        """Lists temporary roles."""

        if member is None:
            query = 'SELECT * FROM temproles INNER JOIN timers ON temproles.timer_id = timers.id ORDER BY timers.expires;'
            records = await self.bot.pool.fetch(query)
        else:
            query = 'SELECT * FROM temproles INNER JOIN timers ON temproles.timer_id = timers.id WHERE user_id = $1 ORDER BY timers.expires;'
            records = await self.bot.pool.fetch(query, member.id)

        if len(records) == 0:
            return await ctx.send('No temporary roles to list.')

        # embed = discord.Embed(title='Temprole List', colour=discord.Colour.green())

        # embed.description = ''
        entries = []
        for record in records:
            user = discord.utils.get(ctx.guild.members, id=record['user_id'])
            role = discord.utils.get(ctx.guild.roles, id=record['role_id'])
            expires = record['expires'].isoformat(timespec='minutes')

            # embed.description = embed.description + f'**{user}** {role} **Expires:** {expires} UTC\n'
            entries.append(f'**{user}** {role} **Expires:** {expires} UTC')

        p = Pages(ctx, entries=entries)
        p.embed.set_author(name='Temprole List')
        p.embed.colour = discord.Colour.green()
        await p.paginate()
Exemplo n.º 11
0
    async def roles(self, ctx):
        """ List of roles in the server """
        allroles = []

        for num, role in enumerate(sorted(ctx.guild.roles, reverse=True),
                                   start=1):
            if role.is_default():
                continue
            allroles.append(
                f"`[{str(num).zfill(2)}]` {role.mention} | {role.id} | **[ Users : {len(role.members)} ]**\n"
            )

        if len(allroles) == 0:
            return await ctx.send(f"{emotes.red_mark} Server has no roles")

        #data = BytesIO(allroles.encode('utf-8'))
        paginator = Pages(ctx,
                          title=f"{ctx.guild.name} roles list",
                          entries=allroles,
                          thumbnail=None,
                          per_page=15,
                          embed_color=ctx.bot.embed_color,
                          show_entry_count=True,
                          author=ctx.author)
        await paginator.paginate()
Exemplo n.º 12
0
    async def search(self, ctx, *, query: str):
        """Shows results for the queried keyword(s) in McGill courses"""
        keyword = query.replace(" ", "+")
        pagelimit = 5
        pagenum = 0
        courses = []
        while (True and pagenum < pagelimit):
            url = "http://www.mcgill.ca/study/2018-2019/courses/search\
            ?search_api_views_fulltext=%s&sort_by=field_subject_code&page=%d" % (
                keyword, pagenum)
            r = requests.get(url)
            soup = BeautifulSoup(r.content, "html.parser")
            found = soup.find_all("div", {"class": "views-row"})
            if (len(found) < 1):
                break
            else:
                courses = courses + found
                pagenum += 1
        if (len(courses) < 1):
            await ctx.send("No course found for: %s." % query)
            return

        courseList = {'names': [], 'values': []}
        for course in courses:
            # split results into titles + information
            title = course.find_all("h4")[0].get_text().split(" ")
            courseList['names'].append(' '.join(title[:2]))
            courseList['values'].append(' '.join(title[2:]))
        p = Pages(ctx,
                  itemList=courseList,
                  title='Courses found for {}'.format(query),
                  option='EMBEDS',
                  editableContent=False)
        await p.paginate()
Exemplo n.º 13
0
 async def remind_list(self, ctx):
     sql = 'SELECT * FROM `reminders` WHERE user={0}'.format(ctx.author.id)
     q = await self.cursor.execute(sql)
     result = await q.fetchall()
     if not result:
         return await ctx.send(
             "\N{NO ENTRY} You don't have any reminders set!")
     try:
         entries = [
          f"**__{human_timedelta(datetime.fromtimestamp(x['time']))}__**" \
          f"\n{x['message'] or ''}" \
          for x in result
         ]
         p = Pages(ctx, entries=entries, per_page=8, show_zero=False)
         p.embed.title = 'Reminders'
         p.embed.color = self.bot.funcs.get_color()()
         p.embed.set_author(name=ctx.author.display_name,
                            icon_url=ctx.author.avatar_url_as())
         await p.paginate()
     except CannotPaginate:
         reminders = []
         count = 0
         for reminder in result:
             created_at = human_timedelta(
                 datetime.fromtimestamp(reminder['time']))
             if reminder['message'] is not None:
                 reminders.append('**{0}.** __{2}__: `{1}`'.format(
                     count, reminder['message'], created_at))
             else:
                 reminders.append('**{0}.** __{1}__'.format(
                     count, created_at))
             count += 1
         await self.truncate(
             ctx.channel, '**Reminders**\n{0}'.format('\n'.join(reminders)))
Exemplo n.º 14
0
    async def locked(self, ctx, typ="Embed"):
        """[M] List all locked members"""

        entries = [self.bot.get_user(uid) for uid in ctx.config['locked']]

        if typ.lower() in ('embed', 'e'):
            p = Pages(self.bot,
                      message=ctx.message,
                      entries=[e.mention for e in entries])
            p.embed.set_author(name="Locked members")
            await p.paginate()

        elif typ.lower() in ('text', 'txt', 't'):
            fmt = '```'
            for e in entries:
                fmt += e.name + "\n"
            fmt += '```'
            try:
                await ctx.send(fmt)
            except:  # noqa
                await ctx.send(
                    f"List too long, use `{ctx.prefix}locked embed` for a paginated version."
                )
        else:
            await ctx.send("Invalid type! Can be either `text` or `embed`")
Exemplo n.º 15
0
    async def userlist(self, ctx):
        """ Whole list of users that bot can see """

        try:
            await ctx.message.delete()
        except:
            pass
        async with ctx.channel.typing():
            await asyncio.sleep(2)
        user_list = []
        for user in self.bot.users:
            user_list.append(user)

        user_lists = []  # Let's list the users
        for num, user in enumerate(user_list, start=0):
            user_lists.append(
                f'`[{num + 1}]` **{user.name}** ({user.id})\n**Created at:** {btime.human_timedelta(user.created_at)}\n**────────────────────────**\n'
            )

        paginator = Pages(ctx,
                          title=f"__Users:__ `[{len(user_lists)}]`",
                          entries=user_lists,
                          per_page=10,
                          embed_color=self.bot.embed_color,
                          show_entry_count=False,
                          author=ctx.author)

        await paginator.paginate()
Exemplo n.º 16
0
    async def _list(self, ctx, page: int = 1):
        """List the guilds I am in."""
        try:
            await ctx.message.delete()
        except:
            pass
        guild_list = []
        for num, guild in enumerate(self.bot.guilds, start=0):
            people = len([x for x in guild.members if not x.bot])
            bots = len([x for x in guild.members if x.bot])
            botfarm = int(100 / len(guild.members) * bots)
            guild_list.append(
                f"`[{num + 1}]` {guild} ({guild.id}) `[Ratio: {botfarm}%]`\n**Joined:** {humanize.naturaltime(guild.get_member(self.bot.user.id).joined_at)}\n"
            )

        paginator = Pages(ctx,
                          title=f"Guilds I'm In:",
                          thumbnail=None,
                          entries=guild_list,
                          per_page=10,
                          embed_color=self.bot.embed_color,
                          show_entry_count=False,
                          author=ctx.author)

        await paginator.paginate()
Exemplo n.º 17
0
 async def duckduckgo(self, ctx, *, search: str):
     """Search duckduckgo.com"""
     load = await self.f_api(ctx.command.name, text=search, json=True)
     if isinstance(load, str):
         return await ctx.send(load)
     elif not load or not any(load.values()):
         return await ctx.send("\N{WARNING SIGN} `Invalid Search.`")
     urls = load['results'] if 'results' in load else None
     card = load['cards'] if 'cards' in load else {}
     ecard = Embed.from_dict(card)
     ecard.color = 0x738bd7
     try:
         p = Pages(ctx,
                   embed=ecard,
                   google=bool(card),
                   per_page=3,
                   entries=[f"**{x['title']}**\n{x['link']}" for x in urls])
         if card is None and not p.embed.title:
             p.embed.title = 'DuckDuckGo Results'
         p.embed.set_author(name=ctx.author.display_name,
                            icon_url=ctx.author.avatar_url
                            or ctx.author.default_avatar_url)
         await p.paginate()
     except CannotPaginate:
         more = '\n'.join([f"<{x['link']}>" for x in urls[1:4]])
         await ctx.send(
             f"**{urls[0]['title']}**\n{urls[0]['link']}\n\n__More Results__\n{more}"
         )
Exemplo n.º 18
0
 async def google(self, ctx, *, search: str):
     """Search the largest search engine on the internet"""
     level = await self.google_safety(ctx.message, True)
     urls, card = await self.google_scrap(search,
                                          True if level != 'off' else False,
                                          False)
     if not urls and not card:
         return await ctx.send("\N{WARNING SIGN} `Invalid Search.`")
     try:
         p = Pages(ctx,
                   embed=card,
                   color=0x738bd7,
                   google=bool(card),
                   entries=[f'**{x[0]}**\n{x[1]}' for x in urls],
                   per_page=3,
                   method=2)
         if card is None:
             p.embed.title = 'Google Search Results'
         p.embed.set_author(name=ctx.author.display_name,
                            icon_url=ctx.author.avatar_url
                            or ctx.author.default_avatar_url)
         await p.paginate()
     except CannotPaginate:
         more = '\n'.join([f'<{x[1]}>' for x in urls[1:4]])
         await ctx.send(
             f'**{urls[0][0]}**\n{urls[0][1]}\n\n__More Results__\n{more}')
Exemplo n.º 19
0
    async def queue(self, ctx):
        """Shows the current queue."""
        vc = ctx.voice_client
        if vc is None:
            return await ctx.send('Not in a voice channel.')

        if not vc.is_playing() and not vc.is_paused():
            return await ctx.send('Not currently playing anything.')

        queue = self.get_queue(ctx.guild).songs._queue

        if len(queue) == 0:
            return await ctx.invoke(self.playing)
        songs = [
            f'[{song.entry.title}]({song.entry.url})\nRequested by {song.requester}'
            for song in queue
        ]
        try:
            p = Pages(ctx, entries=songs, per_page=10)
            p.embed.colour = 0x738bd7
            p.embed.title = f'Currently Playing {vc.source.entry.title} requested by {vc.source.requester}'
            p.embed.url = vc.source.entry.url
            await p.paginate()
        except Exception as e:
            await ctx.send(e)
Exemplo n.º 20
0
    async def send_cog_help(self, cog):
        if cog.qualified_name in self.ignore_cogs:
            return await self.send_error_message(await self.command_not_found(
                cog.qualified_name.lower()))
        if cog.qualified_name in self.owner_cogs and not await self.context.bot.is_owner(
                self.context.author):
            return await self.send_error_message(await self.command_not_found(
                cog.qualified_name.lower()))
        if cog.qualified_name in self.admin_cogs and not await self.context.bot.is_admin(
                self.context.author):
            return await self.send_error_message(await self.command_not_found(
                cog.qualified_name.lower()))
        if cog.qualified_name in self.booster_cogs and not await self.context.bot.is_booster(
                self.context.author):
            return await self.send_error_message(await self.command_not_found(
                cog.qualified_name.lower()))
        if await checks.cog_disabled(self.context, cog.qualified_name):
            return await self.send_error_message(await self.command_not_found(
                cog.qualified_name.lower()))

        commands = []
        if cog.aliases:
            commands.append(
                _("**Category aliases:** {0}\n").format(
                    '`' + '`, `'.join(cog.aliases) + '`'))
        c = 0
        for cmd in cog.get_commands():
            if cmd.hidden and not await self.context.bot.is_admin(
                    self.context.author):
                continue
            if await checks.is_disabled(
                    self.context, cmd) and not await self.context.bot.is_admin(
                        self.context.author):
                continue
            if cmd.short_doc is None:
                brief = _('No information.')
            else:
                brief = cmd.short_doc

            if not cmd.hidden or not await checks.is_disabled(
                    self.context, cmd):
                if not await self.context.bot.is_admin(self.context.author):
                    c += 1
                else:
                    c += 1
            commands.append(f"`{cmd.qualified_name}` - {brief}\n")

        paginator = Pages(
            self.context,
            title=f"{cog.qualified_name.title()} ({c})",
            thumbnail=cog.big_icon,
            entries=commands,
            per_page=12,
            embed_color=self.context.bot.settings['colors']['embed_color'],
            show_entry_count=False,
            author=self.context.author)

        await paginator.paginate()
Exemplo n.º 21
0
	async def stats(self, ctx):
		data = await self.pool.hgetall('cmd_stats', encoding='utf-8')
		data = {x: int(data[x]) for x in data}
		entries = [f"`{x}` - {int(data[x]):,}"
							 for x in sorted(data, reverse=True, key=data.get)]
		p = Pages(ctx, entries=entries, per_page=25, method=2)
		p.embed.title = '\N{KEYBOARD} Top Commands (Since 07/14/2018):'
		p.embed.color = 0x3498db
		await p.paginate()
Exemplo n.º 22
0
    async def lyrics(self, ctx, *, title):
        """ Get song lyrics """
        def split_lyrics(lyr, page_size=2048, newline_max=None):
            verses = lyr.split("\n\n")

            joined_verses = []

            while len(verses) > 0:
                joined_verse = ""
                verse_count = 0
                newline_count = 0

                while True:
                    v = verses[verse_count:]
                    if len(verses[verse_count:]) == 0:
                        break

                    verse_to_be_added = verses[verse_count:][0]

                    if len(verse_to_be_added) > page_size or (
                            newline_max is not None and verse_to_be_added.count("\n") > newline_max):
                        return None
                    if (len(joined_verse) + len(verse_to_be_added)) + len("\n\n") > page_size:
                        break
                    if newline_max is not None and newline_count > newline_max:
                        break

                    joined_verse = (joined_verse + "\n\n" + verse_to_be_added).strip()
                    newline_count = joined_verse.count("\n")
                    verse_count = verse_count + 1

                verses = verses[verse_count:]
                joined_verses.append(joined_verse)

            return joined_verses

        genius = lyricsgenius.Genius(config.GENIUSTOKEN, verbose=False)

        song = await genius.search_song(title)

        if song is None:
            return await ctx.send("Couldn't find any song by that title.")

        verse_array = split_lyrics(song.to_text(), newline_max=30)

        if verse_array is None:
            return await ctx.send("Verse size exceeds maximum. You can find the lyrics at {0}".format(song.url))

        paginator = Pages(ctx,
                          title="{0} by {1}".format(song.title, song.artist),
                          entries=verse_array,
                          thumbnail=song.header_image_url,
                          per_page=1,
                          embed_color=discord.Color.dark_teal(),
                          show_entry_count=True)
        await paginator.paginate()
Exemplo n.º 23
0
    async def quipqiup_beta2(self, ctx, *, query=None):

        if not query:
            await ctx.send(
                'Example: `!qq cbg bfabdbebfab` or `!qq cbg bfabdbebfab c=s b=a`'
            )
            return

        # set up query
        clues = ''
        poseq = [m.start() for m in re.finditer('=', query)]
        if poseq:
            clues = query[poseq[0] - 1:]
            query = query[:poseq[0] - 2]

        # data scrapper adapted from
        # https://github.com/cmpunches/NSA-CryptoChallenge-Solver/blob/340ba7f65072bf00bdc2a4d0cc313d50e3ba6070/cryptochallenge-solver.py
        client = requests.Session()
        client.headers.update({
            'Accept-Encoding': "gzip, deflate, br",
            'Referer': "https://quipqiup.com/",
            'Content-type': "application/x-www-form-urlencoded",
            'Origin': "https://quipqiup.com/"
        })
        body = {"ciphertext": query, "clues": clues, "time": 5}
        rawresult = client.post(
            "https://6n9n93nlr5.execute-api.us-east-1.amazonaws.com/prod/dict",
            json.dumps(body)).content
        obj = json.loads(rawresult.decode())
        print(obj)

        # set up embed template
        embed = discord.Embed(title='Quipqiup',
                              colour=discord.Colour.dark_orange())
        if clues:
            embed.set_footer(text='Query: ' + query + '\nKey: ' + clues)
        elif not clues:
            embed.set_footer(text='Query: ' + query)

        # send result
        if 'errorMessage' in obj:
            final = 'Exited with error message: \n' + obj['errorMessage']
            embed.description(final)
            await ctx.send(embed=embed)

        else:
            solnsort = sorted(obj['solutions'],
                              key=lambda k: k['logp'],
                              reverse=True)
            solns = []
            weights = []
            for n in range(0, len(solnsort)):
                solns.append(solnsort[n]['plaintext'])
                weights.append(solnsort[n]['logp'])
            p = Pages(ctx, solutions=solns, weights=weights, embedTemp=embed)
            await p.pageLoop()
Exemplo n.º 24
0
    async def partnerslist(self, ctx):
        """ Displays a list of partners and information how to become a partner """
        partners = await self.bot.db.fetch(
            "SELECT * FROM partners ORDER BY time ASC")

        partner = []
        for res in partners:
            if res['type'] == 0:
                partnered = f"{self.bot.get_user(res['_id'])} ({res['_id']})"
                ptype = f"Bot: [{self.bot.get_user(res['bot_id'])}](https://discord.com/users/{res['bot_id']})"
                if partnered is None:
                    partnered = f"({res['_id']})"
            elif res['type'] == 1:
                guild = self.bot.get_guild(res['_id'])
                if guild is not None:
                    try:
                        guildinv = await guild.invites()
                        for inv in guildinv[:1]:
                            partnered = f"[{guild}]({inv}) ({res['_id']}) | Owner: {guild.owner} ({guild.owner.id})"
                    except Exception:
                        partnered = f"{guild} ({res['_id']}) | Owner: {guild.owner} ({guild.owner.id})"
                    ptype = _('Server')
                elif not guild and res['valid']:
                    partnered = f"[{res['name']}]({res['invite']})"
                    ptype = _('Server')
                else:
                    partnered = f"({res['_id']})"
                    ptype = 'Invalid type, unpartner.'
            partner.append(
                _("**Partner:** {0}\n"
                  "**Partnered for:** {1}\n"
                  "**Partner type:** {2}\n"
                  "**Partnered message:**\n>>> {3}").format(
                      partnered,
                      btime.human_timedelta(res['time'],
                                            source=datetime.utcnow(),
                                            suffix=None), ptype,
                      res['message']))

        msg = await self.bot.get_channel(
            self.bot.settings['channels']['partners']
        ).fetch_message(741690217379135569)
        partner.append(
            _("Interested in partnering? Here's the official message:\n\n{0}"
              " or [join the support server]({1})").format(
                  msg.content, self.bot.support))

        paginator = Pages(
            ctx,
            title=_("Partnered people with Dredd"),
            entries=partner,
            thumbnail=None,
            per_page=1,
            embed_color=self.bot.settings['colors']['embed_color'],
            show_entry_count=True)
        await paginator.paginate()
Exemplo n.º 25
0
    async def send_cog_help(self, cog):
        if cog.qualified_name in self.ignore_cogs:
            return await self.send_error_message(
                self.command_not_found(cog.qualified_name.lower()))
        if cog.qualified_name in self.owner_cogs and not await self.context.bot.is_owner(
                self.context.author):
            return await self.send_error_message(
                self.command_not_found(cog.qualified_name.lower()))
        if cog.qualified_name in self.admin_cogs and not await self.context.bot.is_admin(
                self.context.author):
            return await self.send_error_message(
                self.command_not_found(cog.qualified_name.lower()))
        if cog.qualified_name in self.vip_cogs and not await self.context.bot.is_booster(
                self.context.author):
            return await self.send_error_message(
                self.command_not_found(cog.qualified_name.lower()))

        commands = []
        c = 0
        for cmd in cog.get_commands():
            if cmd.hidden:
                continue
            if await self.context.bot.db.fetchval(
                    "SELECT * FROM guilddisabled WHERE guild_id = $1 AND command = $2",
                    self.context.guild.id, str(cmd)):
                continue
            if await self.context.bot.db.fetchval(
                    "SELECT * FROM cmds WHERE command = $1", str(cmd)):
                continue
            if cmd.short_doc is None:
                brief = 'No info'
            else:
                brief = cmd.short_doc

            if not cmd.hidden or not await self.context.bot.db.fetchval(
                    "SELECT * FROM guilddisabled WHERE guild_id = $1 AND command = $2",
                    self.context.guild.id,
                    str(cmd)) or not await self.context.bot.db.fetchval(
                        "SELECT * FROM cmds WHERE command = $1", str(cmd)):
                c += 1

            commands.append(f"`{cmd.qualified_name}` - {brief}\n")

        paginator = Pages(self.context,
                          title=f"{cog.qualified_name.title()} ({c})",
                          thumbnail=cog.big_icon,
                          entries=commands,
                          per_page=12,
                          embed_color=self.color['embed_color'],
                          show_entry_count=False,
                          author=self.context.author)

        await paginator.paginate()
Exemplo n.º 26
0
 async def tags(self, ctx):
     g = mongo_setup.tags.find_one({'_id': ctx.guild.id}) # if theres tags for ctx.guild, then the dict should be formatted like: {'tag name': {'author': user id, 'value': 'tag value'}}
     if not g:
         return await ctx.send("This server has no tags yet.")
     tag_info = []
     for key, val in g.items():
         if not isinstance(val, dict): # yea this is probably useless for juan so change this
             continue
         author = val['author']
         tag_info.append(f'Name: {key}\nAuthor: {self.bot.get_user(author)}')
     pages = Pages(ctx, entries=tag_info, specific_name=f'Tags for {ctx.guild.name}') # change this since the paginator for juan probably doesnt have specific_name, but it should
     await pages.paginate()
Exemplo n.º 27
0
async def ownerlist(ctx):
    """Shows a list of all servers using paginator"""
    for guild in bot.guilds:
        guilds = [
            f"**{guild.name}** \nServer Owner: **{guild.owner.name}#{guild.owner.discriminator}**\nServer ID: **{guild.id}**\nTotal Members: **{guild.member_count}**"
            for guild in bot.guilds
        ]
    try:
        p = Pages(ctx, entries=guilds, per_page=5)
        p.embed.colour = passcolor
        await p.paginate()
    except Exception as e:
        await ctx.send(e)
Exemplo n.º 28
0
 async def send_cog_help(self, cog):
     commands = []
     for command in await self.filter_commands(cog.get_commands()):
         commands.append(f"`{command.qualified_name}` - **{command.short_doc}**\n")
     
     paginator = Pages(self.context,
                       title=f"{cog.qualified_name} help",
                       entries=commands,
                       thumbnail=None,
                       per_page=10,
                       embed_color=discord.Color.dark_teal(),
                       show_entry_count=True)
     await paginator.paginate()
Exemplo n.º 29
0
 async def queue(self, ctx):
     """Shows the currently queued songs"""
     q = ctx.state.queue
     if q.empty():
         return await ctx.send(
             "The queue is currently empty.\nYou can queue songs by typing `m!play <song name>`."
         )
     queue = [
         f"{song.player.title}\n    By: {song.ctx.author.name}"
         for song in q._queue
     ]
     p = Pages(self.bot, message=ctx.message, entries=queue)
     p.embed.set_author(name="Music Queue")
     await p.paginate()
Exemplo n.º 30
0
	async def wolframalpha(self, ctx, *, q:str):
		try:
			result = await self.wa.query(q, proxy=self.bot.funcs.proxy)
		except:
			return await ctx.send('\N{WARNING SIGN} Wolfram Alpha API Failed.')
		if result is None or result['@success'] == 'false':
			return await ctx.send('\N{WARNING SIGN} `No results found on` <https://wolframalpha.com>')
		imgs = []
		prev = False
		try:
			pods = list(result.pods)
		except AttributeError:
			return await ctx.send('\N{NO ENTRY} Standard computation time exceeded...')
		load = {}
		for pod in pods:
			if 'subpod' not in pod:
				continue
			subs = pod['subpod']
			if isinstance(subs, dict):
				subs = (subs,)
			for sub in subs:
				txt = sub['plaintext']
				if txt == prev:
					continue
				elif txt:
					load[pod['@title']] = txt
				if 'img' in sub:
					imgs.append(sub['img']['@src'])
				if txt != None:
					prev = txt
		imgs.reverse()
		try:
			p = Pages(ctx, entries=imgs, images=True, minimal=True)
			e = p.embed
			e.title = 'Wolfram|Alpha Result'
			for x in load:
				e.add_field(name=x, value=load[x])
			e.set_thumbnail(url='https://cdn.discordapp.com/attachments/178313653177548800/287641775823126538/Pd8NO4lgMW1gsSrlv_zqoFq18mXrVz0AE-Nrxn5sijtp7AacJywTWoM_1kaJeorJKOhVw300.png')
			e.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar_url or ctx.author.default_avatar_url)
			e.color = discord.Colour(int("FF4C4C", 16))
			await p.paginate()
		except CannotPaginate:
			msg = '\n'.join([f'**{x}**: `{load[x]}`' for x in load])
			#usually cause bot doesnt have embed perms but add images anyways ;-;
			msg += '\n' + '\n'.join(imgs[:3])
			if len(msg) >= 2000:
				await ctx.send('\N{WARNING SIGN} Results too long...')
			else:
				await ctx.send(msg)