Beispiel #1
0
 async def ttspam(self, ctx, *, text: str):
     """Spam a message with TTS. **This may get you banned from servers.**
     Usage: ttspam [message]"""
     or_check_perms(ctx, ('send_tts_messages', 'manage_messages'))
     m = await self.bot.say(textwrap.wrap((text + ' ') * 2000, width=2000)[0], tts=True)
     await asyncio.sleep(0.1)
     await self.bot.delete_message(m)
Beispiel #2
0
 async def unmute(self, ctx, *, member: discord.Member):
     """Unmute someone on voice and text chat.
     Usage: unmute [person's name]"""
     or_check_perms(ctx, ('mute_members', 'manage_roles', 'manage_channels',
                          'manage_messages'))
     status = await self.bot.say('Unmuting... 🌚')
     pg_task = self.loop.create_task(
         asyncio.wait_for(self.progress(status, 'Unmuting'),
                          timeout=30,
                          loop=self.loop))
     role_map = {r.name: r for r in member.roles}
     try:
         if 'Muted' in role_map:
             await self.bot.remove_roles(member, role_map['Muted'])
         ch_perms = discord.PermissionOverwrite(
             **{p: None
                for p in muted_perms})
         for channel in ctx.message.server.channels:
             await self.bot.edit_channel_permissions(
                 channel, member, ch_perms)
         await self.bot.server_voice_state(member, mute=False, deafen=None)
         pg_task.cancel()
         await self.bot.delete_message(status)
         await self.bot.say('Successfully unmuted **%s**!' % str(member))
     except (discord.Forbidden, discord.HTTPException):
         pg_task.cancel()
         await self.bot.delete_message(status)
         await self.bot.say(
             '**I don\'t have enough permissions to do that!**')
Beispiel #3
0
    async def picospeak(self, ctx, *, tospeak: str):
        """Uses the SVOX pico TTS engine to speak a message.
        Usage: picospeak [message]"""
        or_check_perms(ctx, ('bot_owner', ))
        state = self.get_voice_state(ctx.message.server)

        if state.voice is None:
            success = await ctx.invoke(self.summon)
            if not success:
                return
        if state.voice.channel != ctx.message.author.voice_channel:
            await self.bot.say(
                'You can only modify the queue if you\'re in the same channel as me!'
            )
            return
        if len(state.songs._queue) >= 5:
            await self.bot.say('There can only be up to 5 items in queue!')
            return

        stream = io.BytesIO(
            subprocess.check_output(
                ['pico2wave', '-w', '/tmp/pipe.wav', tospeak]))
        state.voice.encoder_options(sample_rate=16000, channels=1)
        player = state.voice.create_stream_player(stream,
                                                  after=state.toggle_next)
        player.volume = 1.0
        entry = VoiceEntry(ctx.message, player, override_name='Speech')
        await state.songs.put(entry)
        await self.bot.say('Queued ' + str(entry))
        state.voice.encoder_options(sample_rate=48000, channels=2)
Beispiel #4
0
 async def record_recog(self, ctx):
     """Speech recognize the current voice recording.
     Usage: recording recog"""
     or_check_perms(ctx,
                    ['manage_server', 'manage_channels', 'move_members'])
     with assert_msg(ctx, '**The bot owner has not set up this feature!**'):
         check(self.opus_decoder != None)
     with assert_msg(ctx, '**This server does not have a recording!**'):
         check(ctx.message.server.id in self.bot.pcm_data)
     status = await self.bot.say('Hmm, let me think... 🌚')
     pg_task = self.loop.create_task(
         asyncio.wait_for(self.progress(status, 'Hmm, let me think'),
                          timeout=30,
                          loop=self.loop))
     sr_data = sr.AudioData(self.recording_data[ctx.message.server.id],
                            48000, 2)
     try:
         with async_timeout.timeout(16):
             final = await self.loop.run_in_executor(
                 None, r.recognize_sphinx, sr_data)
     except asyncio.TimeoutError:
         pg_task.cancel()
         await self.bot.edit_message(
             status, '**It took too long to recognize your recording!**')
         return
     pg_task.cancel()
     await self.bot.edit_message(status,
                                 'I think you said: ' + final[:2000])
