Exemple #1
0
    async def time(self, ctx, *, offset: str = None):
        """Melihat local TimeZone milik mu atau member."""
        timezone = None
        if offset == None:
            member = ctx.message.author
        else:
            # Try to get a user first
            member = DisplayName.memberForName(offset, ctx.message.guild)

        if member:
            # We got one
            # Check for timezone first
            offset = self.settings.getGlobalUserStat(member, "TimeZone")
            memberName = DisplayName.memberForName(member, ctx.guild)
            if offset == None:
                offset = self.settings.getGlobalUserStat(member, "UTCOffset")

        if offset == None:
            msg = "*{}* belum mengatur local TimeZone.\n".format(
                memberName.mention)
            msg += "Cobalah merekomendasikannya untuk mengetik\n*`{}help settz`*\n\n".format(
                ctx.prefix)
            msg += "TimeZone *{}* saat ini ".format(memberName.mention)
            msg += "*{}* UTC.".format(
                UserTime.getClockForTime(
                    datetime.datetime.utcnow().strftime("%I:%M %p")))
            em = discord.Embed(color=0XFF8C00, description=msg)
            em.set_footer(
                text="Saat mengetik command, tanda [] tidak usah digunakan\n{}"
                .format(ctx.author),
                icon_url="{}".format(ctx.author.avatar_url))
            await ctx.channel.send(embed=em)
            return

        # At this point - we need to determine if we have an offset - or possibly a timezone passed
        t = self.getTimeFromTZ(offset)
        if t == None:
            # We did not get an offset
            t = self.getTimeFromOffset(offset)
            if t == None:
                msg = "┐( ̄ヘ ̄;)┌\nAku tidak dapat menemukan TimeZone yang kamu cari."
                em = discord.Embed(color=0XFF8C00, description=msg)
                em.set_footer(text="{}#{}".format(ctx.author),
                              icon_url="{}".format(ctx.author.avatar_url))
                await ctx.channel.send(embed=em)
                return
        t["time"] = UserTime.getClockForTime(t["time"])
        if member:
            msg = "local TimeZone {}\nBerada di *{}* saat ini jam *{}*".format(
                memberName.mention, t["zone"], t["time"])
        else:
            msg = "local TimeZone *{}* saat ini jam *{}*".format(
                t["zone"], t["time"])

        # Say message
        em = discord.Embed(color=0XFF8C00, description=msg)
        em.set_footer(text="{}".format(ctx.author),
                      icon_url="{}".format(ctx.author.avatar_url))
        await ctx.channel.send(embed=em)
Exemple #2
0
 async def gamelookup(self, ctx, *,game: str):
     igdb1 = igdb(self.key)
     result = igdb1.games({
         'search': "{}".format(game),
         'fields': ['name','game',
             'first_release_date','summary',
             'cover','platforms','url']
         })
     result = result.body
     GameInfo=result[0]
     cover = GameInfo['cover']
     platformconvert = GameInfo['platforms']
     gameurl = GameInfo['url']
     platformconvert.sort()
     plat = "\n".join([Platform_Lookup[x] for x in platformconvert])
     gt_dict = UserTime.getUserTime(
                     ctx.author,
                     self.settings,
                     datetime.fromtimestamp(time.mktime(time.localtime(GameInfo["first_release_date"]/1000.)))
                 )
     game_time = "{} {}".format(gt_dict['time'], gt_dict['zone'])
     await Message.Embed(
         title=GameInfo["name"],
         thumbnail="http:{}".format(cover["url"]),
         url=gameurl,
         color=ctx.author,
         fields=[
             {"name":"Summary", "value":GameInfo['summary'] if len(GameInfo['summary']) <= 1024 else GameInfo['summary'][:1021]+'...'},
             {"name":"Release Date", "value":game_time},
             {"name":"Platforms", "value":plat}
         ]
     ).send(ctx)
