예제 #1
0
파일: admin.py 프로젝트: ry00001/saobot
 async def system(self, ctx, *, command : str):
     'Run system commands.'
     message = await ctx.send('<a:typing:399298322029871105> Processing...')
     result = []
     try:
         process = subprocess.Popen(command.split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
         result = process.communicate()
     except FileNotFoundError:
         stderr = f'Command not found: {command}'
     embed = discord.Embed(
         title="Command output",
         color=randomness.random_colour()
     )
     if len(result) >= 1 and result[0] in [None, b'']: stdout = 'No output.'
     if len(result) >= 2 and result[0] in [None, b'']: stderr = 'No output.'
     if len(result) >= 1 and result[0] not in [None, b'']: stdout = result[0].decode('utf-8')
     if len(result) >= 2 and result[1] not in [None, b'']: stderr = result[1].decode('utf-8')
     string = ""
     if len(result) >= 1:
         if (len(result[0]) >= 1024): 
             stdout = result[0].decode('utf-8')
             string = string + f'[[STDOUT]]\n{stdout}'
             key = await self.haste_upload(string)
             return await ctx.send(f"http://hastebin.com/{key}")
     if len(result) >= 2:
         if (len(result[1]) >= 1024): 
             stdout = result[0].decode('utf-8')
             string = string + f'[[STDERR]]\n{stdout}'
             key = await self.haste_upload(string)
             return await ctx.send(f"http://hastebin.com/{key}")
     embed.add_field(name="stdout", value=f'```{stdout}```' if 'stdout' in locals() else 'No output.', inline=False)
     embed.add_field(name="stderr", value=f'```{stderr}```' if 'stderr' in locals() else 'No output.', inline=False)
     await message.edit(content='', embed=embed)
예제 #2
0
    async def animalfact(self, ctx, _type: str):
        with ctx.channel.typing():
            sesh = aiohttp.ClientSession()
            types = []
            async with sesh.get("http://fact.birb.pw/api/v1/endpoints") as r:
                if r.status == 200:
                    data = await r.text()
                    types = ast.literal_eval(data)  # safe eval, woot
                    joinedtypes = ", ".join(types)
            if _type not in types:
                sesh.close()
                return await ctx.send(
                    f":x: Invalid type. Available types are: {joinedtypes}")
            async with sesh.get(
                    "http://fact.birb.pw/api/v1/{}".format(_type)) as r:
                if r.status == 200:
                    data = await r.text()
                    json_resp = json.loads(data)
                    fact = json_resp["string"]

                    await ctx.send(embed=discord.Embed(
                        title="{} fact".format(_type.title()),
                        color=randomness.random_colour(),
                        description=fact).set_footer(
                            text="Powered by fact.birb.pw"))
                else:
                    await ctx.send(":x: An HTTP error has occurred.",
                                   delete_after=3)
            sesh.close()
예제 #3
0
 async def on_reaction_add(self, r, u):
     name = r.emoji if type(r.emoji) == str else r.emoji.name  # may as well
     count = r.count
     settings = database.get_settings(
         self.conn, r.message.guild)  # grab me all the settings
     if not settings:
         return  # oops, no settings
     if not 'starboard_channel' in settings.keys():
         return  # oops, no sb channel
     min_count = database.check_setting(self.conn, r.message.guild,
                                        'starboard_min_count') or 1
     sb_name = database.check_setting(self.conn, r.message.guild,
                                      'starboard_emote') or 'тнР'
     channel = database.check_setting(self.conn, r.message.guild,
                                      'starboard_channel')
     channel = r.message.guild.get_channel(
         int(channel))  # get proper channel
     if channel is None:
         return  # no more starboard channel, and we don't wanna throw an exception now do we
     if name == sb_name and count >= min_count:
         e = discord.Embed(colour=randomness.random_colour())
         e.set_author(name=str(r.message.author),
                      icon_url=r.message.author.avatar_url_as(format=None))
         e.description = r.message.content
         e.timestamp = datetime.datetime.utcnow()
         hec = random.choice([':star:', ':star2:', ':dizzy:'])
         mmm = f'{hec} **{count}** <#{r.message.channel.id}>'
         await channel.send(mmm, embed=e)
예제 #4
0
    async def getbot(self, ctx, *, id_arg: discord.Member):

        with ctx.channel.typing():
            if not id_arg or not ctx.guild.get_member(id_arg.id):
                return await ctx.send("This member doesn't exist.")

            # print(id_arg.id)
            if not id_arg.bot:
                return await ctx.send("This member isn't a bot.")

            a = await get_stats(ctx.bot, id_arg.id)
            if a == False:
                return await ctx.send("This bot is not on bots.discord.pw.")
            embed = discord.Embed(title="Bot information for {}".format(
                a["name"]),
                                  color=randomness.random_colour())
            owner_ids = a["owner_ids"]
            embed.add_field(name="Library", value=a["library"])
            embed.add_field(name="User ID", value=a["user_id"])
            owner_info = []
            for i in owner_ids:
                tmpvar = ctx.guild.get_member(int(i))
                try:
                    owner_info.append(
                        f'**{tmpvar.name}**#{tmpvar.discriminator} ({tmpvar.id})'
                    )
                except:
                    pass
            if a["website"]:
                embed.add_field(name="Website",
                                value="[Bot Website]({})".format(a["website"]))
            embed.add_field(name="Prefix", value="`{}`".format(a["prefix"]))
            if len(owner_info) >= 1:
                embed.add_field(
                    name="Owner" if len(owner_info) == 1 else "Owners",
                    value="\n".join(owner_info))
            if a["invite_url"]:
                embed.add_field(name="Invite",
                                value="[Bot Invite]({})".format(
                                    a["invite_url"]))
            if not a["description"] == "":
                embed.add_field(name="Description", value=a["description"])
            embed.set_thumbnail(url=id_arg.avatar_url)
            embed.set_footer(
                text="Tuxedo Discord Bot Lookup | Generated at {}".format(
                    datetime.utcnow()))

            await ctx.send(embed=embed)
예제 #5
0
 async def system(self, ctx, *, command: str):
     'Run system commands.'
     message = await ctx.send('<a:typing:401162479041773568> Processing...')
     result = []
     try:
         process = subprocess.Popen(command.split(' '),
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
         result = process.communicate()
     except FileNotFoundError:
         stderr = f'Command not found: {command}'
     embed = discord.Embed(title="Command output",
                           color=randomness.random_colour())
     if len(result) >= 1 and result[0] in [None, b'']:
         stdout = 'No output.'
     if len(result) >= 2 and result[0] in [None, b'']:
         stderr = 'No output.'
     if len(result) >= 1 and result[0] not in [None, b'']:
         stdout = result[0].decode('utf-8')
     if len(result) >= 2 and result[1] not in [None, b'']:
         stderr = result[1].decode('utf-8')
     string = ""
     if len(result) >= 1:
         if (len(result[0]) >= 1024):
             stdout = result[0].decode('utf-8')
             string = string + f'[[STDOUT]]\n{stdout}'
             link = await self.post_to_hastebin(string)
             await message.edit(content=f":x: Content too long. {link}",
                                embed=None)
             return
     if len(result) >= 2:
         if (len(result[1]) >= 1024):
             stdout = result[0].decode('utf-8')
             string = string + f'[[STDERR]]\n{stdout}'
             link = await self.post_to_hastebin(string)
             await message.edit(content=f":x: Content too long. {link}",
                                embed=None)
             return
     embed.add_field(
         name="stdout",
         value=f'```{stdout}```' if 'stdout' in locals() else 'No output.',
         inline=False)
     embed.add_field(
         name="stderr",
         value=f'```{stderr}```' if 'stderr' in locals() else 'No output.',
         inline=False)
     await message.edit(content='', embed=embed)
예제 #6
0
파일: admin.py 프로젝트: polyjitter/Tuxedo
 async def system(self, ctx, *, command: str):
     'Run system commands.'
     process = subprocess.Popen(command.split(' '), stdout=subprocess.PIPE)
     result = process.communicate()
     embed = discord.Embed(title="Command output",
                           color=randomness.random_colour())
     if result[0] is not None: stdout = result[0].decode('utf-8')
     if result[1] is not None: stderr = result[1].decode('utf-8')
     embed.add_field(
         name="stdout",
         value=f'```{stdout}```' if 'stdout' in locals() else 'No output.',
         inline=False)
     embed.add_field(
         name="stderr",
         value=f'```{stderr}```' if 'stderr' in locals() else 'No output.',
         inline=False)
     await ctx.send(embed=embed)
예제 #7
0
파일: anime.py 프로젝트: ry00001/saobot
 async def search(self, ctx, *, name:str):
     data = await self.kitsu.get_anime(name)
     if len(data) == 0:
         return await ctx.send(':no_entry_sign: Not found.')
     anime = AttrDict(data[0])
     attrs = AttrDict(anime.attributes)
     embed = discord.Embed(color=randomness.random_colour())
     embed.title = f'{attrs.titles["ja_jp"]} ({attrs.titles["en_jp"]})'
     if not attrs.nsfw:
         embed.set_thumbnail(url=attrs.posterImage['medium'])
     embed.description = attrs.synopsis
     embed.url = f'https://kitsu.io/anime/{attrs.slug}'
     embed.set_footer(text='Powered by kitsu.io')
     embed.add_field(name='Started On', value=date.parse_date(attrs.startDate))
     embed.add_field(name='Ended On', value='Ongoing' if attrs.status != 'finished' else date.parse_date(attrs.endDate))
     
     await ctx.send(embed=embed)
예제 #8
0
    async def ginfo(self, ctx, *, guildname: str = None):
        if guildname != None:
            try:
                gid = int(guildname)
            except ValueError:
                gid = 0
        if guildname != None:
            if not permissions.owner_id_check(ctx.bot, ctx.author.id):
                return
            guild = discord.utils.find(
                lambda a: a.name == guildname or a.id == gid, ctx.bot.guilds)
        else:
            guild = ctx.guild
        if guild == None:
            return await ctx.send(':x: Guild not found.')
        embed = discord.Embed(color=randomness.random_colour(),
                              title=f'Guild info for {guild.name}')
        bots = len([a for a in guild.members if a.bot])
        percent = bots / len(guild.members) * 100
        if percent > farmlevel:
            embed.description = ':warning: May be a bot farm!'
            embed.colour = 0xFF0000

        if guild.icon_url != '':
            embed.set_thumbnail(url=guild.icon_url)

        chans = ', '.join([f'`{c.name}`' for c in guild.channels])
        embed.add_field(
            name='Members',
            value=f'{len(guild.members)} ({bots} bots, {math.floor(percent)}%)'
        )
        embed.add_field(
            name='Owner',
            value=
            f'**{guild.owner.name}**#{guild.owner.discriminator} ({guild.owner.id})'
        )
        embed.add_field(name='Roles',
                        value=', '.join([r.name for r in guild.roles]) +
                        f' ({len(guild.roles)})')
        embed.add_field(name='Channels',
                        value=f'{chans} ({len(guild.channels)})')
        embed.add_field(name='Verification Level',
                        value=verlevels[guild.verification_level])

        await ctx.send(embed=embed)
예제 #9
0
    async def eval_cmd(self, ctx, *, code: str):
        """Evaluates Python code"""
        if self._eval.get('env') is None:
            self._eval['env'] = {}
        if self._eval.get('count') is None:
            self._eval['count'] = 0

        codebyspace = code.split(" ")
        print(codebyspace)
        silent = False
        if codebyspace[0] == "--silent" or codebyspace[0] == "-s":
            silent = True
            codebyspace = codebyspace[1:]
            code = " ".join(codebyspace)

        self._eval['env'].update({
            'self': self.bot,
            'ctx': ctx,
            'message': ctx.message,
            'channel': ctx.message.channel,
            'guild': ctx.message.guild,
            'author': ctx.message.author,
        })

        # let's make this safe to work with
        code = code.replace('```py\n', '').replace('```', '').replace('`', '')

        _code = ('async def func(self):\n  try:\n{}\n  '
                 'finally:\n    self._eval[\'env\'].update(locals())').format(
                     textwrap.indent(code, '    '))

        before = time.monotonic()
        # noinspection PyBroadException
        try:
            exec(_code, self._eval['env'])
            func = self._eval['env']['func']
            output = await func(self)

            if output is not None:
                output = repr(output)
        except Exception as e:
            output = '{}: {}'.format(type(e).__name__, e)
        after = time.monotonic()
        self._eval['count'] += 1
        count = self._eval['count']

        code = code.split('\n')
        if len(code) == 1:
            _in = 'In [{}]: {}'.format(count, code[0])
        else:
            _first_line = code[0]
            _rest = code[1:]
            _rest = '\n'.join(_rest)
            _countlen = len(str(count)) + 2
            _rest = textwrap.indent(_rest, '...: ')
            _rest = textwrap.indent(_rest, ' ' * _countlen)
            _in = 'In [{}]: {}\n{}'.format(count, _first_line, _rest)

        message = '```py\n{}'.format(_in)
        if output is not None:
            message += '\nOut[{}]: {}'.format(count, output)
        ms = int(round((after - before) * 1000))
        if ms > 100:  # noticeable delay
            message += '\n# {} ms\n```'.format(ms)
        else:
            message += '\n```'

        try:
            if ctx.author.id == self.bot.user.id:
                await ctx.message.edit(content=message)
            else:
                if not silent:
                    await ctx.send(message)
        except discord.HTTPException:
            if not silent:
                with aiohttp.ClientSession() as sesh:
                    async with sesh.post(
                            "https://hastebin.com/documents/",
                            data=output,
                            headers={"Content-Type": "text/plain"}) as r:
                        r = await r.json()
                        embed = discord.Embed(description=(
                            "[View output - click]"
                            "(https://hastebin.com/raw/{})").format(r["key"]),
                                              color=randomness.random_colour())
                        await ctx.send(embed=embed)