Beispiel #5
0
 async def mute(self, ctx, *, member: discord.Member):
     """Mute someone on voice and text chat.
     Usage: mute [person's name]"""
     or_check_perms(ctx, [
         'mute_members', 'manage_roles', 'manage_channels',
         'manage_messages'
     ])
     status = await ctx.send('Muting... 🌚')
     pg_task = self.loop.create_task(
         asyncio.wait_for(self.progress(status, 'Muting'),
                          timeout=30,
                          loop=self.loop))
     try:
         ch_perms = discord.PermissionOverwrite(
             **{p: False
                for p in muted_perms})
         for channel in ctx.guild.channels:
             await channel.set_permissions(member, ch_perms)
         await member.__redit(mute=True,
                              deafen=None,
                              reason='Mute command was used on user')
         pg_task.cancel()
         await status.delete(reason='Deleting progress/status message')
         await ctx.send('Successfully muted **%s**!' % str(member))
     except (discord.Forbidden, discord.HTTPException):
         pg_task.cancel()
         await status.delete(reason='Deleting progress/status message')
         await ctx.send('**I don\'t have enough permissions to do that!**')
Beispiel #6
0
    async def topic(self, ctx, *, topic: str):
        """Start the current round with a topic."""
        or_check_perms(ctx, [
            'manage_guild', 'manage_channels', 'manage_messages',
            'manage_roles'
        ])
        if ctx.channel.id in self.games:
            try:
                await ctx.message.delete(
                    reason=
                    'Deleting message sent to change the topic, so players don\'t see and prepare before the round'
                )
            except discord.Forbidden:
                await ctx.send(
                    '⚠ **I work best with the Manage Messages permission.**')
            game = self.games[ctx.channel.id]
            r_mention = game['r_mention']
            game['topic'] = topic
            await ctx.send('''Starting **round {}** in 30 seconds!
{}Get your butts in here, and grab your dankest memes!'''.format(
                str(game['round']), r_mention))
            await asyncio.sleep(28.6, loop=self.loop)
            game['active'] = True
            game['round_active'] = True
            await ctx.send(
                f'''{r_mention}The **meme war** is now starting for the topic `{topic}`!
Get your memes in already! :clap::clap:
Leaders: when you're ready, select a winner (and end the round) with `{ctx.prefix}gamenight winner`!'''
            )
        else:
            await ctx.send(
                ctx.mention +
                ' There isn\'t a game night session in this channel!')
Beispiel #7
0
 async def start(self, ctx):
     or_check_perms(ctx, [
         'manage_guild', 'manage_channels', 'manage_messages',
         'manage_roles'
     ])
     await ctx.send(
         f':clap: Use `{ctx.prefix}gamenight memewar [topic]` for now.')
Beispiel #8
0
 async def winner(self, ctx, *, winner: discord.Member):
     """Select a winner for a game night session.
     Usage: gamenight winner [winner]"""
     or_check_perms(ctx, ['manage_server', 'manage_channels', 'manage_messages', 'manage_roles'])
     if ctx.message.channel.id in self.games:
         try:
             await self.bot.delete_message(ctx.message)
         except discord.Forbidden:
             await self.bot.say('⚠ **I work best with the Manage Messages permission.**')
         game = self.games[ctx.message.channel.id]
         if winner in game['players']:
             k = '.'
             key = '**...and the winner is'
             msg = await self.bot.say(key + '**')
             for i in range(1, 4):
                 await asyncio.sleep(0.96)
                 await self.bot.edit_message(msg, key + (k * i) + '**')
             await asyncio.sleep(0.97)
             await self.bot.edit_message(msg, key + '...:drum:**')
             await asyncio.sleep(0.97)
             await self.bot.edit_message(msg, key + '...:drum: ' + str(winner) + '!**')
             game['players'][winner] += 1
             game['round'] += 1
             game['round_active'] = False
             await asyncio.sleep(1.5)
             await self.bot.say(f'Leaders: to set the topic for the next round, do `{ctx.prefix}gamenight topic [topic]`!')
         else:
             await self.bot.reply('that person isn\'t in this game night session!')
     else:
         await self.bot.reply('there isn\'t a game night session in this channel!')
Beispiel #9
0
 async def ttspam(self, ctx, *, text: str):
     """Spam a message with TTS. **This may get you banned from guilds.**
     Usage: ttspam [message]"""
     or_check_perms(ctx, ('manage_messages', ))
     m = await ctx.send(textwrap.wrap((text + ' ') * 2000, width=2000)[0],
                        tts=True)
     await asyncio.sleep(0.1)
     await m.delete(
         reason=
         'Deleting message used for a ttspam command (only usable by people with Manage Messages)'
     )
