예제 #1
0
    async def g(self, ctx, *, query):
        """Google web search. Ex: [p]g what is discordapp?"""
        if not embed_perms(ctx.message):
            config = load_optional_config()
            async with aiohttp.ClientSession() as session:
                async with session.get("https://www.googleapis.com/customsearch/v1?q=" + urllib.parse.quote_plus(query) + "&start=" + '1' + "&key=" + config['google_api_key'] + "&cx=" + config['custom_search_engine']) as resp:
                    result = json.loads(await resp.text())
            return await ctx.send(result['items'][0]['link'])

        try:
            entries, root = await get_google_entries(query)
            card_node = root.find(".//div[@id='topstuff']")
            card = self.parse_google_card(card_node)
        except RuntimeError as e:
            await ctx.send(str(e))
        else:
            if card:
                value = '\n'.join(entries[:2])
                if value:
                    card.add_field(name='Search Results', value=value, inline=False)
                return await ctx.send(embed=card)
            if len(entries) == 0:
                return await ctx.send('No results.')
            next_two = entries[1:3]
            if next_two:
                formatted = '\n'.join(map(lambda x: '<%s>' % x, next_two))
                msg = '{}\n\n**See also:**\n{}'.format(entries[0], formatted)
            else:
                msg = entries[0]
            await ctx.send(msg)
예제 #2
0
    async def avi(self, ctx, txt: str = None):
        """View bigger version of user's avatar. Ex: [p]info avi @user"""
        if txt:
            try:
                user = ctx.message.mentions[0]
            except IndexError:
                user = ctx.guild.get_member_named(txt)
            if not user:
                user = ctx.guild.get_member(int(txt))
            if not user:
                user = self.bot.get_user(int(txt))
            if not user:
                await ctx.send(self.bot.bot_prefix + 'Could not find user.')
                return
        else:
            user = ctx.message.author

        if user.avatar_url_as(static_format='png')[54:].startswith('a_'):
            avi = user.avatar_url.rsplit("?", 1)[0]
        else:
            avi = user.avatar_url_as(static_format='png')
        if embed_perms(ctx.message):
            em = discord.Embed(colour=0x708DD0)
            em.set_image(url=avi)
            await ctx.send(embed=em)
        else:
            await ctx.send(self.bot.bot_prefix + avi)
        await ctx.message.delete()
예제 #3
0
    async def avi(self, ctx, txt: str = None):
        """View bigger version of user's avatar. Ex: [p]info avi @user"""
        if txt:
            try:
                user = ctx.message.mentions[0]
            except IndexError:
                user = ctx.guild.get_member_named(txt)
            if not user:
                user = ctx.guild.get_member(int(txt))
            if not user:
                user = self.bot.get_user(int(txt))
            if not user:
                await ctx.send(self.bot.bot_prefix + 'Could not find user.')
                return
        else:
            user = ctx.message.author

        # Thanks to IgneelDxD for help on this
        if user.avatar_url_as(static_format='png')[54:].startswith('a_'):
            avi = 'https://images.discordapp.net/avatars/' + user.avatar_url[35:-10]
        else:
            avi = user.avatar_url_as(static_format='png')
        if embed_perms(ctx.message):
            em = discord.Embed(colour=0x708DD0)
            em.set_image(url=avi)
            await ctx.send(embed=em)
        else:
            await ctx.send(self.bot.bot_prefix + avi)
        await ctx.message.delete()
예제 #4
0
 async def about(self, ctx, txt: str = None):
     """Links to the bot's github page."""
     if embed_perms(ctx.message) and txt != 'short':
         em = discord.Embed(
             color=0xad2929,
             title='\ud83e\udd16 Appu\'s Discord Selfbot',
             description=
             '**Features:**\n- Custom commands/reactions\n- Save last x images in a channel to your computer\n- Keyword notifier\n'
             '- Set/cycle your game status and your avatar\n- Google web and image search\n- MyAnimeList search\n- Spoiler tagging\n'
             '- Server info commands\n- Quoting, calculator, creating polls, and much more'
         )
         em.add_field(
             name='\ud83d\udd17 Link to download',
             value=
             '[Github link](https://github.com/appu1232/Discord-Selfbot/tree/master)'
         )
         em.add_field(
             name='\ud83c\udfa5Quick examples:',
             value='[Simple commands](http://i.imgur.com/3H9zpop.gif)')
         if txt == 'link':
             em.add_field(
                 name='👋 Discord Server',
                 value=
                 'Join the official Discord server [here](https://discord.gg/FGnM5DM)!'
             )
         em.set_footer(text='Made by appu1232#2569',
                       icon_url='https://i.imgur.com/RHagTDg.png')
         await self.bot.send_message(ctx.message.channel,
                                     content=None,
                                     embed=em)
     else:
         await self.bot.send_message(
             ctx.message.channel,
             'https://github.com/appu1232/Selfbot-for-Discord')
     await self.bot.delete_message(ctx.message)
예제 #5
0
    async def avi(self, ctx, txt: str = None):
        """View bigger version of user's avatar. Ex: [p]info avi @user"""
        if txt:
            try:
                user = ctx.message.mentions[0]
            except IndexError:
                user = ctx.guild.get_member_named(txt)
            if not user:
                user = ctx.guild.get_member(int(txt))
            if not user:
                user = self.bot.get_user(int(txt))
            if not user:
                await ctx.send(self.bot.bot_prefix + 'Could not find user.')
                return
        else:
            user = ctx.message.author

        avi = user.avatar_url
        if embed_perms(ctx.message):
            em = discord.Embed(colour=0x708DD0)
            em.set_image(url=avi)
            await ctx.send(embed=em)
        else:
            await ctx.send(self.bot.bot_prefix + avi)
        await ctx.message.delete()
예제 #6
0
    async def now(self, ctx):
        """Date time module."""
        dandt, tzerror = self.get_datetime()
        if embed_perms(ctx.message):
            em = discord.Embed(color=discord.Color.blue())
            em.add_field(name=u'\u23F0 Time',
                         value="{:%H:%M:%S}".format(dandt),
                         inline=False)
            em.add_field(name=u'\U0001F4C5 Date',
                         value="{:%d %B %Y}".format(dandt),
                         inline=False)
            if tzerror:
                em.add_field(
                    name=u'\u26A0 Warning',
                    value=
                    "Invalid timezone specified, system timezone was used instead.",
                    inline=False)

            await self.bot.send_message(ctx.message.channel,
                                        content=None,
                                        embed=em)
        else:
            msg = '**Local Date and Time:** ```{:Time: %H:%M:%S\nDate: %Y-%m-%d```}'.format(
                dandt)
            await self.bot.send_message(ctx.message.channel,
                                        self.bot.bot_prefix + msg)
        await self.bot.delete_message(ctx.message)
예제 #7
0
    async def g(self, ctx, *, query):
        """Google web search. Ex: [p]g what is discordapp?"""
        if not embed_perms(ctx.message):
            config = load_optional_config()
            async with self.bot.session.get("https://www.googleapis.com/customsearch/v1?q=" + urllib.parse.quote_plus(query) + "&start=1" + "&key=" + config['google_api_key'] + "&cx=" + config['custom_search_engine']) as resp:
                result = json.loads(await resp.text())
            return await ctx.send(result['items'][0]['link'])

        try:
            entries, root = await get_google_entries(query, session=self.bot.session)
            card_node = root.find(".//div[@id='topstuff']")
            card = self.parse_google_card(card_node)
        except RuntimeError as e:
            await ctx.send(str(e))
        else:
            if card:
                value = '\n'.join(entries[:2])
                if value:
                    card.add_field(name='Search Results', value=value, inline=False)
                return await ctx.send(embed=card)
            if not entries:
                return await ctx.send('No results.')
            next_two = entries[1:3]
            if next_two:
                formatted = '\n'.join(map(lambda x: '<%s>' % x, next_two))
                msg = '{}\n\n**See also:**\n{}'.format(entries[0], formatted)
            else:
                msg = entries[0]
            await ctx.send(msg)
예제 #8
0
    async def avi(self, ctx, txt: str = None):
        """View bigger version of user's avatar. Ex: >info avi @user"""
        if txt:
            try:
                user = ctx.message.mentions[0]
            except:
                user = ctx.message.server.get_member_named(txt)
            if not user:
                user = ctx.message.server.get_member(txt)
            if not user:
                await self.bot.send_message(
                    ctx.message.channel,
                    self.bot.bot_prefix + 'Could not find user.')
                return
        else:
            user = ctx.message.author

        # Thanks to IgneelDxD for help on this
        if user.avatar_url[54:].startswith('a_'):
            avi = 'https://images.discordapp.net/avatars/' + user.avatar_url[
                35:-10]
        else:
            avi = user.avatar_url
        if embed_perms(ctx.message):
            em = discord.Embed(colour=0x708DD0)
            em.set_image(url=avi)
            await self.bot.send_message(ctx.message.channel, embed=em)
        else:
            await self.bot.send_message(ctx.message.channel,
                                        self.bot.bot_prefix + avi)
        await self.bot.delete_message(ctx.message)
예제 #9
0
 async def i(self, ctx, *, query):
     """Google image search. [p]i Lillie pokemon sun and moon"""
     await ctx.message.delete()
     config = load_optional_config()
     if query[0].isdigit():
         item = int(query[0])
         query = query[1:]
     else:
         item = 0
     async with self.bot.session.get("https://www.googleapis.com/customsearch/v1?q=" + urllib.parse.quote_plus(query) + "&start=" + '1' + "&key=" + config['google_api_key'] + "&cx=" + config['custom_search_engine'] + "&searchType=image") as resp:
         if resp.status != 200:
             if not config['google_api_key'] or not config['custom_search_engine']:
                 return await ctx.send(self.bot.bot_prefix + "You don't seem to have image searching configured properly. Refer to the wiki for details.")
             return await ctx.send(self.bot.bot_prefix + 'Google failed to respond.')
         else:
             result = json.loads(await resp.text())
             try:
                 result['items']
             except:
                 return await ctx.send(self.bot.bot_prefix + 'There were no results to your search. Use more common search query or make sure you have image search enabled for your custom search engine.')
             if len(result['items']) < 1:
                 return await ctx.send(self.bot.bot_prefix + 'There were no results to your search. Use more common search query or make sure you have image search enabled for your custom search engine.')
             em = discord.Embed()
             if embed_perms(ctx.message):
                 em.set_image(url=result['items'][item]['link'])
                 show_search = get_config_value("optional_config", "show_search_term")
                 if show_search == "True":
                     em.set_footer(text="Search term: \"" + query + "\"")
                 await ctx.send(content=None, embed=em)
             else:
                 await ctx.send(result['items'][item]['link'])
                 await ctx.send("Search term: \"" + query + "\"")
예제 #10
0
 async def calc(self, ctx, *, msg):
     """Simple calculator. Ex: >calc 2+2"""
     equation = msg.strip().replace('^', '**').replace('x', '*')
     try:
         if '=' in equation:
             left = eval(
                 equation.split('=')[0], {"__builtins__": None},
                 {"sqrt": sqrt})
             right = eval(
                 equation.split('=')[1], {"__builtins__": None},
                 {"sqrt": sqrt})
             answer = str(left == right)
         else:
             answer = str(
                 eval(equation, {"__builtins__": None}, {"sqrt": sqrt}))
     except TypeError:
         return await self.bot.send_message(
             ctx.message.channel,
             self.bot.bot_prefix + "Invalid calculation query.")
     if embed_perms(ctx.message):
         em = discord.Embed(color=0xD3D3D3, title='Calculator')
         em.add_field(name='Input:',
                      value=msg.replace('**', '^').replace('x', '*'),
                      inline=False)
         em.add_field(name='Output:', value=answer, inline=False)
         await self.bot.send_message(ctx.message.channel,
                                     content=None,
                                     embed=em)
         await self.bot.delete_message(ctx.message)
     else:
         await self.bot.send_message(ctx.message.channel,
                                     self.bot.bot_prefix + answer)