Exemple #3
0
    async def recentservers(self, ctx, number: int = 10):
        """Lists the most recent users to join - default is 10, max is 25."""
        # Check if we're suppressing @here and @everyone mentions
        if self.settings.getServerStat(ctx.message.guild, "SuppressMentions"):
            suppress = True
        else:
            suppress = False

        if number > 25:
            number = 25
        if number < 1:
            await ctx.channel.send(
                'Oookay - look!  No servers!  Just like you wanted!')
            return

        joinedList = []
        for guild in self.bot.guilds:
            botmember = DisplayName.memberForID(self.bot.user.id, guild)
            joinedList.append({
                'Name': guild.name,
                'Joined': botmember.joined_at,
                'Members': len(guild.members)
            })

        # sort the servers by join date
        joinedList = sorted(joinedList,
                            key=lambda x: x['Joined'],
                            reverse=True)

        i = 1
        msg = ''
        for member in joinedList:
            if i > number:
                break
            # Get localized user time
            local_time = UserTime.getUserTime(ctx.author, self.settings,
                                              member['Joined'])
            time_str = "{} {}".format(local_time['time'], local_time['zone'])
            if member['Members'] == 1:
                msg += '{}. *{}* - *{}* - *(1 member)*\n'.format(
                    i, member['Name'], time_str)
            else:
                msg += '{}. *{}* - *{}* - *({} members)*\n'.format(
                    i, member['Name'], time_str, member['Members'])
            i += 1

        if number < len(joinedList):
            msg = '__**Last {} of {} Servers I Joined:**__\n\n'.format(
                number, len(joinedList)) + msg
        else:
            msg = '__**Last {} Servers I Joined:**__\n\n'.format(
                len(joinedList)) + msg

        # Check for suppress
        if suppress:
            msg = Nullify.clean(msg)
        await ctx.channel.send(msg)
Exemple #4
0
    async def time(self, ctx, *, offset: str = None):
        """Get UTC time +- an offset."""
        timezone = None
        if offset == None:
            member = ctx.message.author
        else:
            # Try to get a user first
            member = DisplayName.memberForName(offset, ctx.message.guild)

        if member:
            # We got one
            # Check for timezone first
            offset = self.settings.getGlobalUserStat(member, "TimeZone")
            if offset == None:
                offset = self.settings.getGlobalUserStat(member, "UTCOffset")

        if offset == None:
            msg = '*{}* hasn\'t set their TimeZone or offset yet - they can do so with the `{}setoffset [+-offset]` or `{}settz [Region/City]` command.\nThe current UTC time is *{}*.'.format(
                DisplayName.name(member), ctx.prefix, ctx.prefix,
                UserTime.getClockForTime(
                    datetime.datetime.utcnow().strftime("%I:%M %p")))
            await ctx.channel.send(msg)
            return

        # At this point - we need to determine if we have an offset - or possibly a timezone passed
        t = self.getTimeFromTZ(offset)
        if t == None:
            # We did not get an offset
            t = self.getTimeFromOffset(offset)
            if t == None:
                await ctx.channel.send(
                    "I couldn't find that TimeZone or offset!")
                return
        t["time"] = UserTime.getClockForTime(t["time"])
        if member:
            msg = '{}; where *{}* is, it\'s currently *{}*'.format(
                t["zone"], DisplayName.name(member), t["time"])
        else:
            msg = '{} is currently *{}*'.format(t["zone"], t["time"])

        # Say message
        await ctx.channel.send(msg)
Exemple #5
0
    async def firstjoins(self, ctx, number: int = 10):
        """Lists the first users to join - default is 10, max is 25."""
        # Check if we're suppressing @here and @everyone mentions
        if self.settings.getServerStat(ctx.message.guild, "SuppressMentions"):
            suppress = True
        else:
            suppress = False

        if number > 25:
            number = 25
        if number < 1:
            await ctx.channel.send(
                'Oookay - look!  No users!  Just like you wanted!')
            return

        joinedList = []
        for member in ctx.message.guild.members:
            joinedList.append({'ID': member.id, 'Joined': member.joined_at})

        # sort the users by join date
        joinedList = sorted(joinedList, key=lambda x: x['Joined'])

        i = 1
        msg = ''
        for member in joinedList:
            if i > number:
                break
            # Get localized user time
            local_time = UserTime.getUserTime(ctx.author, self.settings,
                                              member['Joined'])
            time_str = "{} {}".format(local_time['time'], local_time['zone'])
            msg += '{}. *{}* - *{}*\n'.format(
                i,
                DisplayName.name(
                    DisplayName.memberForID(member['ID'], ctx.message.guild)),
                time_str)
            i += 1

        if number < len(joinedList):
            msg = '__**First {} of {} Members to Join:**__\n\n'.format(
                number, len(joinedList)) + msg
        else:
            msg = '__**First {} Members to Join:**__\n\n'.format(
                len(joinedList)) + msg

        # Check for suppress
        if suppress:
            msg = Nullify.clean(msg)
        await ctx.channel.send(msg)