Beispiel #10
0
 async def cleverbutt_kickstart(self, ctx, *msg: str):
     """Kickstart / start cleverbutts conversation
     Usage: cleverbutt start {optional: message}"""
     or_check_perms(ctx, ['manage_server', 'manage_channels', 'manage_messages'])
     c_map = {c.name: c for c in ctx.message.server.channels}
     if 'cleverbutts' in c_map:
         ch = c_map['cleverbutts']
         if msg:
             await self.bot.send_message(ch, ctx.raw_args.replace('@everyone', '@\u200beveryone').replace('@here', '@\u200bhere'))
         else:
             await self.bot.send_message(ch, 'Hello, what\'re you up to?')
         await self.bot.say('**Message sent in <#%s>!**' % str(ch.id))
     else:
         await self.bot.say('**There\'s no** `#cleverbutts` **channel in this server!**')
Beispiel #11
0
    async def memewar(self, ctx, *, topic: str):
        """Start a meme war on a topic.
        Usage: gamenight memewar [topic]"""
        or_check_perms(ctx, ['manage_server', 'manage_channels', 'manage_messages', 'manage_roles'])
        game = {
            'active': False,
            'topic': topic,
            'duration': 1.5 * 60,
            'players': {
                ctx.message.author: 0
            },
            'recruiting': True,
            'role': None,
            'round': 1,
            'round_active': False,
            'r_mention': ''
        }
        if ctx.message.channel.id in self.games:
            await self.bot.reply('there\'s already a game night session here!')
            return
        self.games[ctx.message.channel.id] = game
        await self.bot.say(f''':clap: Now hosting a **meme war** for `{topic}`! :clap:
We need at least 3 participants. ({ctx.message.author.mention} is already in.)
Everyone, you have 1 minute to join! Just use `{ctx.prefix}gamenight join`.''')
        await asyncio.sleep(60)
        game['recruiting'] = False
        r_mention = ''
        if len(game['players']) < 3:
            await self.bot.say('⚠ **Stopped due to insufficent number of participants.**')
            del self.games[ctx.message.channel.id]
            return
        try:
            role = await self.bot.create_role(ctx.message.server, name='Game Night Player', color=discord.Color.dark_teal(), mentionable=True)
            for player in game['players']:
                await self.bot.add_roles(player, role)
            r_mention = '<@&' + role.id + '> '
            game['role'] = role
        except discord.Forbidden:
            await self.bot.say('⚠ **I work best with the Manage Roles permission.**')
        game['r_mention'] = r_mention
        await self.bot.say('''Starting the **meme war** in 30 seconds!
{}Get your butts in here, and grab your dankest memes!'''.format(r_mention))
        await asyncio.sleep(28.6)
        game['active'] = True
        game['round_active'] = True
        await self.bot.say(f'''{r_mention}The **meme war** is now starting for the topic `{topic}`!
Get your memes in already! :clap::clap:
Leaders: when you're ready, select a winner (and end the round) with `{ctx.prefix}gamenight winner`!''')
Beispiel #12
0
 async def stop(self, ctx):
     """Stop the current game night session.
     Usage: gamenight stop"""
     or_check_perms(ctx, ['manage_server', 'manage_channels', 'manage_messages', 'manage_roles'])
     if ctx.message.channel.id in self.games:
         game = self.games[ctx.message.channel.id]
         if game['role']:
             try:
                 await self.bot.delete_role(ctx.message.server, game['role'])
             except discord.Forbidden:
                 pass
         del self.games[ctx.message.channel.id]
         await self.bot.say('**Ended the current game night session at round ' + str(game['round']) + '.**')
         del game
     else:
         await self.bot.reply('there\'s no game night session active here!')
Beispiel #13
0
 async def cleverbutt_kickstart(self, ctx, *msg: str):
     """Kickstart / start cleverbutts conversation
     Usage: cleverbutt start {optional: message}"""
     or_check_perms(ctx,
                    ['manage_guild', 'manage_channels', 'manage_messages'])
     c_map = {c.name: c for c in ctx.guild.channels}
     if 'cleverbutts' in c_map:
         ch = c_map['cleverbutts']
         if msg:
             await ch.send(' '.join(msg))
         else:
             await ch.send('Hello, what\'re you up to?')
         await ctx.send('**Message sent in <#%s>!**' % str(ch.id))
     else:
         await ctx.send(
             '**There\'s no** `#cleverbutts` **channel in this guild!**')