예제 #11
0
 async def i(self, ctx, *, query):
     """Google image search. [p]i Lillie pokemon sun and moon"""
     await ctx.message.delete()
     config = load_optional_config()
     if query[0].isdigit():
         item = int(query[0])
         query = query[1:]
     else:
         item = 0
     async with aiohttp.ClientSession() as session:
         async with session.get("https://www.googleapis.com/customsearch/v1?q=" + urllib.parse.quote_plus(query) + "&start=" + '1' + "&key=" + config['google_api_key'] + "&cx=" + config['custom_search_engine'] + "&searchType=image") as resp:
             if resp.status != 200:
                 if not config['google_api_key'] or not config['custom_search_engine']:
                     return await ctx.send(self.bot.bot_prefix + "You don't seem to have image searching configured properly. Refer to the wiki for details.")
                 return await ctx.send(self.bot.bot_prefix + 'Google failed to respond.')
             else:
                 result = json.loads(await resp.text())
                 try:
                     result['items']
                 except:
                     return await ctx.send(self.bot.bot_prefix + 'There were no results to your search. Use more common search query or make sure you have image search enabled for your custom search engine.')
                 if len(result['items']) < 1:
                     return await ctx.send(self.bot.bot_prefix + 'There were no results to your search. Use more common search query or make sure you have image search enabled for your custom search engine.')
                 em = discord.Embed()
                 if embed_perms(ctx.message):
                     em.set_image(url=result['items'][item]['link'])
                     show_search = get_config_value("optional_config", "show_search_term")
                     if show_search == "True":
                         em.set_footer(text="Search term: \"" + query + "\"")
                     await ctx.send(content=None, embed=em)
                 else:
                     await ctx.send(result['items'][item]['link'])
                     await ctx.send("Search term: \"" + query + "\"")
예제 #12
0
    async def userinfo(self, ctx):
        """Get user info. Ex: >info @user"""
        if ctx.invoked_subcommand is None:
            pre = cmd_prefix_len()
            name = ctx.message.content[4 + pre:].strip()
            if name:
                try:
                    user = ctx.message.mentions[0]
                except:
                    user = ctx.guild.get_member_named(name)
                if not user:
                    user = ctx.guild.get_member(int(name))
                if not user:
                    await ctx.send(self.bot.bot_prefix +
                                   'Could not find user.')
                    return
            else:
                user = ctx.message.author

            # Thanks to IgneelDxD for help on this
            if user.avatar_url[54:].startswith('a_'):
                avi = 'https://images.discordapp.net/avatars/' + user.avatar_url[
                    35:-10]
            else:
                avi = user.avatar_url

            role = user.top_role.name
            if role == "@everyone":
                role = "N/A"
            voice_state = None if not user.voice else user.voice.channel
            if embed_perms(ctx.message):
                em = discord.Embed(timestamp=ctx.message.created_at,
                                   colour=0x708DD0)
                em.add_field(name='User ID', value=user.id, inline=True)
                em.add_field(name='Nick', value=user.nick, inline=True)
                em.add_field(name='Status', value=user.status, inline=True)
                em.add_field(name='In Voice', value=voice_state, inline=True)
                em.add_field(name='Game', value=user.game, inline=True)
                em.add_field(name='Highest Role', value=role, inline=True)
                em.add_field(name='Account Created',
                             value=user.created_at.__format__(
                                 '%A, %d. %B %Y @ %H:%M:%S'))
                em.add_field(name='Join Date',
                             value=user.joined_at.__format__(
                                 '%A, %d. %B %Y @ %H:%M:%S'))
                em.set_thumbnail(url=avi)
                em.set_author(name=user,
                              icon_url='https://i.imgur.com/RHagTDg.png')
                await ctx.send(embed=em)
            else:
                msg = '**User Info:** ```User ID: %s\nNick: %s\nStatus: %s\nIn Voice: %s\nGame: %s\nHighest Role: %s\nAccount Created: %s\nJoin Date: %s\nAvatar url:%s```' % (
                    user.id, user.nick, user.status, voice_state,
                    user.game, role,
                    user.created_at.__format__('%A, %d. %B %Y @ %H:%M:%S'),
                    user.joined_at.__format__('%A, %d. %B %Y @ %H:%M:%S'), avi)
                await ctx.send(self.bot.bot_prefix + msg)

            await ctx.message.delete()
예제 #13
0
    async def de(self, ctx, name):
        """Embeds an image from discordemoji.com"""
        await ctx.message.delete()

        emoji = next((x for x in self.emojis if x['title'] == name), None)

        if embed_perms(ctx.message) and emoji:
            try:
                await ctx.message.channel.send(content=None, embed=discord.Embed().set_image(url=f"https://discordemoji.com/assets/emoji/{emoji['slug']}.png"))
            except:
                return
예제 #14
0
 async def fc(self, ctx, friend_code="all"):
     """List friend codes. Do [p]help fc for more information.
     [p]fc - List all of your friend codes.
     [p]fc <friend_code> - Show one of your friend codes.
     Friend codes are stored in the settings/fc.json file and look similar to this:
     {
         "3DS": "435-233",
         "Wii U": "545262",
         "Steam": "lickinlemons"
     }
     Friend code names are case-insensitive and can contain any characters you want.
     The friend code values can also be anything you want.
     """
     await ctx.message.delete()
     fc = CaseInsensitiveDict(dataIO.load_json("settings/fc.json"))
     if friend_code == "all":
         if not fc:
             return await ctx.send(self.bot.bot_prefix +
                                   "You have no friend codes to show!")
         if embed_perms(ctx.message):
             embed = discord.Embed()
             for code in fc:
                 embed.add_field(name=code, value=fc[code], inline=False)
             return await ctx.send("", embed=embed)
         else:
             message = ""
             for code in fc:
                 message += "**{}**\n{}\n".format(code, fc[code])
             return await ctx.send(message)
     else:
         if not friend_code in fc:
             return await ctx.send(
                 self.bot.bot_prefix +
                 "You don't have a value set for that friend code!")
         if embed_perms(ctx.message):
             embed = discord.Embed()
             embed.add_field(name=friend_code, value=fc[friend_code])
             await ctx.send("", embed=embed)
         else:
             await ctx.send("**{}**\n{}".format(friend_code,
                                                fc[friend_code]))
예제 #15
0
 async def ping(self, ctx):
     """Get response time."""
     msgtime = ctx.message.created_at.now()
     await (await self.bot.ws.ping())
     now = datetime.datetime.now()
     ping = now - msgtime
     if embed_perms(ctx.message):
         pong = discord.Embed(title='Pong! Response Time:', description=str(ping.microseconds / 1000.0) + ' ms',
                              color=0x7A0000)
         pong.set_thumbnail(url='http://odysseedupixel.fr/wp-content/gallery/pong/pong.jpg')
         await ctx.send(content=None, embed=pong)
     else:
         await ctx.send(self.bot.bot_prefix + '``Response Time: %s ms``' % str(ping.microseconds / 1000.0))
예제 #16
0
 async def ping(self, ctx):
     """Get response time."""
     msgtime = ctx.message.created_at.now()
     await (await self.bot.ws.ping())
     now = datetime.datetime.now()
     ping = now - msgtime
     if embed_perms(ctx.message):
         pong = discord.Embed(title='Pong! Response Time:', description=str(ping.microseconds / 1000.0) + ' ms',
                              color=0x7A0000)
         pong.set_thumbnail(url='http://odysseedupixel.fr/wp-content/gallery/pong/pong.jpg')
         await ctx.send(content=None, embed=pong)
     else:
         await ctx.send(self.bot.bot_prefix + '``Response Time: %s ms``' % str(ping.microseconds / 1000.0))
예제 #17
0
 async def avi(self, ctx, msg: str = None):
     """Get server avatar image link."""
     if msg:
         server, found = self.find_server(msg)
     else:
         server = ctx.message.server
     if embed_perms(ctx.message):
         em = discord.Embed()
         em.set_image(url=server.icon_url)
         await self.bot.send_message(ctx.message.channel, embed=em)
     else:
         await self.bot.send_message(ctx.message.channel, self.bot.bot_prefix + server.icon_url)
     await self.bot.delete_message(ctx.message)
예제 #18
0
    async def userinfo(self, ctx, *, name=""):
        """Get user info. Ex: [p]info @user"""
        if ctx.invoked_subcommand is None:
            pre = cmd_prefix_len()
            if name:
                try:
                    user = ctx.message.mentions[0]
                except IndexError:
                    user = ctx.guild.get_member_named(name)
                if not user:
                    user = ctx.guild.get_member(int(name))
                if not user:
                    user = self.bot.get_user(int(name))
                if not user:
                    await ctx.send(self.bot.bot_prefix + 'Could not find user.')
                    return
            else:
                user = ctx.message.author

            if user.avatar_url_as(static_format='png')[54:].startswith('a_'):
                avi = user.avatar_url.rsplit("?", 1)[0]
            else:
                avi = user.avatar_url_as(static_format='png')
            if isinstance(user, discord.Member):
                role = user.top_role.name
                if role == "@everyone":
                    role = "N/A"
                voice_state = None if not user.voice else user.voice.channel
            if embed_perms(ctx.message):
                em = discord.Embed(timestamp=ctx.message.created_at, colour=0x708DD0)
                em.add_field(name='User ID', value=user.id, inline=True)
                if isinstance(user, discord.Member):
                    em.add_field(name='Nick', value=user.nick, inline=True)
                    em.add_field(name='Status', value=user.status, inline=True)
                    em.add_field(name='In Voice', value=voice_state, inline=True)
                    em.add_field(name='Game', value=user.activity, inline=True)
                    em.add_field(name='Highest Role', value=role, inline=True)
                em.add_field(name='Account Created', value=user.created_at.__format__('%A, %d. %B %Y @ %H:%M:%S'))
                if isinstance(user, discord.Member):
                    em.add_field(name='Join Date', value=user.joined_at.__format__('%A, %d. %B %Y @ %H:%M:%S'))
                em.set_thumbnail(url=avi)
                em.set_author(name=user, icon_url='https://i.imgur.com/RHagTDg.png')
                await ctx.send(embed=em)
            else:
                if isinstance(user, discord.Member):
                    msg = '**User Info:** ```User ID: %s\nNick: %s\nStatus: %s\nIn Voice: %s\nGame: %s\nHighest Role: %s\nAccount Created: %s\nJoin Date: %s\nAvatar url:%s```' % (user.id, user.nick, user.status, voice_state, user.activity, role, user.created_at.__format__('%A, %d. %B %Y @ %H:%M:%S'), user.joined_at.__format__('%A, %d. %B %Y @ %H:%M:%S'), avi)
                else:
                    msg = '**User Info:** ```User ID: %s\nAccount Created: %s\nAvatar url:%s```' % (user.id, user.created_at.__format__('%A, %d. %B %Y @ %H:%M:%S'), avi)
                await ctx.send(self.bot.bot_prefix + msg)

            await ctx.message.delete()
예제 #19
0
 async def avi(self, ctx, msg: str = None):
     """Get server avatar image link."""
     if msg:
         server, found = self.find_server(msg)
         if not found:
             return await ctx.send(server)
     else:
         server = ctx.message.guild
     if embed_perms(ctx.message):
         em = discord.Embed()
         em.set_image(url=server.icon_url)
         await ctx.send(embed=em)
     else:
         await ctx.send(self.bot.bot_prefix + server.icon_url)