Exemple #6
0
    async def joined(self, ctx, *, member: str = None):
        """Says when a member joined."""
        if member is None:
            member = ctx.message.author

        if type(member) is str:
            memberName = member
            member = DisplayName.memberForName(memberName, ctx.message.guild)
            if not member:
                msg = 'I couldn\'t find *{}*...'.format(memberName)
                return await Utils.suppressed(ctx, msg)
        # Get localized user time
        local_time = UserTime.getUserTime(ctx.author, self.settings,
                                          member.joined_at)
        time_str = "{} {}".format(local_time['time'], local_time['zone'])
        await ctx.send('*{}* joined *{}*'.format(DisplayName.name(member),
                                                 time_str))
Exemple #7
0
	async def ruser(self, ctx, *, user_name = None):
		"""Gets some info on the passed username - attempts to use your username if none provided."""
		if user_name == None:
			user_name = ctx.author.nick if ctx.author.nick else ctx.author.name
		# Get the info
		url = "https://www.reddit.com/user/{}/about.json?raw_json=1".format(quote(user_name))
		# Giving a 200 response for some things that aren't found
		try:
			theJSON = await DL.async_json(url, {'User-agent': self.ua})
		except:
			# Assume that we couldn't find that user
			error = "Make sure you're passing a valid reddit username."
			return await Message.EmbedText(title="An error occurred!", description=error, color=ctx.author).send(ctx)
		# Returns:  {"message": "Not Found", "error": 404}  if not found
		if "message" in theJSON:
			error = theJSON.get("error", "An error has occurred.")
			return await Message.EmbedText(title=theJSON["message"], description=str(error), color=ctx.author).send(ctx)
		# Build our embed
		e = { 
			"title" : "/u/" + theJSON["data"]["name"],
			"url" : "https://www.reddit.com/user/" + theJSON["data"]["name"],
			"color" : ctx.author, 
			"fields" : [] }
		created_s = time.gmtime(theJSON["data"]["created_utc"])
		created_dt = datetime(*created_s[:6])
		# Get the actual user time of creation
		created = UserTime.getUserTime(ctx.author, self.settings, created_dt)
		created_string = "{} {}".format(created['time'], created['zone'])
		e["fields"].append({ "name" : "Created", "value" : created_string, "inline" : True })
		e["fields"].append({ "name" : "Link Karma", "value" : "{:,}".format(theJSON["data"]["link_karma"]), "inline" : True })
		e["fields"].append({ "name" : "Comment Karma", "value" : "{:,}".format(theJSON["data"]["comment_karma"]), "inline" : True })
		e["fields"].append({ "name" : "Has Gold", "value" : str(theJSON["data"]["is_gold"]), "inline" : True })
		e["fields"].append({ "name" : "Is Mod", "value" : str(theJSON["data"]["is_mod"]), "inline" : True })
		e["fields"].append({ "name" : "Verified Email", "value" : str(theJSON["data"]["has_verified_email"]), "inline" : True })
		# Send the embed
		await Message.Embed(**e).send(ctx)