Beispiel #14
0
 async def prefix(self, ctx, *prefix: str):
     """Get or set the command prefix.
     Usage: prefix {new prefix}"""
     sk = ' server'
     prop = ('by_server', 'command_prefix')
     if self.bot.selfbot:
         sk = ''
         prop = ('global', 'selfbot_prefix')
     if prefix:
         or_check_perms(
             ctx, ['manage_server', 'manage_channels', 'manage_messages'])
         jprefix = ' '.join(prefix)
         self.bot.store.set_prop(ctx.message, *prop, jprefix)
         await self.bot.say(':white_check_mark:')
     else:
         oprefix = self.bot.store.get_cmdfix(ctx.message)
         await self.bot.say('**Current%s command prefix is: **`%s`' %
                            (sk, oprefix))
Beispiel #15
0
 async def winner(self, ctx, *, winner: discord.Member):
     """Select a winner for a game night session.
     Usage: gamenight winner [winner]"""
     or_check_perms(ctx, [
         'manage_guild', 'manage_channels', 'manage_messages',
         'manage_roles'
     ])
     if ctx.channel.id in self.games:
         try:
             await ctx.message.delete(
                 reason=
                 'Deleting message sent to select winner, so players don\'t see the winner until after the drum roll'
             )
         except discord.Forbidden:
             await ctx.send(
                 '⚠ **I work best with the Manage Messages permission.**')
         game = self.games[ctx.channel.id]
         if winner in game['players']:
             k = '.'
             key = '**...and the winner is'
             msg = await ctx.send(key + '**')
             for i in range(1, 4):
                 await asyncio.sleep(0.96, loop=self.loop)
                 await msg.edit(content=key + (k * i) + '**')
             await asyncio.sleep(0.97, loop=self.loop)
             await msg.edit(content=mkey + '...:drum:**')
             await asyncio.sleep(0.97, loop=self.loop)
             await msg.edit(content=key + '...:drum: ' + str(winner) + '!**'
                            )
             game['players'][winner] += 1
             game['round'] += 1
             game['round_active'] = False
             await asyncio.sleep(1.5, loop=self.loop)
             await ctx.send(
                 f'Leaders: to set the topic for the next round, do `{ctx.prefix}gamenight topic [topic]`!'
             )
         else:
             await ctx.send(
                 ctx.mention +
                 ' That person isn\'t in this game night session!')
     else:
         await ctx.send(
             ctx.mention +
             ' There isn\'t a game night session in this channel!')
Beispiel #16
0
 async def ocr(self, ctx):
     """OCR an image.
     Usage: ocr [attach an image]"""
     or_check_perms(ctx, ('bot_owner', ))
     warnings.simplefilter('error', Image.DecompressionBombWarning)
     if ctx.message.attachments:
         with async_timeout.timeout(5):
             async with self.bot.cog_http.get(
                     ctx.message.attachments[0].proxy_url) as r:
                 raw_image = await r.read()
     else:
         await ctx.send(':warning: No attachment found.')
         return
     img_bytes = BytesIO(raw_image)
     image = Image.open(img_bytes)
     text = tesserocr.image_to_text(image)
     if text:
         await ctx.send(text)
     else:
         await ctx.send('No results.')
Beispiel #17
0
    async def record_toggle(self, ctx):
        """Toggle (start/stop) voice recording.
        Usage: recording toggle"""
        or_check_perms(ctx,
                       ['manage_server', 'manage_channels', 'move_members'])
        state = self.get_voice_state(ctx.message.server)
        if state.voice is None:
            success = await ctx.invoke(self.summon)
            if not success:
                return

        sid = ctx.message.server.id
        if sid not in self.servers_recording:
            self.servers_recording.add(sid)
            await self.bot.say(
                '**Voice in this server is now being recorded!**')
        else:
            self.servers_recording.remove(sid)
            await self.bot.say(
                '**Voice is no longer being recorded in this server!**')