예제 #20
0
 async def fc(self, ctx, friend_code="all"):
     """List friend codes. Do [p]help fc for more information.
     [p]fc - List all of your friend codes.
     [p]fc <friend_code> - Show one of your friend codes.
     Friend codes are stored in the settings/fc.json file and look similar to this:
     {
         "3DS": "435-233",
         "Wii U": "545262",
         "Steam": "lickinlemons"
     }
     Friend code names are case-insensitive and can contain any characters you want.
     The friend code values can also be anything you want.
     """
     await ctx.message.delete()
     fc = CaseInsensitiveDict(dataIO.load_json("settings/fc.json"))
     if friend_code == "all":
         if not fc:
             return await ctx.send(self.bot.bot_prefix + "You have no friend codes to show!")
         if embed_perms(ctx.message):
             embed = discord.Embed()
             for code in fc:
                 embed.add_field(name=code, value=fc[code], inline=False)
             return await ctx.send("", embed=embed)
         else:
             message = ""
             for code in fc:
                 message += "**{}**\n{}\n".format(code, fc[code])
             return await ctx.send(message)
     else:
         if not friend_code in fc:
             return await ctx.send(self.bot.bot_prefix + "You don't have a value set for that friend code!")
         if embed_perms(ctx.message):
             embed = discord.Embed()
             embed.add_field(name=friend_code, value=fc[friend_code])
             await ctx.send("", embed=embed)
         else:
             await ctx.send("**{}**\n{}".format(friend_code, fc[friend_code]))
예제 #21
0
 async def avi(self, ctx, msg: str = None):
     """Get server avatar image link."""
     if msg:
         server, found = self.find_server(msg)
         if not found:
             return await ctx.send(server)
     else:
         server = ctx.message.guild
     if embed_perms(ctx.message):
         em = discord.Embed()
         em.set_image(url=server.icon_url)
         await ctx.send(embed=em)
     else:
         await ctx.send(self.bot.bot_prefix + server.icon_url)
     await ctx.message.delete()
예제 #22
0
    async def userinfo(self, ctx, *, name=""):
        """Get user info. Ex: [p]info @user"""
        if ctx.invoked_subcommand is None:
            pre = cmd_prefix_len()
            if name:
                try:
                    user = ctx.message.mentions[0]
                except IndexError:
                    user = ctx.guild.get_member_named(name)
                if not user:
                    user = ctx.guild.get_member(int(name))
                if not user:
                    user = self.bot.get_user(int(name))
                if not user:
                    await ctx.send(self.bot.bot_prefix + 'Could not find user.')
                    return
            else:
                user = ctx.message.author

            avi = user.avatar_url
            if isinstance(user, discord.Member):
                role = user.top_role.name
                if role == "@everyone":
                    role = "N/A"
                voice_state = None if not user.voice else user.voice.channel
            if embed_perms(ctx.message):
                em = discord.Embed(timestamp=ctx.message.created_at, colour=0x708DD0)
                em.add_field(name='User ID', value=user.id, inline=True)
                if isinstance(user, discord.Member):
                    em.add_field(name='Nick', value=user.nick, inline=True)
                    em.add_field(name='Status', value=user.status, inline=True)
                    em.add_field(name='In Voice', value=voice_state, inline=True)
                    em.add_field(name='Game', value=user.activity, inline=True)
                    em.add_field(name='Highest Role', value=role, inline=True)
                em.add_field(name='Account Created', value=user.created_at.__format__('%A, %d. %B %Y @ %H:%M:%S'))
                if isinstance(user, discord.Member):
                    em.add_field(name='Join Date', value=user.joined_at.__format__('%A, %d. %B %Y @ %H:%M:%S'))
                em.set_thumbnail(url=avi)
                em.set_author(name=user, icon_url='https://i.imgur.com/RHagTDg.png')
                await ctx.send(embed=em)
            else:
                if isinstance(user, discord.Member):
                    msg = '**User Info:** ```User ID: %s\nNick: %s\nStatus: %s\nIn Voice: %s\nGame: %s\nHighest Role: %s\nAccount Created: %s\nJoin Date: %s\nAvatar url:%s```' % (user.id, user.nick, user.status, voice_state, user.activity, role, user.created_at.__format__('%A, %d. %B %Y @ %H:%M:%S'), user.joined_at.__format__('%A, %d. %B %Y @ %H:%M:%S'), avi)
                else:
                    msg = '**User Info:** ```User ID: %s\nAccount Created: %s\nAvatar url:%s```' % (user.id, user.created_at.__format__('%A, %d. %B %Y @ %H:%M:%S'), avi)
                await ctx.send(self.bot.bot_prefix + msg)

            await ctx.message.delete()
예제 #23
0
 async def about(self, ctx, txt: str = None):
     """Links to the bot's github page."""
     if embed_perms(ctx.message) and txt != 'short':
         em = discord.Embed(color=0xad2929, title='\ud83e\udd16 Appu\'s Discord Selfbot',
                            description='**Features:**\n- Custom commands/reactions\n- Save last x images in a channel to your computer\n- Keyword notifier\n'
                                        '- Set/cycle your game status and your avatar\n- Google web and image search\n- MyAnimeList search\n- Spoiler tagging\n'
                                        '- Server info commands\n- Quoting, calculator, creating polls, and much more')
         em.add_field(name='\ud83d\udd17 Link to download',
                      value='[Github link](https://github.com/appu1232/Discord-Selfbot/tree/master)')
         em.add_field(name='\ud83c\udfa5Quick examples:', value='[Simple commands](http://i.imgur.com/3H9zpop.gif)')
         if txt == 'link': em.add_field(name='👋 Discord Server', value='Join the official Discord server [here](https://discord.gg/FGnM5DM)!')
         em.set_footer(text='Made by appu1232#2569', icon_url='https://i.imgur.com/RHagTDg.png')
         await ctx.send(content=None, embed=em)
     else:
         await ctx.send('https://github.com/appu1232/Selfbot-for-Discord')
     await ctx.message.delete()
예제 #24
0
 async def ping(self, ctx):
     """Get response time."""
     msgtime = ctx.message.created_at.now()
     await (await self.bot.ws.ping())
     now = datetime.datetime.now()
     ping = now - msgtime
     if embed_perms(ctx.message):
         pong = discord.Embed(title='Pong!',
                              description=str(ping.microseconds / 1000.0) +
                              ' ms',
                              color=0x35465C)
         pong.set_thumbnail(url='https://i.imgur.com/xafWcc2.gif')
         await ctx.send(content=None, embed=pong)
     else:
         await ctx.send(self.bot.bot_prefix + '``Response Time: %s ms``' %
                        str(ping.microseconds / 1000.0))
예제 #25
0
    async def setavatar(self, ctx, *, msg):
        """
        Set an avatar from a URL: Usage >setavatar <url_to_image>
        Image must be a .png or a .jpg
        """
        url = msg
        response = requests.get(url, stream=True)
        name = url.split('/')[-1]
        with open(name, 'wb') as img:

            for block in response.iter_content(1024):
                if not block:
                    break

                img.write(block)

        if url:
            with open(name, 'rb') as fp:
                e = fp.read()
                with open('settings/avatars.json', 'r+') as fp:
                    opt = json.load(fp)
                    if opt['password']:
                        if opt['password'] == "":
                            await self.bot.send_message(
                                ctx.message.channel,
                                "You have not set your password yet in `settings/avatars.json` Please do so and try again"
                            )
                        else:
                            pw = opt['password']
                            await self.bot.edit_profile(password=pw, avatar=e)
                            await self.bot.send_message(
                                ctx.message.channel,
                                "Your avatar has been set to the specified image"
                            )
                    else:
                        opt['password'] = ""
                        await self.bot.send_message(
                            ctx.message.channel,
                            "You have not set your password yet in `settings/avatars.json` Please do so and try again"
                        )
            os.remove(name)
        elif not embed_perms(ctx.message) and url:
            await self.bot.send_message(ctx.message.channel, url)
        else:
            await self.bot.send_message(
                ctx.message.channel,
                self.bot.bot_prefix + 'Could not find image.')
예제 #26
0
파일: fun.py 프로젝트: afifeka/selfbot-ray
 async def ball8(self, ctx, *, msg: str):
     """Let the 8ball decide your fate. Ex: [p]8ball Will I get good?"""
     answer = random.randint(0, 19)
     if embed_perms(ctx.message):
         if answer < 10:
             color = 0x008000
         elif 10 <= answer < 15:
             color = 0xFFD700
         else:
             color = 0xFF0000
         em = discord.Embed(color=color)
         em.add_field(name='\u2753 Question', value=msg)
         em.add_field(name='\ud83c\udfb1 8ball', value=self.ball[answer], inline=False)
         await ctx.send(content=None, embed=em)
         await ctx.message.delete()
     else:
         await ctx.send('\ud83c\udfb1 ``{}``'.format(random.choice(self.ball)))
예제 #27
0
 async def ball8(self, ctx, *, msg: str):
     """Let the 8ball decide your fate. Ex: [p]8ball Will I get good?"""
     answer = random.randint(0, 19)
     if embed_perms(ctx.message):
         if answer < 10:
             color = 0x008000
         elif 10 <= answer < 15:
             color = 0xFFD700
         else:
             color = 0xFF0000
         em = discord.Embed(color=color)
         em.add_field(name='\u2753 Question', value=msg)
         em.add_field(name='\ud83c\udfb1 8ball', value=self.ball[answer], inline=False)
         await ctx.send(content=None, embed=em)
         await ctx.message.delete()
     else:
         await ctx.send('\ud83c\udfb1 ``{}``'.format(random.choice(self.ball)))
예제 #28
0
 async def calc(self, ctx, *, msg):
     """Simple calculator. Ex: >calc 2+2"""
     equation = msg.strip().replace('^', '**')
     if '=' in equation:
         left = eval(equation.split('=')[0])
         right = eval(equation.split('=')[1])
         answer = str(left == right)
     else:
         answer = str(eval(equation))
     if embed_perms(ctx.message):
         em = discord.Embed(color=0xD3D3D3, title='Calculator')
         em.add_field(name='Input:',
                      value=msg.replace('**', '^'),
                      inline=False)
         em.add_field(name='Output:', value=answer, inline=False)
         await self.bot.send_message(ctx.message.channel,
                                     content=None,
                                     embed=em)
         await self.bot.delete_message(ctx.message)
     else:
         await self.bot.send_message(ctx.message.channel,
                                     self.bot.bot_prefix + answer)