Exemple #8
0
    async def botinfo(self, ctx):
        """Mencantumkan statistik umum tentang bot."""
        bot_member = self.bot.user if not ctx.guild else ctx.guild.get_member(
            self.bot.user.id)
        color = bot_member if isinstance(bot_member, discord.Member) else None
        message = await Message.EmbedText(title="Mendapatkan informasi...",
                                          color=0XFF8C00).send(ctx)

        # Get guild count
        guild_count = "{:,}".format(len(self.bot.guilds))

        # Try to do this more efficiently, and faster
        total_members = [x.id for x in self.bot.get_all_members()]
        unique_members = set(total_members)
        if len(total_members) == len(unique_members):
            member_count = "{:,}".format(len(total_members))
        else:
            member_count = "{:,} ({:,} unique)".format(len(total_members),
                                                       len(unique_members))

        # Get commands/cogs count
        cog_amnt = 0
        empty_cog = 0
        for cog in self.bot.cogs:
            visible = []
            for c in self.bot.get_cog(cog).get_commands():
                if c.hidden:
                    continue
                visible.append(c)
            if not len(visible):
                empty_cog += 1
                # Skip empty cogs
                continue
            cog_amnt += 1

        cog_count = "{:,} cog".format(cog_amnt)
        # Easy way to append "s" if needed:
        if not len(self.bot.cogs) == 1:
            cog_count += ""
        if empty_cog:
            cog_count += " [{:,} Cog tanpa command]".format(empty_cog)

        visible = []
        for command in self.bot.commands:
            if command.hidden:
                continue
            visible.append(command)

        command_count = "{:,} Command\n".format(len(visible))

        # Get localized created time
        local_time = UserTime.getUserTime(ctx.author, self.settings,
                                          bot_member.created_at)
        created_at = "{} {}".format(local_time['time'], local_time['zone'])

        # Get localized joined time if in a server
        if isinstance(bot_member, discord.Member):
            local_time = UserTime.getUserTime(ctx.author, self.settings,
                                              bot_member.joined_at)
            joined_at = "{} {}".format(local_time['time'], local_time['zone'])

        # Get the current prefix
        prefix = await self.bot.command_prefix(self.bot, ctx.message)
        prefix = ", ".join(
            [x for x in prefix if not x == "<@!{}> ".format(self.bot.user.id)])

        # Get the owners
        ownerList = self.settings.getGlobalStat('Owner', [])
        owners = "..."
        if len(ownerList):
            userList = []
            for owner in ownerList:
                # Get the owner's name
                user = self.bot.get_user(int(owner))
                if not user:
                    userString = "Unknown User ({})".format(owner)
                else:
                    userString = "{}#{}".format(user.name, user.discriminator)
                userList.append(userString)
            owners = ', '.join(userList)

        # Get bot's avatar url
        avatar = bot_member.avatar_url
        if not len(avatar):
            avatar = bot_member.default_avatar_url

        # Build the embed
        fields = [{
            "name": "Total Member",
            "value": member_count,
            "inline": True
        }, {
            "name": "Total Server",
            "value": guild_count,
            "inline": True
        }, {
            "name": "Total Command",
            "value": command_count + " ({})".format(cog_count),
            "inline": True
        }, {
            "name": "Tanggal Bot Dibuat",
            "value": created_at,
            "inline": True
        }, {
            "name": "Pemilik",
            "value": owners,
            "inline": True
        }, {
            "name": "Prefix",
            "value": prefix,
            "inline": True
        }, {
            "name": "Shard Count",
            "value": self.bot.shard_count,
            "inline": True
        }]
        if isinstance(bot_member, discord.Member):
            fields.append({
                "name": "Joined",
                "value": joined_at,
                "inline": True
            })
            # Get status
            status_text = "<:online:768401856731807784> ONLINE"
            if bot_member.status == discord.Status.offline:
                status_text = "<:offline:768402297406357524> OFFLINE"
            elif bot_member.status == discord.Status.dnd:
                status_text = "<:dnd:768402324405092362>\nDO NOT DISTRUB"
            elif bot_member.status == discord.Status.idle:
                status_text = "<:idle:768402412045729802> IDLE"
            fields.append({
                "name": "Status",
                "value": status_text,
                "inline": True
            })

            if bot_member.activity and bot_member.activity.name:
                play_list = [
                    "Playing", "Streaming", "Listening to", "Watching"
                ]
                try:
                    play_string = play_list[bot_member.activity.type]
                except:
                    play_string = "Playing"
                fields.append({
                    "name": play_string,
                    "value": str(bot_member.activity.name),
                    "inline": True
                })
                if bot_member.activity.type == 1:
                    # Add the URL too
                    fields.append({
                        "name":
                        "Stream URL",
                        "value":
                        "[Watch Now]({})".format(bot_member.activity.url),
                        "inline":
                        True
                    })
        # Update the embed
        await Message.Embed(title=DisplayName.name(bot_member) + " Info",
                            color=0XFF8C00,
                            fields=fields,
                            thumbnail=avatar).edit(ctx, message)