Beispiel #18
0
 async def stop(self, ctx):
     """Stop the current game night session.
     Usage: gamenight stop"""
     or_check_perms(ctx, [
         'manage_guild', 'manage_channels', 'manage_messages',
         'manage_roles'
     ])
     if ctx.channel.id in self.games:
         game = self.games[ctx.channel.id]
         if game['role']:
             try:
                 await game['role'].delete(
                     reason='Deleting game night session-specific role')
             except discord.Forbidden:
                 pass
         del self.games[ctx.channel.id]
         await ctx.send('**Ended the current game night session at round ' +
                        str(game['round']) + '.**')
         del game
     else:
         await ctx.send(ctx.mention +
                        ' There\'s no game night session active here!')
Beispiel #19
0
 async def ocr(self, ctx):
     """OCR an image.
     Usage: ocr [attach an image]"""
     or_check_perms(ctx, ('bot_owner',))
     if not have_pil:
         await self.bot.say('The bot owner hasn\'t set up this feature!')
         return False
     warnings.simplefilter('error', Image.DecompressionBombWarning)
     if ctx.message.attachments:
         with async_timeout.timeout(5):
             async with aiohttp.request('GET', ctx.message.attachments[0]['url']) as r:
                 raw_image = await r.read()
     else:
         await self.bot.say(':warning: No attachment found.')
         return
     img_bytes = BytesIO(raw_image)
     image = Image.open(img_bytes)
     text = tesserocr.image_to_text(image)
     if text:
         await self.bot.say(text)
     else:
         await self.bot.say('No results.')
Beispiel #20
0
 async def cog(self, ctx):
     """Manage all of my cogs and gears.
     Usage: cog {stuff}"""
     or_check_perms(ctx, ('bot_owner', ))
     if ctx.invoked_subcommand is None:
         await self.bot.send_cmd_help(ctx)
Beispiel #21
0
 async def purge(self, ctx, *count):
     """Purge a channel of messages.
     Usage: purge"""
     if self.bot.selfbot:
         await self.bot.say(
             '**That command doesn\'t work in selfbot mode, due to a Discord restriction.**'
         )
         return
     or_check_perms(ctx,
                    ['manage_server', 'manage_channels', 'manage_messages'])
     mode = 'count'
     detected = False
     if not count:
         limit = 1500
         detected = True
     elif len(count) == 1:
         if count[0] == 'infinite':
             limit = 1600
             detected = True
         else:
             try:
                 limit = abs(int(count[0])) + 1
                 if limit > 1600:
                     await self.bot.say(
                         ctx.message.author.mention +
                         ' **You can only clean messages by user or 1-1600!**'
                     )
                     return
                 detected = True
             except ValueError:
                 pass
     if not detected:
         mode = 'target'
         targets = set()
         members = {}
         s = ctx.message.server
         for i in getattr(s, 'members', []):
             members[i.mention] = i
             members[i.id] = i
             members[i.display_name] = i
             members[i.name] = i
         for i in count:
             try:
                 member = s.get_member(i)
             except AttributeError:
                 try:
                     member = await self.bot.get_user_info(i)
                 except discord.HTTPException:
                     member = None
             if member:
                 targets.add(member)
             else:
                 try:
                     member = await self.bot.get_user_info(i)
                 except discord.HTTPException:
                     member = None
                 if member:
                     targets.add(member)
         names = []
         _i = 0
         while _i < len(count):
             names.append(count[_i])
             with suppress(KeyError):
                 if ' '.join(names) in members:
                     targets.add(members[' '.join(names)])
                     names = []
                 elif _i + 1 == len(count):
                     targets.add(members[count[0]])
                     _i = -1
                     users = count[1:]
                     names = []
             _i += 1
         if not targets:
             await self.bot.say(
                 '**No matching users, try again! Name, nickname, name#0000 (discriminator), or ID work. Spaces do, too!**'
             )
             return
         purge_ids = [m.id for m in targets]
     try:
         if mode == 'count':
             deleted = await self.bot.purge_from(ctx.message.channel,
                                                 limit=limit)
         else:
             deleted = await self.bot.purge_from(
                 ctx.message.channel,
                 limit=1500,
                 check=lambda m: m.author.id in purge_ids)
     except discord.Forbidden:
         await self.bot.say(
             ctx.message.author.mention +
             ' **I don\'t have enough permissions to do that here 😢**')
         return
     except discord.HTTPException as e:
         if '14 days old' in str(e):
             await self.bot.say(
                 'I can only purge messages under 14 days old :sob:')
             return
         else:
             raise e
     dn = len(deleted)
     del_msg = await self.bot.say(
         '👏 I\'ve finished, deleting {0} message{1}!'.format(
             (dn if dn else 'no'), ('' if dn == 1 else 's')))
     await asyncio.sleep(2.8)
     await self.bot.delete_message(del_msg)