예제 #29
0
    async def quote(self, ctx, *, msg: str = None):
        """Quote a message. >help quote for more info.
        >quote - quotes the last message sent in the channel.
        >quote <words> - tries to search for a message in the server that contains the given words and quotes it.
        >quote <message_id> - quotes the message with the given message id. Ex: >quote 302355374524644290(Enable developer mode to copy message ids).
        >quote <words> | channel=<channel_name> - quotes the message with the given words from the channel name specified in the second argument
        >quote <message_id> | channel=<channel_name> - quotes the message with the given message id in the given channel name"""
        result = channel = None
        pre = cmd_prefix_len()
        await self.bot.delete_message(ctx.message)
        if msg:
            try:
                length = len(self.bot.all_log[ctx.message.channel.id + ' ' +
                                              ctx.message.server.id])
                if length < 201:
                    size = length
                else:
                    size = 200
                for channel in ctx.message.server.channels:
                    if str(channel.type) == 'text':
                        if channel.id + ' ' + ctx.message.server.id in self.bot.all_log:
                            for i in range(length - 2, length - size, -1):
                                try:
                                    search = self.bot.all_log[
                                        channel.id + ' ' +
                                        ctx.message.server.id][i]
                                except:
                                    continue
                                if (msg.lower().strip()
                                        in search[0].content.lower() and
                                    (search[0].author != ctx.message.author
                                     or search[0].content[pre:7] != 'quote ')
                                    ) or (ctx.message.content[6:].strip()
                                          == search[0].id):
                                    result = search[0]
                                    break
                            if result:
                                break
            except KeyError:
                pass

            if not result:
                if " | channel=" in msg:
                    channelList = []
                    for channels in self.bot.get_all_channels():
                        if channels.name == msg.split("| channel=")[1]:
                            channelList.append(channels)
                    msg = msg.split(" | channel=")[0]
                    for channel in channelList:
                        if str(channel.type) == 'text':
                            if channel.id + ' ' + ctx.message.server.id in self.bot.all_log:
                                for i in range(length - 2, length - size, -1):
                                    try:
                                        search = self.bot.all_log[
                                            channel.id + ' ' +
                                            ctx.message.server.id][i]
                                    except:
                                        continue
                                    if (msg.lower().strip()
                                            in search[0].content.lower() and
                                        (search[0].author != ctx.message.author
                                         or
                                         search[0].content[pre:7] != 'quote ')
                                        ) or (ctx.message.content[6:].strip()
                                              == search[0].id):
                                        result = search[0]
                                        break
                                if result:
                                    break
                    if not result:
                        for channel in channelList:
                            try:
                                async for sent_message in self.bot.logs_from(
                                        channel, limit=500):
                                    if (msg.lower().strip()
                                            in sent_message.content and
                                        (sent_message.author !=
                                         ctx.message.author
                                         or sent_message.content[pre:7] !=
                                         'quote ')) or (msg.strip()
                                                        == sent_message.id):
                                        result = sent_message
                                        break
                            except:
                                pass
                            if result:
                                break
            if not result:
                for channel in ctx.message.server.channels:
                    try:
                        async for sent_message in self.bot.logs_from(
                                channel, limit=500):
                            if (msg.lower().strip() in sent_message.content and
                                (sent_message.author != ctx.message.author
                                 or sent_message.content[pre:7] != 'quote ')
                                ) or (msg.strip() == sent_message.id):
                                result = sent_message
                                break
                    except:
                        pass
                    if result:
                        break

        else:
            channel = ctx.message.channel
            search = self.bot.all_log[ctx.message.channel.id + ' ' +
                                      ctx.message.server.id][-2]
            result = search[0]
        if result:
            sender = result.author.nick if result.author.nick else result.author.name
            if embed_perms(ctx.message) and result.content:
                em = discord.Embed(description=result.content,
                                   timestamp=result.timestamp)
                with open('settings/optional_config.json') as fp:
                    opt = json.load(fp)
                try:
                    embed_color = opt['quoteembed_color']
                    if embed_color == "auto":
                        em.color = result.author.top_role.color
                    else:
                        em.color = int('0x' + embed_color, 16)
                except:
                    em.color = 0xbc0b0b
                em.set_author(name=sender, icon_url=result.author.avatar_url)
                if channel != ctx.message.channel:
                    em.set_footer(text='#{} | {} '.format(
                        channel.name, channel.server.name))
                await self.bot.send_message(ctx.message.channel, embed=em)
            else:
                await self.bot.send_message(
                    ctx.message.channel, '%s - %s```%s```' %
                    (sender, result.timestamp, result.content))
        else:
            await self.bot.send_message(
                ctx.message.channel, self.bot.bot_prefix + 'No quote found.')
예제 #30
0
 async def stats(self, ctx):
     """Bot stats."""
     uptime = (datetime.datetime.now() - self.bot.uptime)
     hours, rem = divmod(int(uptime.total_seconds()), 3600)
     minutes, seconds = divmod(rem, 60)
     days, hours = divmod(hours, 24)
     if days:
         time = '%s days, %s hours, %s minutes, and %s seconds' % (days, hours, minutes, seconds)
     else:
         time = '%s hours, %s minutes, and %s seconds' % (hours, minutes, seconds)
     game = self.bot.game
     if not game:
         game = 'None'
     channel_count = 0
     for guild in self.bot.guilds:
         channel_count += len(guild.channels)
     if not self.bot.command_count:
         most_used_cmd = 'Not enough info'
     else:
         cmd_name = max(self.bot.command_count, key=self.bot.command_count.get)
         total_usage = self.bot.command_count[str(cmd_name)]
         plural = '' if total_usage == 1 else 's'
         most_used_cmd = '{} - {} use{}'.format(cmd_name, total_usage, plural)
     if embed_perms(ctx.message):
         em = discord.Embed(title='Bot Stats', color=0x32441c)
         em.add_field(name=u'\U0001F553 Uptime', value=time, inline=False)
         em.add_field(name=u'\u2328 Most Used Cmd', value=most_used_cmd, inline=False)
         em.add_field(name=u'\U0001F4E4 Msgs sent', value=str(self.bot.icount))
         em.add_field(name=u'\U0001F4E5 Msgs received', value=str(self.bot.message_count))
         em.add_field(name=u'\u2757 Mentions', value=str(self.bot.mention_count))
         em.add_field(name=u'\u2694 Servers', value=str(len(self.bot.guilds)))
         em.add_field(name=u'\ud83d\udcd1 Channels', value=str(channel_count))
         em.add_field(name=u'\u270F Keywords logged', value=str(self.bot.keyword_log))
         g = u'\U0001F3AE Game'
         if '=' in game: g = '\ud83c\udfa5 Stream'
         em.add_field(name=g, value=game)
         try:
             mem_usage = '{:.2f} MiB'.format(__import__('psutil').Process().memory_full_info().uss / 1024 ** 2)
         except AttributeError:
             # OS doesn't support retrieval of USS (probably BSD or Solaris)
             mem_usage = '{:.2f} MiB'.format(__import__('psutil').Process().memory_full_info().rss / 1024 ** 2)
         em.add_field(name=u'\U0001F4BE Memory usage:', value=mem_usage)
         try:
             g = git.cmd.Git(working_dir=os.getcwd())
             branch = g.execute(["git", "rev-parse", "--abbrev-ref", "HEAD"])
             g.execute(["git", "fetch", "origin", branch])
             version = g.execute(["git", "rev-list", "--right-only", "--count", "{}...origin/{}".format(branch, branch)])
             if branch == "master":
                 branch_note = "."
             else:
                 branch_note = " (`" + branch + "` branch)."
             if version == '0':
                 status = 'Up to date%s' % branch_note
             else:
                 latest = g.execute(
                     ["git", "log", "--pretty=oneline", "--abbrev-commit", "--stat", "--pretty", "-%s" % version,
                      "origin/%s" % branch])
                 haste_latest = await hastebin(latest, self.bot.session)
                 if version == '1':
                     status = 'Behind by 1 release%s [Latest update.](%s)' % (branch_note, haste_latest)
                 else:
                     status = '%s releases behind%s [Latest updates.](%s)' % (version, branch_note, haste_latest)
             em.add_field(name=u'\U0001f4bb Update status:', value=status)
         except:
             pass
         await ctx.send(content=None, embed=em)
     else:
         msg = '**Bot Stats:** ```Uptime: %s\nMessages Sent: %s\nMessages Received: %s\nMentions: %s\nguilds: %s\nKeywords logged: %s\nGame: %s```' % (
         time, str(self.bot.icount), str(self.bot.message_count), str(self.bot.mention_count),
         str(len(self.bot.guilds)), str(self.bot.keyword_log), game)
         await ctx.send(self.bot.bot_prefix + msg)
     await ctx.message.delete()
예제 #31
0
 async def stats(self, ctx):
     """Bot stats."""
     uptime = (datetime.datetime.now() - self.bot.uptime)
     hours, rem = divmod(int(uptime.total_seconds()), 3600)
     minutes, seconds = divmod(rem, 60)
     days, hours = divmod(hours, 24)
     if days:
         time = '%s days, %s hours, %s minutes, and %s seconds' % (
             days, hours, minutes, seconds)
     else:
         time = '%s hours, %s minutes, and %s seconds' % (hours, minutes,
                                                          seconds)
     game = self.bot.game
     if not game:
         game = 'None'
     channel_count = 0
     for server in self.bot.servers:
         channel_count += len(server.channels)
     if embed_perms(ctx.message):
         em = discord.Embed(title='Bot Stats', color=0x32441c)
         em.add_field(name=u'\U0001F553 Uptime', value=time, inline=False)
         em.add_field(name=u'\U0001F4E4 Msgs sent',
                      value=str(self.bot.icount))
         em.add_field(name=u'\U0001F4E5 Msgs received',
                      value=str(self.bot.message_count))
         em.add_field(name=u'\u2757 Mentions',
                      value=str(self.bot.mention_count))
         em.add_field(name=u'\u2694 Servers',
                      value=str(len(self.bot.servers)))
         em.add_field(name=u'\ud83d\udcd1 Channels',
                      value=str(channel_count))
         em.add_field(name=u'\u270F Keywords logged',
                      value=str(self.bot.keyword_log))
         g = u'\U0001F3AE Game'
         if '=' in game: g = '\ud83c\udfa5 Stream'
         em.add_field(name=g, value=game)
         mem_usage = '{:.2f} MiB'.format(
             __import__('psutil').Process().memory_full_info().uss /
             1024**2)
         em.add_field(name=u'\U0001F4BE Memory usage:', value=mem_usage)
         try:
             g = git.cmd.Git(working_dir=os.getcwd())
             branch = g.execute(
                 ["git", "rev-parse", "--abbrev-ref", "HEAD"])
             g.execute(["git", "fetch", "origin", branch])
             version = g.execute([
                 "git", "rev-list", "--right-only", "--count",
                 "{}...origin/{}".format(branch, branch)
             ])
             if branch == "master":
                 branch_note = "."
             else:
                 branch_note = " (`" + branch + "` branch)."
             if version == '0':
                 status = 'Up to date%s' % branch_note
             else:
                 latest = g.execute([
                     "git", "log", "--pretty=oneline", "--abbrev-commit",
                     "--stat", "--pretty",
                     "-%s" % version,
                     "origin/%s" % branch
                 ])
                 gist_latest = PythonGists.Gist(
                     description='Latest changes for the selfbot.',
                     content=latest,
                     name='latest.txt')
                 if version == '1':
                     status = 'Behind by 1 release%s [Latest update.](%s)' % (
                         branch_note, gist_latest)
                 else:
                     status = '%s releases behind%s [Latest updates.](%s)' % (
                         version, branch_note, gist_latest)
             em.add_field(name=u'\U0001f4bb Update status:', value=status)
         except:
             pass
         await self.bot.send_message(ctx.message.channel,
                                     content=None,
                                     embed=em)
     else:
         msg = '**Bot Stats:** ```Uptime: %s\nMessages Sent: %s\nMessages Received: %s\nMentions: %s\nServers: %s\nKeywords logged: %s\nGame: %s```' % (
             time, str(self.bot.icount), str(self.bot.message_count),
             str(self.bot.mention_count), str(len(
                 self.bot.servers)), str(self.bot.keyword_log), game)
         await self.bot.send_message(ctx.message.channel,
                                     self.bot.bot_prefix + msg)
     await self.bot.delete_message(ctx.message)