Exemple #9
0
    async def serverinfo(self, ctx, *, guild_name = None):
        """melihat informasi server."""
        
        # Check if we passed another guild
        guild = None
        if guild_name == None:
            guild = ctx.guild
        else:
            for g in self.bot.guilds:
                if g.name.lower() == guild_name.lower():
                    guild = g
                    break
                if str(g.id) == str(guild_name):
                    guild = g
                    break
        if guild == None:
            # We didn't find it
            await ctx.send("┐( ̄ヘ ̄;)┌\nAku tidak dapat menemukan guild itu...")
            return
        
        server_embed = discord.Embed(color=0XFF8C00)
        server_embed.title = guild.name
        
        # Get localized user time
        local_time = UserTime.getUserTime(ctx.author, self.settings, guild.created_at)
        time_str = "{} {}".format(local_time['time'], local_time['zone'])
        
        server_embed.description = "Created at {}".format(time_str)
        online_members = 0
        bot_member     = 0
        bot_online     = 0
        for member in guild.members:
            if member.bot:
                bot_member += 1
                if not member.status == discord.Status.offline:
                        bot_online += 1
                continue
            if not member.status == discord.Status.offline:
                online_members += 1
        # bot_percent = "{:,g}%".format((bot_member/len(guild.members))*100)
        user_string = "{:,}/{:,} online ({:,g}%)".format(
                online_members,
                len(guild.members) - bot_member,
                round((online_members/(len(guild.members) - bot_member) * 100), 2)
        )
        b_string = "bot" if bot_member == 1 else "bots"
        user_string += "\n{:,}/{:,} {} online ({:,g}%)".format(
                bot_online,
                bot_member,
                b_string,
                round((bot_online/bot_member)*100, 2)
        )
        #server_embed.add_field(name="Members", value="{:,}/{:,} online ({:.2f}%)\n{:,} {} ({}%)".format(online_members, len(guild.members), bot_percent), inline=True)
        server_embed.add_field(name="Member ({:,} total)".format(len(guild.members)), value=user_string, inline=True)
        server_embed.add_field(name="Total Role", value=str(len(guild.roles)), inline=True)
        chandesc = "{:,} text, {:,} voice".format(len(guild.text_channels), len(guild.voice_channels))
        server_embed.add_field(name="Channel", value=chandesc, inline=True)
        server_embed.add_field(name="Default Role", value=guild.default_role, inline=True)
        server_embed.add_field(name="Owner", value=guild.owner.name + "#" + guild.owner.discriminator, inline=True)
        server_embed.add_field(name="AFK Channel", value=guild.afk_channel, inline=True)
        server_embed.add_field(name="Verification", value=guild.verification_level, inline=True)
        server_embed.add_field(name="Voice Region", value=guild.region, inline=True)
        #server_embed.add_field(name="Server besar?", value=guild.large, inline=True)
        server_embed.add_field(name="Shard ID", value="{}/{}".format(guild.shard_id+1, self.bot.shard_count), inline=True)
        server_embed.add_field(name="Nitro Boost",value="{} (level {})".format(guild.premium_subscription_count,guild.premium_tier))
        # Find out where in our join position this server is
        joinedList = []
        popList    = []
        for g in self.bot.guilds:
            joinedList.append({ 'ID' : g.id, 'Joined' : g.me.joined_at })
            popList.append({ 'ID' : g.id, 'Population' : len(g.members) })
        
        # sort the guilds by join date
        joinedList = sorted(joinedList, key=lambda x:x["Joined"].timestamp() if x["Joined"] != None else -1)
        popList = sorted(popList, key=lambda x:x['Population'], reverse=True)
        
        check_item = { "ID" : guild.id, "Joined" : guild.me.joined_at }
        total = len(joinedList)
        position = joinedList.index(check_item) + 1
        server_embed.add_field(name="Posisi Bergabung", value="{:,} dari {:,}".format(position, total), inline=True)
        
        # Get our population position
        check_item = { "ID" : guild.id, "Population" : len(guild.members) }
        total = len(popList)
        position = popList.index(check_item) + 1
        server_embed.add_field(name="Rank populasi", value="{:,} dari {:,}".format(position, total), inline=True)
        
        emojitext = ""
        emojifields = []
        disabledemojis = 0
        twitchemojis = 0
        for i,emoji in enumerate(guild.emojis):
            if not emoji.available:
                disabledemojis += 1
                continue
            if emoji.managed:
                twitchemojis += 1
                continue
            emojiMention = "<{}:{}:{}>".format("a" if emoji.animated else "",emoji.name,emoji.id)
            test = emojitext + emojiMention
            if len(test) > 1024:
                # TOOO BIIIIIIIIG
                emojifields.append(emojitext)
                emojitext=emojiMention
            else:
                emojitext = emojitext + emojiMention
        
        if len(emojitext): emojifields.append(emojitext) # Add any leftovers
        if twitchemojis:   emojifields.append("{:,} managed".format(twitchemojis))
        if disabledemojis: emojifields.append("{:,} unavailable".format(disabledemojis)) # Add the disabled if any

        server_embed.set_thumbnail(url=guild.icon_url if len(guild.icon_url) else ctx.author.default_avatar_url)
        server_embed.set_footer(text="Server ID: {}".format(guild.id))
        #Let's send all the embeds we need finishing off with extra emojis as needed
        for i,e in enumerate(emojifields):
            name = "Disabled Emojis" if e.lower().endswith("unavailable") else "Twitch Emojis" if e.lower().endswith("managed") else "Emojis ({} of {})".format(i+1,len(emojifields))
            #server_embed.add_field(name=name,value=e,inline=True)
            if len(server_embed) > 6000: # too big
                server_embed.remove_field(len(server_embed.fields)-1)
                await ctx.send(embed=server_embed)
                server_embed = discord.Embed(color=0XFF8C00)
                server_embed.title = guild.name
                server_embed.set_thumbnail(url=guild.icon_url if len(guild.icon_url) else ctx.author.default_avatar_url)
                server_embed.set_footer(text="Server ID: {}".format(guild.id))
                server_embed.description = "Continued Emojis:"
                #server_embed.add_field(name=name,value=e,inline=True)
        if len(server_embed.fields):
            await ctx.send(embed=server_embed)