Beispiel #22
0
 async def help(self, ctx, *commands_or_cogs: str):
     """Show the bot's help.
     Usage: help"""
     if ctx.invoked_with.startswith('p'):
         or_check_perms(ctx, [
             'bot_admin', 'manage_guild', 'manage_messages',
             'manage_channels'
         ])
     pages = []
     cog_assign = {}
     fields = {}
     chars = 0
     emb = discord.Embed(color=random.randint(0, 255**3 - 1))
     emb.title = 'Bot Help'
     emb.set_author(name=ctx.me.display_name, icon_url=ctx.me.avatar_url)
     if not commands_or_cogs:
         for name, cmd in self.bot.all_commands.items():
             if cmd.cog_name:
                 cog = cmd.cog_name
             else:
                 cog = 'No Category'
             if cog not in cog_assign:
                 cog_assign[cog] = []
             cog_assign[cog].append(cmd)
         for group, cmds in cog_assign.items():
             field = []
             did_names = []
             for cmd in cmds:
                 if cmd.name not in did_names:
                     if not cmd.hidden:
                         field.append('\u2022 **' + cmd.name + '**: *' +
                                      (cmd.short_doc if cmd.
                                       short_doc else 'I\'m a command.') +
                                      '*')
                         did_names.append(cmd.name)
             fields[group] = field
     else:  # got commands OR cogs here, and don't know which.
         lcogs = {c.lower(): self.bot.cogs[c] for c in self.bot.cogs}
         cog_names = {c.lower(): c for c in self.bot.cogs}
         for item in commands_or_cogs[0:25]:
             litem = item.lower()
             item_done = False
             if litem in lcogs:
                 did_names = []
                 field = []
                 for cmd in self.bot.all_commands.values():
                     if cmd.cog_name == cog_names[litem]:
                         if cmd.name not in did_names:
                             if not cmd.hidden:
                                 field.append(
                                     '\u2022 **' + cmd.name + '**: *' +
                                     (cmd.short_doc if cmd.
                                      short_doc else 'I\'m a command.') +
                                     '*')
                                 did_names.append(cmd.name)
                 fields[cog_names[litem]] = field
                 item_done = True
             if litem in self.bot.all_commands:
                 cmd = self.bot.all_commands[litem]
                 field = '`' + ctx.prefix
                 if cmd.aliases:
                     field += '[' + cmd.name + '|' + '|'.join(
                         cmd.aliases) + ']`'
                 else:
                     field += cmd.name + '`'
                 field += '\n\n' + (cmd.help
                                    if cmd.help else 'I\'m a command.')
                 fields[item] = (field, )
                 item_done = True
             if not item_done:
                 fields[item] = ('No such command or cog.', )
     chars = len(target.display_name)
     for cog in fields:
         field = fields[cog]
         content = '\n'.join(field)
         if not content:
             content = 'No visible commands.'
         pre_len = len(content) + len(cog)
         if chars + pre_len > self.char_limit:
             pages.append(emb)
             emb = discord.Embed(color=random.randint(0, 255**3 - 1))
             emb.set_author(name=ctx.me.display_name,
                            icon_url=ctx.me.avatar_url)
             chars = 0
             if len(content) <= 1024:
                 emb.add_field(name=cog, value=content)
             else:
                 pager = commands.Paginator(prefix='',
                                            suffix='',
                                            max_size=1024)
                 for ln in field:
                     pager.add_line(ln)
                 for page in pager.pages:
                     emb.add_field(name=cog, value=page)
         chars += pre_len
     self.logger.info('Generated help, ending with ' + str(chars) +
                      ' chars')
     if not pages:
         pages.append(emb)
     destination = ctx.author
     if chars < 1000:
         destination = ctx.channel
     if len(pages) > 1:
         destination = ctx.author
     if ctx.invoked_with.startswith('p'):
         destination = ctx.channel
     if self.bot.selfbot:
         destination = ctx.channel
     for page in pages:
         try:
             await destination.send(embed=page)
         except discord.HTTPException:
             self.bot._last_help_embeds = pages
             await destination.send(
                 'Error sending embed. Cogs/Commands: ' +
                 ', '.join([f['name'] for f in page.to_dict()['fields']]))
     if destination == ctx.author:
         if isinstance(ctx.channel, discord.abc.GuildChannel):
             await ctx.send(
                 ctx.mention +
                 ' **__I\'ve sent you my help, please check your DMs!__**')