예제 #32
0
    async def quote(self, ctx, *, msg: str = ""):
        """Quote a message. [p]help quote for more info.
        [p]quote - quotes the last message sent in the channel.
        [p]quote <words> - tries to search for a message in the server that contains the given words and quotes it.
        [p]quote <message_id> - quotes the message with the given message ID. Ex: [p]quote 302355374524644290 (enable developer mode to copy message IDs)
        [p]quote <user_mention_name_or_id> - quotes the last message sent by a specific user
        [p]quote <words> | channel=<channel_name> - quotes the message with the given words in a specified channel
        [p]quote <message_id> | channel=<channel_name> - quotes the message with the given message ID in a specified channel
        [p]quote <user_mention_name_or_id> | channel=<channel_name> - quotes the last message sent by a specific user in a specified channel
        """
        
        await ctx.message.delete()
        result = None
        channels = [ctx.channel] + [x for x in ctx.guild.channels if x != ctx.channel and type(x) == discord.channel.TextChannel]
        
        args = msg.split(" | ")
        msg = args[0]
        if len(args) > 1:
            channel = args[1].split("channel=")[1]
            channels = []
            for chan in ctx.guild.channels:
                if chan.name == channel or str(chan.id) == channel:
                    channels.append(chan)
                    break
            else:
                for guild in self.bot.guilds:
                    for chan in guild.channels:
                        if chan.name == channel or str(chan.id) == channel and type(chan) == discord.channel.TextChannel:
                            channels.append(chan)
                            break
            if not channels:
                return await ctx.send(self.bot.bot_prefix + "The specified channel could not be found.")
            
        user = get_user(ctx.message, msg)

        async def get_quote(msg, channels, user):
            for channel in channels:
                try:
                    if user:
                        async for message in channel.history(limit=500):
                            if message.author == user:
                                return message
                    if len(msg) > 15 and msg.isdigit():
                        async for message in channel.history(limit=500):
                            if str(message.id) == msg:
                                return message
                    else:
                        async for message in channel.history(limit=500):
                            if msg in message.content:
                                return message
                except discord.Forbidden:
                    continue
            return None
            
        if msg:
            result = await get_quote(msg, channels, user)
        else:
            async for message in ctx.channel.history(limit=1):
                result = message
        
        if result:
            if type(result.author) == discord.User:
                sender = result.author.name
            else:
                sender = result.author.nick if result.author.nick else result.author.name
            if embed_perms(ctx.message) and result.content:
                color = get_config_value("optional_config", "quoteembed_color")
                if color == "auto":
                    color = result.author.top_role.color
                elif color == "":
                    color = 0xbc0b0b
                else:
                    color = int('0x' + color, 16)
                em = discord.Embed(color=color, description=result.content, timestamp=result.created_at)
                em.set_author(name=sender, icon_url=result.author.avatar_url)
                footer = ""
                if result.channel != ctx.channel:
                    footer += "#" + result.channel.name
                    
                if result.guild != ctx.guild:
                    footer += " | " + result.guild.name
                    
                if footer:
                    em.set_footer(text=footer)
                await ctx.send(embed=em)
            elif result.content:
                await ctx.send('%s - %s```%s```' % (sender, result.created_at, result.content))
            else:
                await ctx.send(self.bot.bot_prefix + "Embeds cannot be quoted.")
        else:
            await ctx.send(self.bot.bot_prefix + 'No quote found.')
예제 #33
0
    async def embed(self, ctx, *, msg: str = None):
        """Embed given text. Ex: Do >embed for more help

        Example: >embed title=test this | description=some words | color=3AB35E | field=name=test value=test

        You do NOT need to specify every property, only the ones you want.

        **All properties and the syntax (put your custom stuff in place of the <> stuff):
        - title=<words>
        - description=<words>
        - color=<hex_value>
        - image=<url_to_image> (must be https)
        - thumbnail=<url_to_image>
        - author=<words> **OR** author=name=<words> icon=<url_to_image>
        - footer=<words> **OR** footer=name=<words> icon=<url_to_image>
        - field=name=<words> value=<words> (you can add as many fields as you want)
        - ptext=<words>

        NOTE: After the command is sent, the bot will delete your message and replace it with the embed. Make sure you have it saved or else you'll have to type it all again if the embed isn't how you want it.
        PS: Hyperlink text like so: [text](https://www.whateverlink.com)
        PPS: Force a field to go to the next line with the added parameter inline=False"""
        if msg:
            if embed_perms(ctx.message):
                ptext = title = description = image = thumbnail = color = footer = author = None
                timestamp = discord.Embed.Empty
                embed_values = msg.split('|')
                for i in embed_values:
                    with open('settings/optional_config.json', 'r+') as fp:
                        opt = json.load(fp)
                        if opt['embed_color'] != "":
                            color = opt['embed_color']
                    if i.strip().lower().startswith('ptext='):
                        ptext = i.strip()[6:].strip()
                    elif i.strip().lower().startswith('title='):
                        title = i.strip()[6:].strip()
                    elif i.strip().lower().startswith('description='):
                        description = i.strip()[12:].strip()
                    elif i.strip().lower().startswith('desc='):
                        description = i.strip()[5:].strip()
                    elif i.strip().lower().startswith('image='):
                        image = i.strip()[6:].strip()
                    elif i.strip().lower().startswith('thumbnail='):
                        thumbnail = i.strip()[10:].strip()
                    elif i.strip().lower().startswith('colour='):
                        color = i.strip()[7:].strip()
                    elif i.strip().lower().startswith('color='):
                        color = i.strip()[6:].strip()
                    elif i.strip().lower().startswith('footer='):
                        footer = i.strip()[7:].strip()
                    elif i.strip().lower().startswith('author='):
                        author = i.strip()[7:].strip()
                    elif i.strip().lower().startswith('timestamp'):
                        timestamp = ctx.message.timestamp
                    else:
                        if description is None and not i.strip().lower(
                        ).startswith('field='):
                            description = i.strip()

                if color:
                    if color.startswith('#'):
                        color = color[1:]
                    if not color.startswith('0x'):
                        color = '0x' + color

                if ptext is title is description is image is thumbnail is color is footer is author is None and 'field=' not in msg:
                    await self.bot.delete_message(ctx.message)
                    return await self.bot.send_message(
                        ctx.message.channel,
                        content=None,
                        embed=discord.Embed(description=msg))

                if color:
                    em = discord.Embed(timestamp=timestamp,
                                       title=title,
                                       description=description,
                                       color=int(color, 16))
                else:
                    em = discord.Embed(timestamp=timestamp,
                                       title=title,
                                       description=description)
                for i in embed_values:
                    if i.strip().lower().startswith('field='):
                        field_inline = True
                        field = i.strip().lstrip('field=')
                        field_name, field_value = field.split('value=')
                        if 'inline=' in field_value:
                            field_value, field_inline = field_value.split(
                                'inline=')
                            if 'false' in field_inline.lower(
                            ) or 'no' in field_inline.lower():
                                field_inline = False
                        field_name = field_name.strip().lstrip('name=')
                        em.add_field(name=field_name,
                                     value=field_value.strip(),
                                     inline=field_inline)
                if author:
                    if 'icon=' in author:
                        text, icon = author.split('icon=')
                        if 'url=' in icon:
                            print("here")
                            em.set_author(
                                name=text.strip()[5:],
                                icon_url=icon.split('url=')[0].strip(),
                                url=icon.split('url=')[1].strip())
                        else:
                            em.set_author(name=text.strip()[5:], icon_url=icon)
                    else:
                        if 'url=' in author:
                            print("here")
                            em.set_author(
                                name=author.split('url=')[0].strip()[5:],
                                url=author.split('url=')[1].strip())
                        else:
                            em.set_author(name=author)

                if image:
                    em.set_image(url=image)
                if thumbnail:
                    em.set_thumbnail(url=thumbnail)
                if footer:
                    if 'icon=' in footer:
                        text, icon = footer.split('icon=')
                        em.set_footer(text=text.strip()[5:], icon_url=icon)
                    else:
                        em.set_footer(text=footer)
                await self.bot.send_message(ctx.message.channel,
                                            content=ptext,
                                            embed=em)
            else:
                await self.bot.send_message(
                    ctx.message.channel, self.bot.bot_prefix +
                    'No embed permissions in this channel.')
        else:
            msg = '```How to use the >embed command:\nExample: >embed title=test this | description=some words | color=3AB35E | field=name=test value=test\n\nYou do NOT need to specify every property, only the ones you want.' \
                  '\nAll properties and the syntax (put your custom stuff in place of the <> stuff):\ntitle=<words>\ndescription=<words>\ncolor=<hex_value>\nimage=<url_to_image> (must be https)\nthumbnail=<url_to_image>\nauthor=<words> **OR** author=name=<words> icon=<url_to_image>\nfooter=<words> ' \
                  '**OR** footer=name=<words> icon=<url_to_image>\nfield=name=<words> value=<words> (you can add as many fields as you want)\nptext=<words>\n\nNOTE: After the command is sent, the bot will delete your message and replace it with ' \
                  'the embed. Make sure you have it saved or else you\'ll have to type it all again if the embed isn\'t how you want it.\nPS: Hyperlink text like so: [text](https://www.whateverlink.com)\nPPS: Force a field to go to the next line with the added parameter inline=False```'
            await self.bot.send_message(ctx.message.channel,
                                        self.bot.bot_prefix + msg)
        try:
            await self.bot.delete_message(ctx.message)
        except:
            pass
예제 #34
0
    async def quote(self, ctx, *, msg: str = ""):
        """Quote a message. [p]help quote for more info.
        [p]quote - quotes the last message sent in the channel.
        [p]quote <words> - tries to search for a message in the server that contains the given words and quotes it.
        [p]quote <message_id> - quotes the message with the given message ID. Ex: [p]quote 302355374524644290 (enable developer mode to copy message IDs)
        [p]quote <user_mention_name_or_id> - quotes the last message sent by a specific user
        [p]quote <words> | channel=<channel_name> - quotes the message with the given words in a specified channel
        [p]quote <message_id> | channel=<channel_name> - quotes the message with the given message ID in a specified channel
        [p]quote <user_mention_name_or_id> | channel=<channel_name> - quotes the last message sent by a specific user in a specified channel
        """
        
        ###await ctx.message.delete()
        result = None
        channels = [ctx.channel] + [x for x in ctx.guild.channels if x != ctx.channel and type(x) == discord.channel.TextChannel]
        
        args = msg.split(" | ")
        msg = args[0]
        if len(args) > 1:
            channel = args[1].split("channel=")[1]
            channels = []
            for chan in ctx.guild.channels:
                if chan.name == channel or str(chan.id) == channel:
                    channels.append(chan)
                    break
            else:
                for guild in self.bot.guilds:
                    for chan in guild.channels:
                        if chan.name == channel or str(chan.id) == channel and type(chan) == discord.channel.TextChannel:
                            channels.append(chan)
                            break
            if not channels:
                return await ctx.send(self.bot.bot_prefix + "The specified channel could not be found.")
            
        user = get_user(ctx.message, msg)

        async def get_quote(msg, channels, user):
            for channel in channels:
                try:
                    if user:
                        async for message in channel.history(limit=500):
                            if message.author == user:
                                return message
                    if len(msg) > 15 and msg.isdigit():
                        async for message in channel.history(limit=500):
                            if str(message.id) == msg:
                                return message
                    else:
                        async for message in channel.history(limit=500):
                            if msg in message.content:
                                return message
                except discord.Forbidden:
                    continue
            return None
            
        if msg:
            result = await get_quote(msg, channels, user)
        else:
            async for message in ctx.channel.history(limit=1):
                result = message
        
        if result:
            if type(result.author) == discord.User:
                sender = result.author.name
            else:
                sender = result.author.nick if result.author.nick else result.author.name
            if embed_perms(ctx.message) and result.content:
                color = get_config_value("optional_config", "quoteembed_color")
                if color == "auto":
                    color = result.author.top_role.color
                elif color == "":
                    color = 0xbc0b0b
                else:
                    color = int('0x' + color, 16)
                em = discord.Embed(color=color, description=result.content, timestamp=result.created_at)
                em.set_author(name=sender, icon_url=result.author.avatar_url)
                footer = ""
                if result.channel != ctx.channel:
                    footer += "#" + result.channel.name
                    
                if result.guild != ctx.guild:
                    footer += " | " + result.guild.name
                    
                if footer:
                    em.set_footer(text=footer)
                await ctx.send(embed=em)
            elif result.content:
                await ctx.send('%s - %s```%s```' % (sender, result.created_at, result.content))
            else:
                await ctx.send(self.bot.bot_prefix + "Embeds cannot be quoted.")
        else:
            await ctx.send(self.bot.bot_prefix + 'No quote found.')