Exemple #10
0
    async def botinfo(self, ctx):
        """Lists some general stats about the bot."""
        bot_member = self.bot.user if not ctx.guild else ctx.guild.get_member(
            self.bot.user.id)
        color = bot_member if isinstance(bot_member, discord.Member) else None
        message = await Message.EmbedText(title="Gathering info...",
                                          color=color).send(ctx)

        # Get guild count
        guild_count = "{:,}".format(len(self.bot.guilds))

        # Try to do this more efficiently, and faster
        total_members = [x.id for x in self.bot.get_all_members()]
        unique_members = set(total_members)
        if len(total_members) == len(unique_members):
            member_count = "{:,}".format(len(total_members))
        else:
            member_count = "{:,} ({:,} unique)".format(len(total_members),
                                                       len(unique_members))

        # Get commands/cogs count
        cog_amnt = 0
        empty_cog = 0
        for cog in self.bot.cogs:
            visible = []
            for c in self.bot.get_cog(cog).get_commands():
                if c.hidden:
                    continue
                visible.append(c)
            if not len(visible):
                empty_cog += 1
                # Skip empty cogs
                continue
            cog_amnt += 1

        cog_count = "{:,} cog".format(cog_amnt)
        # Easy way to append "s" if needed:
        if not len(self.bot.cogs) == 1:
            cog_count += "s"
        if empty_cog:
            cog_count += " [{:,} without commands]".format(empty_cog)

        visible = []
        for command in self.bot.commands:
            if command.hidden:
                continue
            visible.append(command)

        command_count = "{:,}".format(len(visible))

        # Get localized created time
        local_time = UserTime.getUserTime(ctx.author, self.settings,
                                          bot_member.created_at)
        created_at = "{} {}".format(local_time['time'], local_time['zone'])

        # Get localized joined time if in a server
        if isinstance(bot_member, discord.Member):
            local_time = UserTime.getUserTime(ctx.author, self.settings,
                                              bot_member.joined_at)
            joined_at = "{} {}".format(local_time['time'], local_time['zone'])

        # Get the current prefix
        prefix = await self.bot.command_prefix(self.bot, ctx.message)
        prefix = ", ".join(
            [x for x in prefix if not x == "<@!{}> ".format(self.bot.user.id)])

        # Get the owners
        ownerList = self.settings.getGlobalStat('Owner', [])
        owners = "Unclaimed..."
        if len(ownerList):
            userList = []
            for owner in ownerList:
                # Get the owner's name
                user = self.bot.get_user(int(owner))
                if not user:
                    userString = "Unknown User ({})".format(owner)
                else:
                    userString = "{}#{}".format(user.name, user.discriminator)
                userList.append(userString)
            owners = ', '.join(userList)

        # Get bot's avatar url
        avatar = bot_member.avatar_url
        if not len(avatar):
            avatar = bot_member.default_avatar_url

        # Build the embed
        fields = [{
            "name": "Members",
            "value": member_count,
            "inline": True
        }, {
            "name": "Servers",
            "value": guild_count,
            "inline": True
        }, {
            "name": "Commands",
            "value": command_count + " (in {})".format(cog_count),
            "inline": True
        }, {
            "name": "Created",
            "value": created_at,
            "inline": True
        }, {
            "name": "Owners",
            "value": owners,
            "inline": True
        }, {
            "name": "Prefixes",
            "value": prefix,
            "inline": True
        }, {
            "name": "Shard Count",
            "value": self.bot.shard_count,
            "inline": True
        }]
        if isinstance(bot_member, discord.Member):
            fields.append({
                "name": "Joined",
                "value": joined_at,
                "inline": True
            })
            # Get status
            status_text = ":green_heart:"
            if bot_member.status == discord.Status.offline:
                status_text = ":black_heart:"
            elif bot_member.status == discord.Status.dnd:
                status_text = ":heart:"
            elif bot_member.status == discord.Status.idle:
                status_text = ":yellow_heart:"
            fields.append({
                "name": "Status",
                "value": status_text,
                "inline": True
            })

            if bot_member.activity and bot_member.activity.name:
                play_list = [
                    "Playing", "Streaming", "Listening to", "Watching"
                ]
                try:
                    play_string = play_list[bot_member.activity.type]
                except:
                    play_string = "Playing"
                fields.append({
                    "name": play_string,
                    "value": str(bot_member.activity.name),
                    "inline": True
                })
                if bot_member.activity.type == 1:
                    # Add the URL too
                    fields.append({
                        "name":
                        "Stream URL",
                        "value":
                        "[Watch Now]({})".format(bot_member.activity.url),
                        "inline":
                        True
                    })
        # Update the embed
        await Message.Embed(title=DisplayName.name(bot_member) + " Info",
                            color=color,
                            description="Current Bot Information",
                            fields=fields,
                            thumbnail=avatar).edit(ctx, message)