Beispiel #23
0
 async def help(self, ctx, *commands_or_cogs: str):
     """Show the bot's help.
     Usage: help"""
     if ctx.invoked_with.startswith('p'):
         or_check_perms(ctx, [
             'bot_admin', 'manage_server', 'manage_messages',
             'manage_channels'
         ])
     try:
         if ctx.message.server.me:
             target = ctx.message.server.me
         else:
             target = self.bot.user
     except AttributeError:
         target = self.bot.user
     au = target.avatar_url
     avatar_link = (au if au else target.default_avatar_url)
     pages = []
     cog_assign = {}
     fields = {}
     chars = 0
     emb = discord.Embed(color=int('0x%06X' %
                                   random.randint(0, 256**3 - 1), 16))
     emb.title = 'Bot Help'
     emb.set_author(name=target.display_name, icon_url=avatar_link)
     if not commands_or_cogs:
         for name, cmd in self.bot.commands.items():
             if cmd.cog_name:
                 cog = cmd.cog_name
             else:
                 cog = 'No Category'
             if cog not in cog_assign:
                 cog_assign[cog] = []
             cog_assign[cog].append(cmd)
         for group, cmds in cog_assign.items():
             field = []
             did_names = []
             for cmd in cmds:
                 if cmd.name not in did_names:
                     if not cmd.hidden:
                         field.append('\u2022 **' + cmd.name + '**: *' +
                                      (cmd.short_doc if cmd.
                                       short_doc else 'I\'m a command.') +
                                      '*')
                         did_names.append(cmd.name)
             fields[group] = field
     else:  # got commands OR cogs here, and don't know which.
         lcogs = {c.lower(): self.bot.cogs[c] for c in self.bot.cogs}
         cog_names = {c.lower(): c for c in self.bot.cogs}
         for item in commands_or_cogs[0:25]:
             litem = item.lower()
             item_done = False
             if litem in lcogs:
                 did_names = []
                 field = []
                 for cmd in self.bot.commands.values():
                     if cmd.cog_name == cog_names[litem]:
                         if cmd.name not in did_names:
                             if not cmd.hidden:
                                 field.append(
                                     '\u2022 **' + cmd.name + '**: *' +
                                     (cmd.short_doc if cmd.
                                      short_doc else 'I\'m a command.') +
                                     '*')
                                 did_names.append(cmd.name)
                 fields[cog_names[litem]] = field
                 item_done = True
             if litem in self.bot.commands:
                 cmd = self.bot.commands[litem]
                 field = '`' + ctx.prefix
                 if cmd.aliases:
                     field += '[' + cmd.name + '|' + '|'.join(
                         cmd.aliases) + ']`'
                 else:
                     field += cmd.name + '`'
                 field += '\n\n' + (cmd.help
                                    if cmd.help else 'I\'m a command.')
                 fields['\u200b' + item] = (field, )
                 item_done = True
             if not item_done:
                 fields['\u200b' + item] = ('No such command or cog.', )
     chars = 0
     for cog in fields:
         field = fields[cog]
         content = '\n'.join(field)
         if not content:
             content = 'No visible commands.'
         pre_len = sum([len(i) for i in field])
         if chars + pre_len < self.char_limit:
             if len(content) <= 1024:
                 emb.add_field(name=cog, value=content)
             else:
                 pager = commands.Paginator(prefix='',
                                            suffix='',
                                            max_size=1024)
                 for ln in field:
                     pager.add_line(ln)
                 for page in pager.pages:
                     emb.add_field(name=cog, value=page)
         else:
             pages.append(emb)
             emb = discord.Embed(
                 color=int('0x%06X' % random.randint(0, 256**3 - 1), 16))
             emb.title = 'Bot Help'
             emb.set_author(name=target.display_name, icon_url=avatar_link)
             chars = 0
             if len(content) <= 1024:
                 emb.add_field(name=cog, value=content)
             else:
                 pager = commands.Paginator(prefix='',
                                            suffix='',
                                            max_size=1024)
                 for ln in field:
                     pager.add_line(ln)
                 for page in pager.pages:
                     emb.add_field(name=cog, value=page)
         chars += pre_len
     self.logger.info('chars ' + str(chars))
     if not pages:
         pages.append(emb)
     pages[-1].set_footer(icon_url=avatar_link, text='Enjoy!')
     destination = ctx.message.author
     if chars < 1000:
         destination = ctx.message.channel
     if len(pages) > 1:
         destination = ctx.message.author
     if ctx.invoked_with.startswith('p'):
         destination = ctx.message.channel
     if self.bot.selfbot:
         destination = ctx.message.channel
     for page in pages:
         try:
             await self.bot.send_message(destination, embed=page)
         except discord.HTTPException:
             self.bot._last_help_embeds = pages
             await self.bot.send_message(
                 destination, 'Error sending embed. Cogs/Commands: ' +
                 ', '.join([f['name'] for f in page.to_dict()['fields']]))
     if destination == ctx.message.author:
         if not ctx.message.channel.is_private:
             await self.bot.say(
                 ctx.message.author.mention +
                 ' **__I\'ve private messaged you my help, please check your DMs!__**'
             )