예제 #35
0
파일: session.py 프로젝트: cmpgamer/gwbot
    async def wvw_session(self, ctx):
        discord_user_id = ctx.message.author.id
        result = None
        try:
            with db.create_connection(**config_data) as connection:
                with connection.cursor() as cur:
                    query = """
                        SELECT * FROM Gw2SessionInfo WHERE id = %s
                    """
                    cur.execute(
                        query,
                        (discord_user_id,)
                    )
                    result = cur.fetchone()
        except Exception as e:
            await ctx.send("Error processing !session wvw")
        else:
            #
            startAchievementInfo = {value['id']: value for value in result['startinfo']['achievements']}
            endAchievementInfo = {value['id']: value for value in result['endinfo']['achievements']}

            startDeaths = {'current': sum([character['deaths'] for character in result['startinfo']['characters']])}
            endDeaths = {'current': sum([character['deaths'] for character in result['endinfo']['characters']])}

            startTime = result['starttime']
            endTime = result['endtime']
            startWvWInfo = {
                'WvW Repairs': startAchievementInfo.get(306, {'current': 0}),
                'WvW Kills': startAchievementInfo.get(283, {'current': 0}),
                'Yak Escort': startAchievementInfo.get(285, {'current': 0}),
                'WvW Yak Kills': startAchievementInfo.get(288, {'current': 0}),
                'WvW Camps': startAchievementInfo.get(291, {'current': 0}),
                'WvW Towers': startAchievementInfo.get(297, {'current': 0}),
                'WvW Keeps': startAchievementInfo.get(300, {'current': 0}),
                'WvW Castles': startAchievementInfo.get(294, {'current': 0}),
                'Warclaw Kills': startAchievementInfo.get(4641, {'current': 0, 'repeated':0}),
                'Warclaw Gate Damage': startAchievementInfo.get(4644, {'current': 0, 'repeated':0}),
                'Deaths': startDeaths
            }
            endWvWInfo = {
                'WvW Repairs': endAchievementInfo.get(306, {'current': 0}),
                'WvW Kills': endAchievementInfo.get(283, {'current': 0}),
                'Yak Escort': endAchievementInfo.get(285, {'current': 0}),
                'WvW Yak Kills': endAchievementInfo.get(288, {'current': 0}),
                'WvW Camps': endAchievementInfo.get(291, {'current': 0}),
                'WvW Towers': endAchievementInfo.get(297, {'current': 0}),
                'WvW Keeps': endAchievementInfo.get(300, {'current': 0}),
                'WvW Castles': endAchievementInfo.get(294, {'current': 0}),
                'Warclaw Kills': endAchievementInfo.get(4641, {'current': 0, 'repeated':0}),
                'Warclaw Gate Damage': endAchievementInfo.get(4644, {'current': 0, 'repeated':0}),
                'Deaths': endDeaths
            }
            # print(startWvWInfo)
            # Normalize Warclaw Kills
            if 'repeated' in startWvWInfo['Warclaw Kills']:
                startWvWInfo['Warclaw Kills']['current'] += startWvWInfo['Warclaw Kills']['repeated'] * 5
                endWvWInfo['Warclaw Kills']['current'] += endWvWInfo['Warclaw Kills']['repeated'] * 5

            # Normalize Warclaw Gate Damage
            if 'repeated' in startWvWInfo['Warclaw Gate Damage']:
                startWvWInfo['Warclaw Gate Damage']['current'] += startWvWInfo['Warclaw Gate Damage']['repeated'] * 100000
                endWvWInfo['Warclaw Gate Damage']['current'] += endWvWInfo['Warclaw Gate Damage']['repeated'] * 100000

            # Get the difference between each current value in the WvWInfo Dicts
            wvwDiff = {key: endWvWInfo[key]['current'] - startWvWInfo[key]['current'] for key in startWvWInfo.keys()}
            print(wvwDiff['Deaths'])
            # Calculate time difference
            timeElapsed = endTime - startTime
            hours, remainder = divmod(timeElapsed.seconds, 3600)
            minutes, seconds = divmod(remainder, 60)
            playTimeStr = "{}h {}m {}s".format(hours, minutes, seconds)

            embed_time_format = "%X UTC"

            user = ctx.message.author
            if embed_perms(ctx.message):

                desc = """
                    You started playing at **{}** and stopped at **{}** for a total playtime of **{}**\n
                    \n
                    `Note: Deaths are tracked globally`
                """.format(startTime.strftime(embed_time_format), endTime.strftime(embed_time_format), playTimeStr)
                # Default to the numerator if denominator is 0 for Kill Death Ratio
                wvw_kdr = wvwDiff['WvW Kills'] / wvwDiff['Deaths'] if wvwDiff['Deaths'] else wvwDiff['WvW Kills']
                em = discord.Embed(title="WvW Session Stats", description=desc, timestamp=ctx.message.created_at, color=0xFF0000)
                # Playtime information
                # KDR
                em.add_field(name='WvW Kills :crossed_swords:', value=wvwDiff['WvW Kills'], inline=True)
                em.add_field(name='Deaths :skull:', value=wvwDiff['Deaths'], inline=True)
                em.add_field(name='KDR', value=wvw_kdr, inline=True)
                # Zero Width space unicode character
                # em.add_field(name='\u200b', value='\u200b', inline=False)
                # WvW Information
                em.add_field(name='Camps Flipped :circus_tent:', value=wvwDiff['WvW Camps'], inline=True)
                em.add_field(name='Towers Seized :synagogue:', value=wvwDiff['WvW Towers'], inline=True)
                em.add_field(name='Keeps Captured :european_castle:', value=wvwDiff['WvW Keeps'], inline=True)
                em.add_field(name='Castles Liberated :japanese_castle:', value=wvwDiff['WvW Castles'], inline=True)
                em.add_field(name='Yaks Slapped :meat_on_bone:', value=wvwDiff['WvW Yak Kills'], inline=True)
                em.add_field(name='Yaks Escorted :ram:', value=wvwDiff['Yak Escort'], inline=True)
                em.add_field(name='Supply Spent Repairing :tools:', value=wvwDiff['WvW Repairs'], inline=True)
                em.add_field(name='Warclaw Maul Kills :lion:', value=wvwDiff['Warclaw Kills'], inline=True)
                em.add_field(name='Warclaw Gate Damage :shinto_shrine:', value=wvwDiff['Warclaw Gate Damage'], inline=True)
                em.set_author(name=user.display_name, icon_url=user.avatar_url)
                await ctx.send(embed=em)
예제 #36
0
    async def anime(self, ctx, *, msg: str = None):
        """Search the anime database. Ex: [p]mal anime Steins;Gate"""
        if msg:
            fetch = await ctx.send(self.bot.bot_prefix + 'Searching...')
            if msg.startswith('[link]'):
                msg = msg[6:]
                link = True
            else:
                link = False

            found, result = await self.google_results('anime', msg)

            if found:
                anime_id = re.findall('/anime/(.*)/', result)
                try:
                    results = await self.t_client.get_anime(int(anime_id[0]))
                except IndexError:
                    return await ctx.send(self.bot.bot_prefix + 'No results.')
                finally:
                    gc.collect()

            else:
                await ctx.send(self.bot.bot_prefix + 'No results.')
                await fetch.delete()
                return await ctx.message.delete()

            if not embed_perms(ctx.message) or link is True:
                await ctx.send(self.bot.bot_prefix +
                               'https://myanimelist.net/anime/%s' % results.id)
                await fetch.delete()
                return await ctx.message.delete()

            # Formatting embed
            selection = results
            synopsis = BeautifulSoup(selection.synopsis, 'html.parser')

            em = discord.Embed(description='{}'.format(
                'https://myanimelist.net/anime/%s' % selection.id),
                               colour=0x0066CC)

            try:
                english = selection.english
                if english:
                    em.add_field(name='English Title',
                                 value=english,
                                 inline=False)
            except:
                pass
            em.add_field(name='Type', value=selection.type)
            episodes = 'Unknown' if selection.episodes == '0' else selection.episodes
            em.add_field(name='Episodes', value=episodes)
            score = '?' if selection.score == 0 else str(
                selection.score) + '/10'
            em.add_field(name='Score', value=score)
            em.add_field(name='Status', value=selection.status)
            try:
                synop = synopsis.get_text()[:400].split('.')
                text = ''
                for i in range(0, len(synop) - 1):
                    text += synop[i] + '.'
            except:
                text = synopsis.get_text()
            em.add_field(name='Synopsis',
                         value=text +
                         ' [Read more »](https://myanimelist.net/anime/%s)' %
                         selection.id)

            air_time = selection.air_start + " - " + selection.air_end
            em.add_field(name='Airing Time:', value=air_time)
            em.set_thumbnail(url=selection.image)
            em.set_author(
                name=selection.title,
                icon_url=
                'https://myanimelist.cdn-dena.com/img/sp/icon/apple-touch-icon-256.png'
            )
            em.set_footer(text='MyAnimeList Anime Search')

            await ctx.send(embed=em)
            await fetch.delete()
            await ctx.message.delete()
        else:
            await ctx.send(self.bot.bot_prefix +
                           'Specify an anime to search for.')
예제 #37
0
    async def serverinfo(self, ctx, *, msg=""):
        """Various info about the server. [p]help server for more info."""
        if ctx.invoked_subcommand is None:
            if msg:
                server = None
                try:
                    float(msg)
                    server = self.bot.get_guild(int(msg))
                    if not server:
                        return await ctx.send(
                                              self.bot.bot_prefix + 'Server not found.')
                except:
                    for i in self.bot.guilds:
                        if i.name.lower() == msg.lower():
                            server = i
                            break
                    if not server:
                        return await ctx.send(self.bot.bot_prefix + 'Could not find server. Note: You must be a member of the server you are trying to search.')
            else:
                server = ctx.message.guild

            online = 0
            for i in server.members:
                if str(i.status) == 'online' or str(i.status) == 'idle' or str(i.status) == 'dnd':
                    online += 1
            all_users = []
            for user in server.members:
                all_users.append('{}#{}'.format(user.name, user.discriminator))
            all_users.sort()
            all = '\n'.join(all_users)

            channel_count = len([x for x in server.channels if type(x) == discord.channel.TextChannel])

            role_count = len(server.roles)
            emoji_count = len(server.emojis)

            if embed_perms(ctx.message):
                em = discord.Embed(color=0xea7938)
                em.add_field(name='Name', value=server.name)
                em.add_field(name='Owner', value=server.owner, inline=False)
                em.add_field(name='Members', value=server.member_count)
                em.add_field(name='Currently Online', value=online)
                em.add_field(name='Text Channels', value=str(channel_count))
                em.add_field(name='Region', value=server.region)
                em.add_field(name='Verification Level', value=str(server.verification_level))
                em.add_field(name='Highest role', value=server.role_hierarchy[0])
                em.add_field(name='Number of roles', value=str(role_count))
                em.add_field(name='Number of emotes', value=str(emoji_count))
                url = await hastebin(str(all), self.bot.session)
                hastebin_of_users = '[List of all {} users in this server]({})'.format(server.member_count, url)
                em.add_field(name='Users', value=hastebin_of_users)
                em.add_field(name='Created At', value=server.created_at.__format__('%A, %d. %B %Y @ %H:%M:%S'))
                em.set_thumbnail(url=server.icon_url)
                em.set_author(name='Server Info', icon_url='https://i.imgur.com/RHagTDg.png')
                em.set_footer(text='Server ID: %s' % server.id)
                await ctx.send(embed=em)
            else:
                msg = '**Server Info:** ```Name: %s\nOwner: %s\nMembers: %s\nCurrently Online: %s\nRegion: %s\nVerification Level: %s\nHighest Role: %s\nCreated At: %s\nServer avatar: : %s```' % (
                    server.name, server.owner, server.member_count, online, server.region, str(server.verification_level), server.role_hierarchy[0], server.created_at.__format__('%A, %d. %B %Y @ %H:%M:%S'), server.icon_url)
                await ctx.send(self.bot.bot_prefix + msg)
            await ctx.message.delete()