Exemple #11
0
    async def serverinfo(self, ctx, *, guild_name=None):
        """Lists some info about the current or passed server."""

        # Check if we passed another guild
        guild = None
        if guild_name == None:
            guild = ctx.guild
        else:
            for g in self.bot.guilds:
                if g.name.lower() == guild_name.lower():
                    guild = g
                    break
                if str(g.id) == str(guild_name):
                    guild = g
                    break
        if guild == None:
            # We didn't find it
            await ctx.send("I couldn't find that guild...")
            return

        # server_embed = discord.Embed(color=ctx.author.color)
        server_embed = discord.Embed()
        server_embed.title = guild.name

        # Get localized user time
        local_time = UserTime.getUserTime(ctx.author, self.settings,
                                          guild.created_at)
        time_str = "{} {}".format(local_time['time'], local_time['zone'])

        server_embed.description = "Created at {}".format(time_str)
        online_members = 0
        bot_member = 0
        bot_online = 0
        for member in guild.members:
            if member.bot:
                bot_member += 1
                if not member.status == discord.Status.offline:
                    bot_online += 1
                continue
            if not member.status == discord.Status.offline:
                online_members += 1
        # bot_percent = "{:,g}%".format((bot_member/len(guild.members))*100)
        user_string = "{:,}/{:,} online ({:,g}%)".format(
            online_members,
            len(guild.members) - bot_member,
            round((online_members / (len(guild.members) - bot_member) * 100),
                  2))
        b_string = "bot" if bot_member == 1 else "bots"
        user_string += "\n{:,}/{:,} {} online ({:,g}%)".format(
            bot_online, bot_member, b_string,
            round((bot_online / bot_member) * 100, 2))
        #server_embed.add_field(name="Members", value="{:,}/{:,} online ({:.2f}%)\n{:,} {} ({}%)".format(online_members, len(guild.members), bot_percent), inline=True)
        server_embed.add_field(name="Members ({:,} total)".format(
            len(guild.members)),
                               value=user_string,
                               inline=True)
        server_embed.add_field(name="Roles",
                               value=str(len(guild.roles)),
                               inline=True)
        chandesc = "{:,} text, {:,} voice".format(len(guild.text_channels),
                                                  len(guild.voice_channels))
        server_embed.add_field(name="Channels", value=chandesc, inline=True)
        server_embed.add_field(name="Default Role",
                               value=guild.default_role,
                               inline=True)
        server_embed.add_field(name="Owner",
                               value=guild.owner.name + "#" +
                               guild.owner.discriminator,
                               inline=True)
        server_embed.add_field(name="AFK Channel",
                               value=guild.afk_channel,
                               inline=True)
        server_embed.add_field(name="Verification",
                               value=guild.verification_level,
                               inline=True)
        server_embed.add_field(name="Voice Region",
                               value=guild.region,
                               inline=True)
        server_embed.add_field(name="Considered Large",
                               value=guild.large,
                               inline=True)
        # Find out where in our join position this server is
        joinedList = []
        popList = []
        for g in self.bot.guilds:
            joinedList.append({'ID': g.id, 'Joined': g.me.joined_at})
            popList.append({'ID': g.id, 'Population': len(g.members)})

        # sort the guilds by join date
        joinedList = sorted(joinedList, key=lambda x: x['Joined'])
        popList = sorted(popList, key=lambda x: x['Population'], reverse=True)

        check_item = {"ID": guild.id, "Joined": guild.me.joined_at}
        total = len(joinedList)
        position = joinedList.index(check_item) + 1
        server_embed.add_field(name="Join Position",
                               value="{:,} of {:,}".format(position, total),
                               inline=True)

        # Get our population position
        check_item = {"ID": guild.id, "Population": len(guild.members)}
        total = len(popList)
        position = popList.index(check_item) + 1
        server_embed.add_field(name="Population Rank",
                               value="{:,} of {:,}".format(position, total),
                               inline=True)

        emojitext = ""
        emojicount = 0
        for emoji in guild.emojis:
            if emoji.animated:
                emojiMention = "<a:" + emoji.name + ":" + str(emoji.id) + ">"
            else:
                emojiMention = "<:" + emoji.name + ":" + str(emoji.id) + ">"
            test = emojitext + emojiMention
            if len(test) > 1024:
                # TOOO BIIIIIIIIG
                emojicount += 1
                if emojicount == 1:
                    ename = "Emojis ({:,} total)".format(len(guild.emojis))
                else:
                    ename = "Emojis (Continued)"
                server_embed.add_field(name=ename,
                                       value=emojitext,
                                       inline=True)
                emojitext = emojiMention
            else:
                emojitext = emojitext + emojiMention

        if len(emojitext):
            if emojicount == 0:
                emojiname = "Emojis ({} total)".format(len(guild.emojis))
            else:
                emojiname = "Emojis (Continued)"
            server_embed.add_field(name=emojiname,
                                   value=emojitext,
                                   inline=True)

        if len(guild.icon_url):
            server_embed.set_thumbnail(url=guild.icon_url)
        else:
            # No Icon
            server_embed.set_thumbnail(url=ctx.author.default_avatar_url)
        server_embed.set_footer(text="Server ID: {}".format(guild.id))
        await ctx.channel.send(embed=server_embed)