Beispiel #24
0
 async def recording(self, ctx):
     """Manage voice recording, recognition, and playback.
     Usage: recording"""
     or_check_perms(ctx, ('bot_owner', ))
     if ctx.invoked_subcommand is None:
         await self.bot.send_cmd_help(ctx)
Beispiel #25
0
 async def cmd_eval(self, ctx, *, code: str):
     """Evaluate some code, or a math expression.
     Usage: eval [code/expression]"""
     or_check_perms(ctx, ('bot_admin',))
     code = bdel(bdel(code, '```python').strip('`'), '```py')
     for key in eval_blocked:
         if re.search(key, code):
             await self.bot.say(ctx.message.author.mention + ' **Blocked keyword found!**')
             return False
     try:
         sio = StringIO()
         with async_timeout.timeout(3):
             with contextlib.redirect_stdout(sio):
                 m_result = await self.math_task(code)
         v = sio.getvalue()
         if v:
             m_result = v + str(m_result)
     except (asyncio.TimeoutError, RuntimeError) as exp:
         resp = '{0.author.mention} **It took too long to evaluate your expression!**'.format(ctx.message)
         if isinstance(exp, RuntimeError):
             if str(exp).startswith('Execution exceeded time limit, max runtime is '):
                 await self.bot.say(resp)
                 return
             else:
                 raise ValueError('ASTEval Error of type TimeoutError')
         else:
             await self.bot.say(resp)
         return
     _result = ''
     if self.bot.asteval.error:
         err_type = self.bot.asteval.error[0].get_error()[0]
         if err_type == 'MemoryError':
             await self.bot.reset_asteval(reason='due to MemoryError')
             await self.bot.say(ctx.message.author.mention + ' **Please re-run your `eval` command!**')
             return
         elif err_type in ['NameError', 'UnboundLocalError']:
             await self.bot.say(ctx.message.author.mention + ' **You tried to use a variable that didn\'t exist!**')
             return
         else:
             raise ValueError('ASTEval Error of type ' + err_type)
     else:
         try:
             _result = str(m_result)
         except MemoryError:
             await self.bot.reset_asteval(reason='due to MemoryError')
             await self.bot.say(ctx.message.author.mention + ' **Please re-run your `eval` command!**')
             return
     try:
         if m_result is None:
             _result = '✅'
         else:
             if not ctx.invoked_with.startswith('r'):
                 _result = '```py\n' + _result + '```'
     except MemoryError:
         await self.bot.reset_asteval(reason='due to MemoryError')
         await self.bot.say(ctx.message.author.mention + ' **Please re-run your `eval` command!**')
         return
     try:
         byte_size = await self.loop.run_in_executor(None, asizeof, self.bot.asteval.symtable)
         if byte_size > 50_000_000: # 110 MiB 115_343_360, 107 MiB 112_197_632, 107 MB 107_000_000
             await self.bot.reset_asteval(reason='due to memory usage > 50M', note=f'was using {byte_size / 1048576} MiB')
     except MemoryError:
         await self.bot.reset_asteval(reason='due to MemoryError during asizeof')
     else:
         del byte_size
     await self.bot.say(_result)
Beispiel #26
0
 async def start(self, ctx):
     or_check_perms(ctx, ['manage_server', 'manage_channels', 'manage_messages', 'manage_roles'])
     await self.bot.say(f':clap: Use `{ctx.prefix}gamenight memewar [topic]` for now.')