예제 #38
0
    async def anime(self, ctx, *, msg: str = None):
        """Search the anime database. Ex: [p]mal anime Steins;Gate"""
        if msg:
            fetch = await ctx.send(self.bot.bot_prefix + 'Searching...')
            if msg.startswith('[link]'):
                msg = msg[6:]
                link = True
            else:
                link = False

            found, result = await self.google_results('anime', msg)

            if found:
                anime_id = re.findall('/anime/(.*)/', result)
                try:
                    results = await self.t_client.get_anime(int(anime_id[0]))
                except IndexError:
                    return await ctx.send(self.bot.bot_prefix + 'No results.')
                finally:
                    gc.collect()

            else:
                await ctx.send(self.bot.bot_prefix + 'No results.')
                await fetch.delete()
                return await ctx.message.delete()

            if not embed_perms(ctx.message) or link is True:
                await ctx.send(self.bot.bot_prefix + 'https://myanimelist.net/anime/%s' % results.id)
                await fetch.delete()
                return await ctx.message.delete()

            # Formatting embed
            selection = results
            synopsis = BeautifulSoup(selection.synopsis, 'html.parser')

            em = discord.Embed(description='{}'.format('https://myanimelist.net/anime/%s' % selection.id),
                               colour=0x0066CC)

            try:
                english = selection.english
                if english:
                    em.add_field(name='English Title', value=english, inline=False)
            except:
                pass
            em.add_field(name='Type', value=selection.type)
            episodes = 'Unknown' if selection.episodes == '0' else selection.episodes
            em.add_field(name='Episodes', value=episodes)
            score = '?' if selection.score == 0 else str(selection.score) + '/10'
            em.add_field(name='Score', value=score)
            em.add_field(name='Status', value=selection.status)
            try:
                synop = synopsis.get_text()[:400].split('.')
                text = ''
                for i in range(0, len(synop)-1):
                    text += synop[i] + '.'
            except:
                text = synopsis.get_text()
            em.add_field(name='Synopsis',
                         value=text + ' [Read more »](https://myanimelist.net/anime/%s)' % selection.id)

            air_time = selection.air_start + " - " + selection.air_end
            em.add_field(name='Airing Time:', value=air_time)
            em.set_thumbnail(url=selection.image)
            em.set_author(name=selection.title,
                          icon_url='https://myanimelist.cdn-dena.com/img/sp/icon/apple-touch-icon-256.png')
            em.set_footer(text='MyAnimeList Anime Search')

            await ctx.send(embed=em)
            await fetch.delete()
            await ctx.message.delete()
        else:
            await ctx.send(self.bot.bot_prefix + 'Specify an anime to search for.')
예제 #39
0
    async def emoji(self, ctx, *, msg):
        """
        Embed or copy a custom emoji (from any server).
        Usage:
        1) >emoji :smug: [Will display the smug emoji as an image]
        2) >emoji copy :smug: [Will add the emoji as a custom emote for the server]
        """
        copy_emote_bool = False
        if "copy " in msg:
            msg = msg.split("copy ")[1]
            copy_emote_bool = True
        if msg.startswith('s '):
            msg = msg[2:]
            get_server = True
        else:
            get_server = False
        msg = msg.strip(':')
        if msg.startswith('<'):
            msg = msg[2:].split(':', 1)[0].strip()
        url = emoji = server = None
        exact_match = False
        for server in self.bot.servers:
            for emoji in server.emojis:
                if msg.strip().lower() in str(emoji):
                    url = emoji.url
                    emote_name = emoji.name
                if msg.strip() == str(emoji).split(':')[1]:
                    url = emoji.url
                    emote_name = emoji.name
                    exact_match = True
                    break
            if exact_match:
                break
        response = requests.get(emoji.url, stream=True)
        name = emoji.url.split('/')[-1]
        with open(name, 'wb') as img:

            for block in response.iter_content(1024):
                if not block:
                    break

                img.write(block)

        if attach_perms(ctx.message) and url:
            if get_server:
                await self.bot.send_message(
                    ctx.message.channel,
                    '**ID:** {}\n**Server:** {}'.format(emoji.id, server.name))
            with open(name, 'rb') as fp:
                if copy_emote_bool:
                    e = fp.read()
                else:
                    await self.bot.send_file(ctx.message.channel, fp)
            if copy_emote_bool:
                try:
                    await self.bot.create_custom_emoji(ctx.message.server,
                                                       name=emote_name,
                                                       image=e)
                    embed = discord.Embed(title="Added new emote",
                                          color=discord.Color.blue())
                    embed.description = "New emote added: " + emote_name
                    await self.bot.say("", embed=embed)
                except:
                    await self.bot.say("Not enough permissions to do this")
            os.remove(name)
        elif not embed_perms(ctx.message) and url:
            await self.bot.send_message(ctx.message.channel, url)
        else:
            await self.bot.send_message(
                ctx.message.channel,
                self.bot.bot_prefix + 'Could not find emoji.')

        return await self.bot.delete_message(ctx.message)
예제 #40
0
    async def serverinfo(self, ctx, *, msg=""):
        """Various info about the server. [p]help server for more info."""
        if ctx.invoked_subcommand is None:
            if msg:
                server = None
                try:
                    float(msg)
                    server = self.bot.get_guild(int(msg))
                    if not server:
                        return await ctx.send(
                                              self.bot.bot_prefix + 'Server not found.')
                except:
                    for i in self.bot.guilds:
                        if i.name.lower() == msg.lower():
                            server = i
                            break
                    if not server:
                        return await ctx.send(self.bot.bot_prefix + 'Could not find server. Note: You must be a member of the server you are trying to search.')
            else:
                server = ctx.message.guild

            online = 0
            for i in server.members:
                if str(i.status) == 'online' or str(i.status) == 'idle' or str(i.status) == 'dnd':
                    online += 1
            all_users = []
            for user in server.members:
                all_users.append('{}#{}'.format(user.name, user.discriminator))
            all_users.sort()
            all = '\n'.join(all_users)

            channel_count = len([x for x in server.channels if type(x) == discord.channel.TextChannel])

            role_count = len(server.roles)
            emoji_count = len(server.emojis)

            if embed_perms(ctx.message):
                em = discord.Embed(color=0xea7938)
                em.add_field(name='Name', value=server.name)
                em.add_field(name='Owner', value=server.owner, inline=False)
                em.add_field(name='Members', value=server.member_count)
                em.add_field(name='Currently Online', value=online)
                em.add_field(name='Text Channels', value=str(channel_count))
                em.add_field(name='Region', value=server.region)
                em.add_field(name='Verification Level', value=str(server.verification_level))
                em.add_field(name='Highest role', value=server.role_hierarchy[0])
                em.add_field(name='Number of roles', value=str(role_count))
                em.add_field(name='Number of emotes', value=str(emoji_count))
                url = await hastebin(str(all), self.bot.session)
                hastebin_of_users = '[List of all {} users in this server]({})'.format(server.member_count, url)
                em.add_field(name='Users', value=hastebin_of_users)
                em.add_field(name='Created At', value=server.created_at.__format__('%A, %d. %B %Y @ %H:%M:%S'))
                em.set_thumbnail(url=server.icon_url)
                em.set_author(name='Server Info', icon_url='https://i.imgur.com/RHagTDg.png')
                em.set_footer(text='Server ID: %s' % server.id)
                await ctx.send(embed=em)
            else:
                msg = '**Server Info:** ```Name: %s\nOwner: %s\nMembers: %s\nCurrently Online: %s\nRegion: %s\nVerification Level: %s\nHighest Role: %s\nCreated At: %s\nServer avatar: : %s```' % (
                    server.name, server.owner, server.member_count, online, server.region, str(server.verification_level), server.role_hierarchy[0], server.created_at.__format__('%A, %d. %B %Y @ %H:%M:%S'), server.icon_url)
                await ctx.send(self.bot.bot_prefix + msg)
            await ctx.message.delete()
예제 #41
0
    async def embed(self, ctx, *, msg: str = None):
        """Embed given text. Ex: Do [p]embed for more help

        Example: [p]embed title=test this | description=some words | color=3AB35E | field=name=test value=test

        You do NOT need to specify every property, only the ones you want.

        **All properties and the syntax:**
        - title=<words>
        - description=<words>
        - color=<hex_value>
        - image=<url_to_image> (must be https)
        - thumbnail=<url_to_image>
        - author=<words> **OR** author=name=<words> icon=<url_to_image>
        - footer=<words> **OR** footer=name=<words> icon=<url_to_image>
        - field=name=<words> value=<words> (you can add as many fields as you want)
        - ptext=<words>

        NOTE: After the command is sent, the bot will delete your message and replace it with the embed. Make sure you have it saved or else you'll have to type it all again if the embed isn't how you want it.
        
        PS: Hyperlink text like so:
        \[text](https://www.whateverlink.com)

        PPS: Force a field to go to the next line with the added parameter inline=False"""
        if msg:
            if embed_perms(ctx.message):
                ptext = title = description = image = thumbnail = color = footer = author = None
                timestamp = discord.Embed.Empty
                embed_values = msg.split('|')
                for i in embed_values:
                    with open('settings/optional_config.json', 'r+') as fp:
                        opt = json.load(fp)
                        if opt['embed_color'] != "":
                            color = opt['embed_color']
                    if i.strip().lower().startswith('ptext='):
                        ptext = i.strip()[6:].strip()
                    elif i.strip().lower().startswith('title='):
                        title = i.strip()[6:].strip()
                    elif i.strip().lower().startswith('description='):
                        description = i.strip()[12:].strip()
                    elif i.strip().lower().startswith('desc='):
                        description = i.strip()[5:].strip()
                    elif i.strip().lower().startswith('image='):
                        image = i.strip()[6:].strip()
                    elif i.strip().lower().startswith('thumbnail='):
                        thumbnail = i.strip()[10:].strip()
                    elif i.strip().lower().startswith('colour='):
                        color = i.strip()[7:].strip()
                    elif i.strip().lower().startswith('color='):
                        color = i.strip()[6:].strip()
                    elif i.strip().lower().startswith('footer='):
                        footer = i.strip()[7:].strip()
                    elif i.strip().lower().startswith('author='):
                        author = i.strip()[7:].strip()
                    elif i.strip().lower().startswith('timestamp'):
                        timestamp = ctx.message.created_at
                    else:
                        if description is None and not i.strip().lower().startswith('field='):
                            description = i.strip()

                if color:
                    if color.startswith('#'):
                        color = color[1:]
                    if not color.startswith('0x'):
                        color = '0x' + color

                if ptext is title is description is image is thumbnail is color is footer is author is None and 'field=' not in msg:
                    await ctx.message.delete()
                    return await ctx.send(content=None,
                                                       embed=discord.Embed(description=msg))

                if color:
                    em = discord.Embed(timestamp=timestamp, title=title, description=description, color=int(color, 16))
                else:
                    em = discord.Embed(timestamp=timestamp, title=title, description=description)
                for i in embed_values:
                    if i.strip().lower().startswith('field='):
                        field_inline = True
                        field = i.strip().lstrip('field=')
                        field_name, field_value = field.split('value=')
                        if 'inline=' in field_value:
                            field_value, field_inline = field_value.split('inline=')
                            if 'false' in field_inline.lower() or 'no' in field_inline.lower():
                                field_inline = False
                        field_name = field_name.strip().lstrip('name=')
                        em.add_field(name=field_name, value=field_value.strip(), inline=field_inline)
                if author:
                    if 'icon=' in author:
                        text, icon = author.split('icon=')
                        if 'url=' in icon:
                            em.set_author(name=text.strip()[5:], icon_url=icon.split('url=')[0].strip(), url=icon.split('url=')[1].strip())
                        else:
                            em.set_author(name=text.strip()[5:], icon_url=icon)
                    else:
                        if 'url=' in author:
                            em.set_author(name=author.split('url=')[0].strip()[5:], url=author.split('url=')[1].strip())
                        else:
                            em.set_author(name=author)

                if image:
                    em.set_image(url=image)
                if thumbnail:
                    em.set_thumbnail(url=thumbnail)
                if footer:
                    if 'icon=' in footer:
                        text, icon = footer.split('icon=')
                        em.set_footer(text=text.strip()[5:], icon_url=icon)
                    else:
                        em.set_footer(text=footer)
                await ctx.send(content=ptext, embed=em)
            else:
                await ctx.send(self.bot.bot_prefix + 'No embed permissions in this channel.')
        else:
            msg = '```How to use the >embed command:\nExample: >embed title=test this | description=some words | color=3AB35E | field=name=test value=test\n\nYou do NOT need to specify every property, only the ones you want.' \
                  '\nAll properties and the syntax (put your custom stuff in place of the <> stuff):\ntitle=<words>\ndescription=<words>\ncolor=<hex_value>\nimage=<url_to_image> (must be https)\nthumbnail=<url_to_image>\nauthor=<words> **OR** author=name=<words> icon=<url_to_image>\nfooter=<words> ' \
                  '**OR** footer=name=<words> icon=<url_to_image>\nfield=name=<words> value=<words> (you can add as many fields as you want)\nptext=<words>\n\nNOTE: After the command is sent, the bot will delete your message and replace it with ' \
                  'the embed. Make sure you have it saved or else you\'ll have to type it all again if the embed isn\'t how you want it.\nPS: Hyperlink text like so: [text](https://www.whateverlink.com)\nPPS: Force a field to go to the next line with the added parameter inline=False```'
            await ctx.send(self.bot.bot_prefix + msg)
        try:
            await ctx.message.delete()
        except:
            pass
예제 #42
0
    async def server(self, ctx):
        """Various info about the server. >help server for more info."""
        if ctx.invoked_subcommand is None:
            pre = cmd_prefix_len()
            if ctx.message.content[6 + pre:].strip():
                server = None
                try:
                    float(ctx.message.content[6 + pre:].strip())
                    server = self.bot.get_server(ctx.message.content[6 + pre:].strip())
                    if not server:
                        return await self.bot.send_message(ctx.message.channel,
                                                           self.bot.bot_prefix + 'Server not found.')
                except:
                    for i in self.bot.servers:
                        if i.name.lower() == ctx.message.content[6 + pre:].lower().strip():
                            server = i
                            break
                    if not server:
                        return await self.bot.send_message(ctx.message.channel, self.bot.bot_prefix + 'Could not find server. Note: You must be a member of the server you are trying to search.')
            else:
                server = ctx.message.server

            online = 0
            for i in server.members:
                if str(i.status) == 'online' or str(i.status) == 'idle' or str(i.status) == 'dnd':
                    online += 1
            all_users = []
            for user in server.members:
                all_users.append('{}#{}'.format(user.name, user.discriminator))
            all_users.sort()
            all = '\n'.join(all_users)

            channel_count = 0
            for channel in server.channels:
                if channel.type == discord.ChannelType.text:
                    channel_count += 1

            role_count = len(server.roles)
            emoji_count = len(server.emojis)

            if embed_perms(ctx.message):
                em = discord.Embed(color=0xea7938)
                em.add_field(name='Name', value=server.name)
                em.add_field(name='Owner', value=server.owner, inline=False)
                em.add_field(name='Members', value=server.member_count)
                em.add_field(name='Currently Online', value=online)
                em.add_field(name='Text Channels', value=str(channel_count))
                em.add_field(name='Region', value=server.region)
                em.add_field(name='Verification Level', value=str(server.verification_level))
                em.add_field(name='Highest role', value=server.role_hierarchy[0])
                em.add_field(name='Number of Roles', value=str(role_count))
                em.add_field(name='Number of Emotes', value=str(emoji_count))
                url = PythonGists.Gist(description='All Users in: %s' % server.name, content=str(all), name='server.txt')
                gist_of_users = '[List of all {} users in this server]({})'.format(server.member_count, url)
                em.add_field(name='Users', value=gist_of_users)
                em.add_field(name='Created At', value=server.created_at.__format__('%A, %d. %B %Y @ %H:%M:%S'))
                em.set_thumbnail(url=server.icon_url)
                em.set_author(name='Server Info', icon_url='https://i.imgur.com/RHagTDg.png')
                em.set_footer(text='Server ID: %s' % server.id)
                await self.bot.send_message(ctx.message.channel, embed=em)
            else:
                msg = '**Server Info:** ```Name: %s\nOwner: %s\nMembers: %s\nCurrently Online: %s\nRegion: %s\nVerification Level: %s\nHighest Role: %s\nDefault Channel: %s\nCreated At: %s\nServer avatar: : %s```' % (
                server.name, server.owner, server.member_count, online, server.region, str(server.verification_level), server.role_hierarchy[0], server.default_channel, server.created_at.__format__('%A, %d. %B %Y @ %H:%M:%S'), server.icon_url)
                await self.bot.send_message(ctx.message.channel, self.bot.bot_prefix + msg)
            await self.bot.delete_message(ctx.message)
예제 #43
0
    async def manga(self, ctx, *, msg: str = None):
        """Search the manga database. Ex: >mal manga Boku no Hero Academia"""
        if msg:
            fetch = await self.bot.send_message(
                ctx.message.channel, self.bot.bot_prefix + 'Searching...')
            if msg.startswith('[link]'):
                msg = msg[6:]
                link = True
            else:
                link = False

            found, result = await self.google_results('manga', msg)

            if found:
                manga_id = re.findall('/manga/(.*)/', result)
                try:
                    results = await self.t_client.get_manga(int(manga_id[0]))
                except IndexError:
                    return await self.bot.send_message(
                        ctx.message.channel,
                        self.bot.bot_prefix + 'No results.')
                gc.collect()

            else:
                await self.bot.send_message(
                    ctx.message.channel, self.bot.bot_prefix + 'No results.')
                await self.bot.delete_message(fetch)
                return await self.bot.delete_message(ctx.message)

            if not embed_perms(ctx.message) or link is True:
                await self.bot.send_message(
                    ctx.message.channel, self.bot.bot_prefix +
                    'https://myanimelist.net/manga/%s' % results.id)
                await self.bot.delete_message(fetch)
                return await self.bot.delete_message(ctx.message)

            # Formatting embed
            selection = results
            synopsis = BeautifulSoup(selection.synopsis, 'html.parser')

            em = discord.Embed(description='{}'.format(
                'https://myanimelist.net/manga/%s' % selection.id),
                               colour=0x0066CC)

            try:
                english = selection.english
                if english:
                    em.add_field(name='English Title',
                                 value=english,
                                 inline=False)
            except:
                pass
            em.add_field(name='Type', value=selection.type)
            chapters = 'Unknown' if selection.chapters == '0' else selection.chapters
            em.add_field(name='Chapters', value=chapters)
            score = '?' if selection.score[0] == 0 else str(
                selection.score[0]) + '/10'
            em.add_field(name='Score', value=score)
            em.add_field(name='Status', value=selection.status)
            try:
                synop = synopsis.get_text()[:400].split('.')
                text = ''
                for i in range(0, len(synop) - 1):
                    text += synop[i] + '.'
            except:
                text = synopsis.get_text()
            em.add_field(name='Synopsis',
                         value=text +
                         ' [Read more »](https://myanimelist.net/manga/%s)' %
                         selection.id)

            em.add_field(name='Airing Time:', value=selection.publish_time)
            em.set_thumbnail(url=selection.image)
            em.set_author(
                name=selection.title,
                icon_url=
                'https://myanimelist.cdn-dena.com/img/sp/icon/apple-touch-icon-256.png'
            )
            em.set_footer(text='MyAnimeList Manga Search')

            await self.bot.send_message(ctx.message.channel, embed=em)
            await self.bot.delete_message(fetch)
            await self.bot.delete_message(ctx.message)
        else:
            await self.bot.send_message(ctx.message.channel,
                                        self.bot.bot_prefix + 'No results')
예제 #44
0
 async def stats(self, ctx):
     """Bot stats."""
     uptime = (datetime.datetime.now() - self.bot.uptime)
     hours, rem = divmod(int(uptime.total_seconds()), 3600)
     minutes, seconds = divmod(rem, 60)
     days, hours = divmod(hours, 24)
     if days:
         time = '%s days, %s hours, %s minutes, and %s seconds' % (
             days, hours, minutes, seconds)
     else:
         time = '%s hours, %s minutes, and %s seconds' % (hours, minutes,
                                                          seconds)
     game = self.bot.game
     if not game:
         game = 'None'
     channel_count = 0
     for guild in self.bot.guilds:
         channel_count += len(guild.channels)
     if not self.bot.command_count:
         most_used_cmd = 'Not enough info'
     else:
         cmd_name = max(self.bot.command_count,
                        key=self.bot.command_count.get)
         total_usage = self.bot.command_count[str(cmd_name)]
         plural = '' if total_usage == 1 else 's'
         most_used_cmd = '{} - {} use{}'.format(cmd_name, total_usage,
                                                plural)
     if embed_perms(ctx.message):
         em = discord.Embed(title='Bot Stats', color=0x32441c)
         em.set_thumbnail(url='https://i.imgur.com/TxsPBMI.gif')
         em.add_field(name=u'\U0001F553 Uptime', value=time, inline=False)
         em.add_field(name=u'\u2328 Most Used Cmd',
                      value=most_used_cmd,
                      inline=False)
         em.add_field(name=u'\U0001F4E4 Msgs sent',
                      value=str(self.bot.icount))
         em.add_field(name=u'\U0001F4E5 Msgs received',
                      value=str(self.bot.message_count))
         em.add_field(name=u'\u2757 Mentions',
                      value=str(self.bot.mention_count))
         em.add_field(name=u'\u2694 Servers',
                      value=str(len(self.bot.guilds)))
         em.add_field(name=u'\ud83d\udcd1 Channels',
                      value=str(channel_count))
         em.add_field(name=u'\u270F Keywords logged',
                      value=str(self.bot.keyword_log))
         g = u'\U0001F3AE Game'
         if '=' in game: g = '\ud83c\udfa5 Stream'
         em.add_field(name=g, value=game)
         try:
             mem_usage = '{:.2f} MiB'.format(
                 __import__('psutil').Process().memory_full_info().uss /
                 1024**2)
         except AttributeError:
             # OS doesn't support retrieval of USS (probably BSD or Solaris)
             mem_usage = '{:.2f} MiB'.format(
                 __import__('psutil').Process().memory_full_info().rss /
                 1024**2)
         em.add_field(name=u'\U0001F4BE Memory usage:', value=mem_usage)
         try:
             g = git.cmd.Git(working_dir=os.getcwd())
             branch = g.execute(
                 ["git", "rev-parse", "--abbrev-ref", "HEAD"])
             g.execute(["git", "fetch", "origin", branch])
             version = g.execute([
                 "git", "rev-list", "--right-only", "--count",
                 "{}...origin/{}".format(branch, branch)
             ])
             if branch == "master":
                 branch_note = "."
             else:
                 branch_note = " (`" + branch + "` branch)."
             if version == '0':
                 status = 'Up to date%s' % branch_note
             else:
                 latest = g.execute([
                     "git", "log", "--pretty=oneline", "--abbrev-commit",
                     "--stat", "--pretty",
                     "-%s" % version,
                     "origin/%s" % branch
                 ])
                 haste_latest = await hastebin(latest, self.bot.session)
                 if version == '1':
                     status = 'Behind by 1 release%s [Latest update.](%s)' % (
                         branch_note, haste_latest)
                 else:
                     status = '%s releases behind%s [Latest updates.](%s)' % (
                         version, branch_note, haste_latest)
             em.add_field(name=u'\U0001f4bb Update status:', value=status)
         except:
             pass
         await ctx.send(content=None, embed=em)
     else:
         msg = '**Bot Stats:** ```Uptime: %s\nMessages Sent: %s\nMessages Received: %s\nMentions: %s\nguilds: %s\nKeywords logged: %s\nGame: %s```' % (
             time, str(self.bot.icount), str(self.bot.message_count),
             str(self.bot.mention_count), str(len(
                 self.bot.guilds)), str(self.bot.keyword_log), game)
         await ctx.send(self.bot.bot_prefix + msg)
     await ctx.message.delete()