Python discord 模块,Embed() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用discord.Embed()

项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def _stats_lottery(self, ctx):
        """Shows your lottery stats
        Shows the number of times you have entered and the number
        of times you have won a lottery."""
        author = ctx.message.author
        settings = self.check_server_settings(author.server)
        if author.id not in settings["Members"]:
            return await self.bot.say("You are not a lottery member. Only members can view and "
                                      "track stats. Use [p]lottery signup to join.")
        role = settings["Config"]["Role"]
        if role not in [r.name for r in author.roles]:
            return await self.bot.say("You do not have the required role to view stats.")

        played = settings["Members"][author.id]["Entries"]
        won = settings["Members"][author.id]["Won"]

        embed = discord.Embed(description="Lottery Stat Tracker", color=0x50bdfe)
        embed.set_author(name=author.name)
        embed.set_thumbnail(url=author.avatar_url)
        embed.add_field(name="Entries", value=played, inline=True)
        embed.add_field(name="Won", value=won, inline=True)
        await self.bot.say(embed=embed)
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def about(self, ctx):
        '''About me'''
        from clients import application_info
        changes = os.popen(r'git show -s HEAD~3..HEAD --format="[`%h`](https://github.com/Harmon758/Harmonbot/commit/%H) %s (%cr)"').read().strip()
        embed = discord.Embed(title = "About Me", color = clients.bot_color)
        embed.description = "[Changelog (Harmonbot Server)]({})\n[Invite Link]({})".format(clients.changelog, discord.utils.oauth_url(application_info.id))
        # avatar = ctx.message.author.avatar_url or ctx.message.author.default_avatar_url
        # embed.set_author(name = ctx.message.author.display_name, icon_url = avatar)
        avatar = self.bot.user.avatar_url or self.bot.user.default_avatar_url
        # embed.set_thumbnail(url = avatar)
        embed.set_author(name = "Harmonbot (Discord ID: {})".format(self.bot.user.id), icon_url = avatar)
        if changes: embed.add_field(name = "Latest Changes:", value = changes, inline = False)
        embed.add_field(name = "Created on:", value = "February 10th, 2016")
        embed.add_field(name = "Version", value = clients.version)
        embed.add_field(name = "Library", value = "[discord.py](https://github.com/Rapptz/discord.py) v{0}\n([Python](https://www.python.org/) v{1.major}.{1.minor}.{1.micro})".format(discord.__version__, sys.version_info))
        me = discord.utils.get(self.bot.get_all_members(), id = clients.owner_id)
        avatar = me.default_avatar_url if not me.avatar else me.avatar_url
        embed.set_footer(text = "Developer/Owner: {0} (Discord ID: {0.id})".format(me), icon_url = avatar)
        await self.bot.reply("", embed = embed)
        await self.bot.say("Changelog (Harmonbot Server): {}".format(clients.changelog))
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def mazer_processr(self, player, reaction, user):
        if user == player and reaction.emoji in tuple(self.arrows.keys()) + ("\N{PRINTER}",):
            maze_instance = self.mazes[reaction.message.id]
            if reaction.emoji == "\N{PRINTER}":
                with open("data/temp/maze.txt", 'w') as maze_file:
                    maze_file.write('\n'.join(maze_instance.visible))
                await self.bot.send_file(reaction.message.channel, "data/temp/maze.txt", content = "{}:\nYour maze is attached".format(player.display_name))
                return
            embed = discord.Embed(color = clients.bot_color)
            avatar = player.avatar_url or player.default_avatar_url
            embed.set_author(name = player.display_name, icon_url = avatar)
            moved = maze_instance.move(self.arrows[reaction.emoji].lower())
            embed.set_footer(text = "Your current position: {}, {}".format(maze_instance.column + 1, maze_instance.row + 1))
            if moved:
                if maze_instance.reached_end():
                    embed.description = "{}\nCongratulations! You reached the end of the maze in {} moves".format(clients.code_block.format(maze_instance.print_visible()), maze_instance.move_counter)
                    del self.reaction_messages[reaction.message.id]
                else:
                    embed.description = "{}".format(clients.code_block.format(maze_instance.print_visible()))
            else:
                embed.description = "{}\n:no_entry: You can't go that way".format(clients.code_block.format(maze_instance.print_visible()))
            await self.bot.edit_message(reaction.message, embed = embed)
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def process_twitch_streams(self, streams, type, match = None):
        for stream in streams:
            if stream["_id"] in self.old_streams_announced:
                for announcement in self.old_streams_announced[stream["_id"]]:
                    embed = announcement[1]
                    embed.set_author(name = embed.author.name.replace("was", "just went"), url = embed.author.url, icon_url = embed.author.icon_url)
                    await self.bot.edit_message(announcement[0], embed = embed)
                self.streams_announced[stream["_id"]] = self.old_streams_announced[stream["_id"]]
                del self.old_streams_announced[stream["_id"]]
            elif stream["_id"] not in self.streams_announced:
                for channel_id, channel_info in self.streams_info["channels"].items():
                    if (match in channel_info[type] or \
                    not match and stream["channel"]["name"] in [s.lower() for s in channel_info[type]]) and \
                    all(filter in stream["channel"]["status"] for filter in channel_info["filters"]):
                        embed = discord.Embed(title = stream["channel"]["status"] if len(stream["channel"]["status"]) <= 256 else stream["channel"]["status"][:253] + "...", description = "{0[channel][display_name]} is playing {0[game]}".format(stream) if stream["channel"]["game"] else discord.Embed.Empty, url = stream["channel"]["url"], timestamp = dateutil.parser.parse(stream["created_at"]).replace(tzinfo = None), color = clients.twitch_color)
                        embed.set_author(name = "{} just went live on Twitch".format(stream["channel"]["display_name"]), icon_url = clients.twitch_icon_url)
                        if stream["channel"]["logo"]: embed.set_thumbnail(url = stream["channel"]["logo"])
                        embed.add_field(name = "Followers", value = stream["channel"]["followers"])
                        embed.add_field(name = "Views", value = stream["channel"]["views"])
                        text_channel = self.bot.get_channel(channel_id)
                        if not text_channel:
                            # TODO: Remove text channel data if now non-existent
                            continue
                        message = await self.bot.send_message(text_channel, embed = embed)
                        self.streams_announced[stream["_id"]] = self.streams_announced.get(stream["_id"], []) + [[message, embed]]
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def runescape_monster(self, ctx, *, monster : str):
        '''Runescape bestiary'''
        url = "http://services.runescape.com/m=itemdb_rs/bestiary/beastSearch.json?term={}".format(monster.replace(' ', '+'))
        async with clients.aiohttp_session.get(url) as resp:
            data = await resp.json()
        if data[0] == "none":
            await self.bot.embed_reply(":no_entry: Monster not found")
            return
        url = "http://services.runescape.com/m=itemdb_rs/bestiary/beastData.json?beastid={}".format(data[0]["value"])
        async with clients.aiohttp_session.get(url) as resp:
            data = await resp.json()
        embed = discord.Embed(title = data["name"], description = data["description"], color = clients.bot_color)
        avatar = ctx.message.author.avatar_url or ctx.message.author.default_avatar_url
        embed.set_author(name = ctx.message.author.display_name, icon_url = avatar)
        embed.add_field(name = "Level", value = data["level"])
        embed.add_field(name = "Weakness", value = data["weakness"])
        embed.add_field(name = "XP/Kill", value = data["xp"])
        embed.add_field(name = "Lifepoints", value = data["lifepoints"])
        embed.add_field(name = "Members", value = "Yes" if data["members"] else "No")
        embed.add_field(name = "Aggressive", value = "Yes" if data["aggressive"] else "No")
        await self.bot.say(embed = embed)
        # add other? - http://runescape.wikia.com/wiki/RuneScape_Bestiary#beastData
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def match_task(self):
        self.match_message = await self.bot.send_embed(self.text_channel, "Loading..")
        await self.update_match_embed()
        while True:
            player = [self.black_player, self.white_player][int(self.turn)]
            if player == self.bot.user:
                await self.bot.edit_message(self.match_message, embed = self.match_embed.set_footer(text = "I'm thinking.."))
                self.chess_engine.position(self)
                self.chess_engine.go(movetime = 2000, async_callback = self.process_chess_engine_command)
                await self.generated_move.wait()
                self.generated_move.clear()
                self.push(self.best_move)
                await self.update_match_embed(footer_text = "I moved {}".format(self.best_move))
            else:
                message = await self.bot.wait_for_message(author = player, channel = self.text_channel, check = lambda msg: self.valid_move(msg.content))
                await self.bot.edit_message(self.match_message, embed = self.match_embed.set_footer(text = "Processing move.."))
                self.make_move(message.content)
                footer_text = discord.Embed.Empty if self.is_game_over() else "It is {}'s ({}'s) turn to move".format(["black", "white"][int(self.turn)], [self.black_player, self.white_player][int(self.turn)])
                await self.update_match_embed(footer_text = footer_text)
                try:
                    await self.bot.delete_message(message)
                except discord.errors.Forbidden:
                    pass
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def embed_reply(self, content, *args, title = discord.Embed.Empty, title_url = discord.Embed.Empty, image_url = None, thumbnail_url = None, footer_text = discord.Embed.Empty, footer_icon_url = discord.Embed.Empty, timestamp = discord.Embed.Empty, fields = [], **kwargs):
        author = commands.bot._get_variable('_internal_author')
        destination = commands.bot._get_variable('_internal_channel')
        embed = discord.Embed(description = str(content) if content else None, title = title, url = title_url, timestamp = timestamp, color = bot_color)
        embed.set_author(name = author.display_name, icon_url = author.avatar_url or author.default_avatar_url)
        if image_url: embed.set_image(url = image_url)
        if thumbnail_url: embed.set_thumbnail(url = thumbnail_url)
        embed.set_footer(text = footer_text, icon_url = footer_icon_url)
        for field_name, field_value in fields:
            embed.add_field(name = field_name, value = field_value)
        extensions = ('delete_after',)
        params = {k: kwargs.pop(k, None) for k in extensions}
        coro = self.send_message(destination, embed = embed, *args, **kwargs)
        if destination.is_private or getattr(destination.permissions_for(destination.server.me), "embed_links", None):
            return self._augmented_msg(coro, embed = embed, **params)
        elif not (title or title_url or image_url or thumbnail_url or footer_text or timestamp):
            fmt = '{0.display_name}: {1}'.format(author, str(content))
            coro = self.send_message(destination, fmt, *args, **kwargs)
            return self._augmented_msg(coro, **params)
        else:
            permissions = ["embed_links"]
            raise errors.MissingCapability(permissions)
项目:youtube    作者:FishyFing    | 项目源码 | 文件源码
def _list_channels(self, ctx):
        """Lists YouTube channels with announcements enabled"""
        guild = ctx.message.guild
        if guild.id in self.ids:
            try:
                data = discord.Embed(
                    title="**__Announcement Channels__**\n", colour=discord.Colour(value=11735575))
                k = self.ids[guild.id]['yt_channel']
                data.add_field(
                    name="YouTube Channel", value=k)
                data.add_field(
                    name="Discord Channel", value=self.ids[guild.id]['channel'])
                data.set_footer(
                    text="Made with \U00002665 by Francis#6565. Support server: https://discord.gg/yp8WpMh")
                await ctx.send(embed=data)
            except IndexError as e:
                logger.exception(
                    "An error occured while pulling data from list... {}".format(e))
项目:spirit    作者:jgayfer    | 项目源码 | 文件源码
def donate(self, ctx):
        """Support the continued development of Spirit!"""
        manager = MessageManager(self.bot, ctx.author, ctx.channel, ctx.prefix, [ctx.message])
        e = discord.Embed(colour=constants.BLUE)

        text = ("Spirit is a work of love that has taken countless hours to develop. Your donation "
              + "will go towards server hosting costs, development tools, and if you donate "
              + "monthly, will also earn you some special privelges on the Spirit Discord server!\n\n"
              + "Donate once: https://www.paypal.me/spiritbot\n"
              + "Donate monthly: https://www.patreon.com/spiritbot")
        reward_1 = "- Colored name on the Spirit Discord server"
        reward_2 = ("- Patron role and colored name on the Spirit Discord server\n"
                  + "- Access to the developer blog on Patreon and the Spirit Discord server\n"
                  + "- Access to a patron only channel on the Spirit Discord server which includes sneak peeks of new features!")
        reward_3 = ("- All rewards from the previous tier\n"
                  + "- Your own personalized message built right into Spirit!")

        e.description = text
        e.add_field(name="$1/Month", value=reward_1)
        e.add_field(name="$5/Month", value=reward_2)
        e.add_field(name="$10/Month", value=reward_3)

        await manager.say(e, embed=True, delete=False)
        await manager.clear()
项目:PTSCogs    作者:PlanetTeamSpeakk    | 项目源码 | 文件源码
def channelinfo(self, ctx, channel : discord.Channel = None):
        """Gives you some channel information."""
        if channel == None:
            channel = ctx.message.channel
        passed = (ctx.message.timestamp - channel.created_at).days
        try:
            channel_created_at = ("Created on {} ({} days ago!)".format(channel.created_at.strftime("%d %b %Y %H:%M"), passed))
            em = discord.Embed(description="{}, here you go:".format(ctx.message.author.mention), title="Channel Info", color=0X008CFF)
            em.add_field(name="Channel Name", value=str(channel.name))
            em.add_field(name="Channel ID", value=str(channel.id))
            em.add_field(name="Channel Default", value=str(channel.is_default))
            em.add_field(name="Channel Position", value=str(channel.position + 1))
            em.add_field(name="Channel Topic", value=(channel.topic))
            em.set_footer(text=channel_created_at)
            await self.bot.say(embed=em)
        except discord.HTTPException:
            channel_created_at = ("Created on {} ({} days ago!)".format(channel.created_at.strftime("%d %b %Y %H:%M"), passed))            
            em = discord.Embed(description="{}, here you go:".format(ctx.message.author.mention), title="Channel Info", color=0X008CFF)
            em.add_field(name="Channel Name", value=str(channel.name))
            em.add_field(name="Channel ID", value=str(channel.id))
            em.add_field(name="Channel Default", value=str(channel.is_default))
            em.add_field(name="Channel Position", value=str(channel.position + 1))
            em.add_field(name="Channel Topic", value="None")
            em.set_footer(text=channel_created_at)
            await self.bot.say(embed=em)
项目:PTSCogs    作者:PlanetTeamSpeakk    | 项目源码 | 文件源码
def discrim(self, discriminator: str):
        """Shows you all the members I can find with the discrim you gave."""
        discriminator = discriminator.replace("#", "")
        if not discriminator.isdigit():
            await self.bot.say("A Discrimnator can only have digits and a #\nExamples\n`#4157`, `4157`")
            return

        members = [str(s) for s in list(self.bot.get_all_members()) if s.discriminator == discriminator]
        members = ", ".join(list(set(members)))
        if not members:
            await self.bot.say("I could not find any users in any of the servers I'm in with a discriminator of `{}`".format(discriminator))
            return
        else:
            embed = discord.Embed(colour=0X00B6FF)
            embed.add_field(name="Discriminator #{}".format(discriminator), value=str(members), inline=False)
            try:
                await self.bot.say(embed=embed)
            except:
                await self.bot.say("An unknown error occured while embedding.")
项目:Kurisu-Reswitched    作者:916253    | 项目源码 | 文件源码
def on_member_join(self, member):
        await self.bot.wait_until_all_ready()
        msg = "? **Join**: {} | {}#{}\n?? __Creation__: {}\n?? __User ID__: {}".format(
            member.mention, self.bot.escape_name(member.name), member.discriminator, member.created_at, member.id
        )
        with open("data/restrictions.json", "r") as f:
            rsts = json.load(f)
        if member.id in rsts:
            roles = []
            for rst in rsts[member.id]:
                roles.append(discord.utils.get(self.bot.server.roles, name=rst))
            await self.bot.add_roles(member, *roles)
        with open("data/warnsv2.json", "r") as f:
            warns = json.load(f)
        try:
            if len(warns[member.id]["warns"]) == 0:
                await self.bot.send_message(self.bot.serverlogs_channel, msg)
            else:
                embed = discord.Embed(color=discord.Color.dark_red())
                embed.set_author(name="Warns for {}#{}".format(self.bot.escape_name(member.name), member.discriminator), icon_url=member.avatar_url)
                for idx, warn in enumerate(warns[member.id]["warns"]):
                    embed.add_field(name="{}: {}".format(idx + 1, warn["timestamp"]), value="Issuer: {}\nReason: {}".format(warn["issuer_name"], warn["reason"]))
                await self.bot.send_message(self.bot.serverlogs_channel, msg, embed=embed)
        except KeyError:  # if the user is not in the file
            await self.bot.send_message(self.bot.serverlogs_channel, msg)
项目:Kurisu-Reswitched    作者:916253    | 项目源码 | 文件源码
def listwarns(self, ctx, user):
        """List warns for a user. Staff only."""
        try:
            member = ctx.message.mentions[0]
        except IndexError:
            await self.bot.say("Please mention a user.")
            return
        embed = discord.Embed(color=discord.Color.dark_red())
        embed.set_author(name="Warns for {}#{}".format(member.display_name, member.discriminator), icon_url=member.avatar_url)
        with open("data/warnsv2.json", "r") as f:
            warns = json.load(f)
        try:
            if len(warns[member.id]["warns"]) == 0:
                embed.description = "There are none!"
                embed.color = discord.Color.green()
            else:
                for idx, warn in enumerate(warns[member.id]["warns"]):
                    embed.add_field(name="{}: {}".format(idx + 1, warn["timestamp"]), value="Issuer: {}\nReason: {}".format(warn["issuer_name"], warn["reason"]))
        except KeyError:  # if the user is not in the file
            embed.description = "There are none!"
            embed.color = discord.Color.green()
        await self.bot.say("", embed=embed)
项目:lagbot    作者:mikevb1    | 项目源码 | 文件源码
def show(self, ctx):
        """Show the prefix set for this guild.

        Also shows whether or not the default prefix can be used.
        """
        rec = await self.bot.get_guild_prefix(ctx.guild.id)
        if rec is None:
            await ctx.send("A custom prefix hasn't been set for this guild.")
            return

        prefix, allow_default = rec['prefix'], rec['allow_default']
        valid = [prefix]
        default = config.prefix
        if allow_default:
            if isinstance(default, (tuple, list)):
                valid.extend(default)
            else:
                valid.append(default)

        embed = discord.Embed()
        embed.add_field(name='Custom Prefix', value=valid[0])
        embed.add_field(name='Allow Default', value=str(rec['allow_default']))
        embed.add_field(name='Valid Prefixes', value='\n'.join(valid))
        await ctx.send(embed=embed)
项目:lagbot    作者:mikevb1    | 项目源码 | 文件源码
def debug(self, ctx, *, code: cleanup_code):
        """Evaluates code."""
        result = None
        env = get_env(ctx)
        env['__'] = self.last_eval

        try:
            result = eval(code, env)
            if inspect.isawaitable(result):
                result = await result
            if isinstance(result, discord.Embed):
                await ctx.send(embed=result)
                return
        except Exception as e:
            say = self.eval_output(exception_signature())
        else:
            say = self.eval_output(rep(result))
        if say is None:
            say = 'None'
        await ctx.send(say)
项目:lagbot    作者:mikevb1    | 项目源码 | 文件源码
def charinfo(self, ctx, *, chars):
        """Get unicode character info."""
        if not chars:
            return
        chars = unicodedata.normalize('NFC', chars)
        if len(chars) > 25:
            await ctx.send('Too many emoji.')
            return
        embed = discord.Embed()
        for char in chars:
            uc = hex(ord(char))[2:]
            name = unicodedata.name(char, 'unknown')
            if name in {'SPACE', 'EM QUAD', 'EN QUAD'} or ' SPACE' in name:
                char = '" "'
            short = len(uc) <= 4
            code = f'`\\{"u" if short else "U"}{uc.lower().zfill(4 if short else 8)}`'
            embed.add_field(name=name,
                            value=f'{char} [{code}](http://www.fileformat.info/info/unicode/char/{uc}/index.htm)')
        await ctx.send(embed=embed)
项目:lagbot    作者:mikevb1    | 项目源码 | 文件源码
def cat(self, ctx):
        """Get a random cat image."""
        with ctx.typing():
            try:
                image_url = await self.fetch_cat()
            except NotFound as e:
                await ctx.send(e)
                return

            try:
                fact = (await self.fetch_facts(1))[0]
            except NotFound as e:
                fact = ''

            embed = discord.Embed(description=fact or None)
            embed.set_image(url=image_url)
        try:
            await ctx.send(embed=embed)
        except discord.HTTPException:
            embed = discord.Embed(description=fact or None)
            embed.set_footer(text='Failed getting a cat image.')
            await ctx.send(embed=embed)
项目:Socrates    作者:Curlybear    | 项目源码 | 文件源码
def mppsraw(self, ctx):
        logger.info('!mppsraw - User: ' + str(ctx.message.author))
        mpp_text = ''
        r = requests.get('https://api.erepublik-deutschland.de/' + apiKey + '/countries/details/all')
        obj = json.loads(r.text)
        for country in obj['countries']:
            mpps = obj['countries'][country]['military']['mpps']
            if mpps:
                mpps.sort(key=lambda x: x['expires'][0:10])
                for mpp in mpps:
                    mpp_text += self.utils.get_country_name(country) + ';' + self.utils.get_country_name(
                        mpp['country_id']) + ';' + mpp['expires'][0:10] + '\n'

        link = PythonGists.Gist(description='eRepublik MPPs', content=mpp_text, name='mpps' + datetime.datetime.now().strftime("%d-%m-%Y") + '.csv')
        em = discord.Embed(title='All MPPs',
                           description=link, colour=0x0042B9)
        await self.bot.send_message(ctx.message.channel, '', embed=em)
项目:Socrates    作者:Curlybear    | 项目源码 | 文件源码
def convert(self, ctx, in_value: str):
        logger.info('!convert ' + in_value + ' - User: ' + str(ctx.message.author))

        start_date = datetime.datetime(day=21, month=11, year=2007)
        try:
            if self.utils.is_number(in_value):
                delta = datetime.timedelta(days=int(in_value) - 1)
                final_date = start_date + delta
                em = discord.Embed(title='Conversion', description='Date : ' + final_date.strftime('%d/%m/%Y'),
                                   colour=0x0053A9)
                await self.bot.send_message(ctx.message.channel, '', embed=em)
            else:
                in_date = datetime.datetime.strptime(in_value, '%d/%m/%Y')
                erep_day = in_date - start_date + datetime.timedelta(days=1)
                em = discord.Embed(title='Conversion', description='eRepublik day : ' + str(erep_day.days),
                                   colour=0x0053A9)
                await self.bot.send_message(ctx.message.channel, '', embed=em)
        except:
            traceback.print_exc()
            logger.info('   Invalid input')
            await self.bot.say('Invalid input')
项目:Luna    作者:Moonlington    | 项目源码 | 文件源码
def poll(self, ctx, *, string: str):
        """Formatting: Question|Option 1|Option 2|etc."""
        await self.bot.delete_message(ctx.message)
        string = string.strip("| *")
        split = string.split("|")
        emojibet = ['??', '??', '??', '??', '??', '??', '??', '??', '??', '??', '??', '??', '??', '??', '??', '??', '??', '??', '??', '??', '??', '??', '??', '??', '??', '??']
        alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
        question = split[0].strip(" ")
        query = [x.strip(" ") for x in split[1:] if x.strip(" ") != ""]
        em = discord.Embed(description=question, colour=ctx.message.author.color)
        for i, q in enumerate(query):
            em.add_field(name = "Option " + alphabet[i], value = q, inline = False)
        em.set_author(name=ctx.message.author.display_name, icon_url=ctx.message.author.avatar_url)
        em.set_footer(text="React to this message to vote! (Sorry mobile users)")
        sent = await self.bot.send_message(ctx.message.channel, embed = em)
        for i, _ in enumerate(query):
            await self.bot.add_reaction(sent, emojibet[i])
项目:Luna    作者:Moonlington    | 项目源码 | 文件源码
def quote(self, ctx, qid, *, content=None):
        if content is None:
            msg = await self.bot.get_message(ctx.message.channel, qid)
            if msg is None:
                await self.bot.say("Message with that ID not found! (Or you used a user ID which you shouldn't use without content)")
            else:
                em = discord.Embed(description=msg.content, colour=msg.author.color)
                em.set_author(name=str(msg.author), icon_url=msg.author.avatar_url)
                em.set_footer(text="Sent | {}".format(msg.timestamp))
                await self.bot.send_message(ctx.message.channel, embed=em)
        else:
            mem = ctx.message.server.get_member(qid)
            if mem is None:
                await self.bot.say("Member with that ID not found! (Or you used a message ID which you shouldn't use)")
            else:
                em = discord.Embed(description=content, colour=mem.color)
                em.set_author(name=mem.display_name, icon_url=mem.avatar_url)
                em.set_footer(text="Sent | {}".format(random.choice(["Sometime...", "in a whisper.", "in hell"])))
                await self.bot.send_message(ctx.message.channel, embed=em)
项目:Luna    作者:Moonlington    | 项目源码 | 文件源码
def _repljump(ctx):
        '''Brings the shell back down so you can see it again.'''

        session = ctx.message.channel.id

        if session not in self.repl_sessions:
            await self.bot.send_message(ctx.message.channel, embed = discord.Embed(color = 15746887, 
                                                description = "**Error**: _No shell running in channel._"))
            return

        shell = self.repl_sessions[session]
        embed = self.repl_embeds[shell]

        await self.bot.delete_message(ctx.message)
        await self.bot.delete_message(shell)
        new_shell = await self.bot.send_message(ctx.message.channel, embed=embed)

        self.repl_sessions[session] = new_shell

        del self.repl_embeds[shell]
        self.repl_embeds[new_shell] = embed
项目:Luna    作者:Moonlington    | 项目源码 | 文件源码
def _replclear(ctx):
        '''Clears the fields of the shell and resets the color.'''

        session = ctx.message.channel.id

        if session not in self.repl_sessions:
            await self.bot.send_message(ctx.message.channel, embed = discord.Embed(color = 15746887, 
                                                description = "**Error**: _No shell running in channel._"))
            return

        shell = self.repl_sessions[session]

        self.repl_embeds[shell].color = discord.Color.default()
        self.repl_embeds[shell].clear_fields()

        await self.bot.delete_message(ctx.message)
        await self.bot.edit_message(shell, embed=self.repl_embeds[shell])
项目:globibot    作者:best-coloc-ever    | 项目源码 | 文件源码
def voteskip(self, message):
        if message.server.id in self.ongoing_skips:
            return

        player = self.get_player(message.server)

        embed = Embed(
            title       = 'Voteskip',
            description = 'Skip __{}__ ?'.format(player.items[0].resource)
        )
        embed.set_footer(text='Click the reaction below to cast your vote')

        m = await self.send_message(message.channel, '', embed=embed)
        await self.bot.add_reaction(m, '??')

        self.ongoing_skips[message.server.id] = m
        self.run_async(self.skip_timeout(message.server.id, m))
项目:AceBot    作者:Run1e    | 项目源码 | 文件源码
def forumlink(self, ctx, url):
        post = Preview.getThread(url)

        embed = discord.Embed(title=post["title"], url=url)

        embed.description = shorten(post['description'], 2048, 12)

        if post["image"]:
            embed.set_image(url=post["image"] if post["image"][0] != "." else "https://autohotkey.com/boards" + post["image"][1:post["image"].find("&") + 1])

        embed.set_author(name=post["user"]["name"], url="https://autohotkey.com/boards" + post["user"]["url"][1:],
                         icon_url="https://autohotkey.com/boards" + post["user"]["icon"][1:])

        embed.set_footer(text='autohotkey.com')

        await ctx.send(embed=embed)
项目:AceBot    作者:Run1e    | 项目源码 | 文件源码
def embedwiki(self, ctx, wiki):
        embed = discord.Embed()

        sum = wiki.summary
        if len(sum) > 1024:
            sum = sum[0:1024] + '...'

        embed.description = sum
        embed.set_author(name=wiki.title, url=wiki.url, icon_url='https://i.imgur.com/qIor1ag.png')

        image = ''
        for img in wiki.images:
            if not img.endswith('.svg'):
                image = img
                break

        if image:
            embed.set_image(url=image)

        embed.set_footer(text='wikipedia.com')
        await ctx.send(embed=embed)
项目:Godavaru    作者:Godavaru    | 项目源码 | 文件源码
def dog(self, ctx):
        """Get a random cat image!

        **Usage:** `g_dog`

        **Permission:** User"""
        isVideo = True
        while isVideo:
            r = requests.get('https://random.dog/woof.json')
            js = r.json()
            if js['url'].endswith('.mp4'):
                pass
            else:
                isVideo = False
        colours = [0x1abc9c, 0x11806a, 0x2ecc71, 0x1f8b4c, 0x3498db, 0x206694, 0x9b59b6, 0x71368a, 0xe91e63, 0xad1457, 0xf1c40f, 0xc27c0e, 0xa84300, 0xe74c3c, 0x992d22, 0x95a5a6, 0x607d8b, 0x979c9f, 0x546e7a]
        col = int(random.random() * len(colours))
        content = [":dog: Don't be sad! This doggy wants to play with you!", "You seem lonely, {0.mention}. Here, have a dog. They're not as nice as cats, but enjoy!".format(ctx.message.author), "Weuf, woof, woooooooooof. Woof you.", "Pupper!", "Meow... wait wrong animal."]
        con = int(random.random() * len(content))
        em = discord.Embed(color=colours[col])
        em.set_image(url=js['url'])
        await ctx.send(content=content[con], embed=em)
项目:Godavaru    作者:Godavaru    | 项目源码 | 文件源码
def status(self, ctx):
        """Display the current status of the specified member.
        If the member is not specified or an invalid member argument is passed, the member is the author.

        **Usage:** `g_status [member]`

        **Permission:** User"""
        if len(ctx.message.mentions) == 0:
            user = ctx.message.author
            a = ", you are "
        else:
            user = ctx.message.mentions[0]
            a = " is "
        if user.game is None:
            game = "Nothing."
            footer = "Maybe you should get out into the world. Meet some people. Could be good for you."
        else:
            game = str(user.game)
            footer = "Hope it's a fun one!"
        em = discord.Embed(title=user.display_name+a+"playing:",description="`{}`".format(game),color=user.color)
        em.set_footer(text=footer)
        await ctx.send(embed=em)
项目:GrandeCogs    作者:HarukiGrande    | 项目源码 | 文件源码
def analytics(self, ctx, url):
        """Analytics for url"""
        key = self.loadapi["ApiKey"]
        async with aiohttp.ClientSession() as session:
            async with session.get('https://www.googleapis.com/urlshortener/v1/url?key=' + key + '&shortUrl=' + url + '&projection=FULL') as resp:
                print(resp.status)
                yes = await resp.json()
                embed = discord.Embed(colour=discord.Colour.blue())
                embed.add_field(name="**Shortened Url:**",value=yes['id'])
                embed.add_field(name="**Long Url:**",value=yes['longUrl'])
                embed.add_field(name="**Date Created:**",value=yes['created'])
                embed.add_field(name="**Clicks:**",value=yes['analytics']['allTime']['shortUrlClicks'])
                embed.set_image(url="https://www.ostraining.com/cdn/images/coding/google-url-shortener-tool.jpg")
                await self.bot.say(embed=embed)
项目:GrandeCogs    作者:HarukiGrande    | 项目源码 | 文件源码
def neko(self, ctx):
        """Nekos! \o/ Warning: Some lewd nekos exist :eyes:"""
        async with self.session.get("https://nekos.life/api/neko") as resp:
            nekos = await resp.json()

        embed = discord.Embed(colour=discord.Colour.blue())
        embed.set_image(url=nekos['neko'])
        await self.bot.say(embed=embed)
项目:GrandeCogs    作者:HarukiGrande    | 项目源码 | 文件源码
def pat(self, context, member: discord.Member):
        """Pat your senpai/waifu!"""
        author = context.message.author.mention
        mention = member.mention

        pat = "**{0} got patted by {1}!**"

        choices = ['http://i.imgur.com/10VrpFZ.gif', 'http://i.imgur.com/x0u35IU.gif', 'http://i.imgur.com/0gTbTNR.gif', 'http://i.imgur.com/hlLCiAt.gif', 'http://i.imgur.com/sAANBDj.gif']

        image = random.choice(choices)

        embed = discord.Embed(description=pat.format(mention, author), colour=discord.Colour.blue())
        embed.set_image(url=image)

        await self.bot.say(embed=embed)
项目:GrandeCogs    作者:HarukiGrande    | 项目源码 | 文件源码
def kiss(self, context, member: discord.Member):
        """Kiss your senpai/waifu!"""
        author = context.message.author.mention
        mention = member.mention

        kiss = "**{0} gave {1} a kiss!**"

        choices = ['http://i.imgur.com/0D0Mijk.gif', 'http://i.imgur.com/TNhivqs.gif', 'http://i.imgur.com/3wv088f.gif', 'http://i.imgur.com/7mkRzr1.gif', 'http://i.imgur.com/8fEyFHe.gif']

        image = random.choice(choices)

        embed = discord.Embed(description=kiss.format(author, mention), colour=discord.Colour.blue())
        embed.set_image(url=image)

        await self.bot.say(embed=embed)
项目:GrandeCogs    作者:HarukiGrande    | 项目源码 | 文件源码
def hug(self, context, member: discord.Member):
        """Hug your senpai/waifu!"""
        author = context.message.author.mention
        mention = member.mention

        hug = "**{0} gave {1} a hug!**"

        choices = ['http://i.imgur.com/sW3RvRN.gif', 'http://i.imgur.com/gdE2w1x.gif', 'http://i.imgur.com/zpbtWVE.gif', 'http://i.imgur.com/ZQivdm1.gif', 'http://i.imgur.com/MWZUMNX.gif']

        image = random.choice(choices)

        embed = discord.Embed(description=hug.format(author, mention), colour=discord.Colour.blue())
        embed.set_image(url=image)

        await self.bot.say(embed=embed)
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def _status_lottery(self, ctx):
        """Check if a lottery is active"""
        author = ctx.message.author
        settings = self.check_server_settings(author.server)
        if settings["Config"]["Active"]:
            ld = settings["Config"]["Current Loadout"]
            timer = settings["Loadouts"][ld]["Timer"]

            if timer == 0:
                remaining = "no time limit"
            else:
                counter = settings["Config"]["Tracker"]
                seconds = timer - (datetime.utcnow() - parser.parse(counter)).seconds
                remaining = "{} remaining".format(self.time_formatter(seconds))

            winners = settings["Loadouts"][ld]["Winners"]
            entry_limit = settings["Loadouts"][ld]["Limit"]
            dos = settings["Loadouts"][ld]["DOS"]
            role_req = settings["Loadouts"][ld]["Role"]
            prize = settings["Loadouts"][ld]["Prize"]
            footer = "There are currently {} users in the lottery.".format(len(settings["Players"]))

            if author.id in settings["Players"]:
                desc = "You are currently in the lottery."
            else:
                desc = "You have **not** entered into this lottery yet."

            embed = discord.Embed(title="Loadout {}".format(ld), description=desc, color=0x50bdfe)
            embed.set_author(name="Lottery System 3.0")
            embed.add_field(name="Prize", value=prize, inline=True)
            embed.add_field(name="Possible Winners", value=winners, inline=True)
            embed.add_field(name="Role", value=role_req, inline=True)
            embed.add_field(name="Limit", value=entry_limit, inline=True)
            embed.add_field(name="Time Remaining", value=remaining, inline=True)
            embed.add_field(name="Days on Server Required", value=dos, inline=True)
            embed.set_footer(text=footer)
            await self.bot.say(embed=embed)
        else:
            await self.bot.say("There aren't any lotteries running on this server right now.")
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def _view_lottery(self, ctx, loadout: int):
        """View the parameters set for a loadout"""

        if loadout not in [0, 1, 2, 3, 4, 5]:
            return await self.bot.say("Invalid loadout. Must be 0-5.")

        server = ctx.message.server
        settings = self.check_server_settings(server)
        loadout = str(loadout)

        if not self.slot_checker(settings, loadout):
            return await self.bot.say("The selected loadout is empty.")

        timer = settings["Loadouts"][loadout]["Timer"]
        if timer == 0:
            time_fmt = "no time limit"
        else:
            time_fmt = self.time_formatter(timer)

        winners = settings["Loadouts"][loadout]["Winners"]
        entry_limit = settings["Loadouts"][loadout]["Limit"]
        dos = settings["Loadouts"][loadout]["DOS"]
        role_req = settings["Loadouts"][loadout]["Role"]
        prize = settings["Loadouts"][loadout]["Prize"]
        start_msg = settings["Loadouts"][loadout]["Start Message"]
        end_msg = settings["Loadouts"][loadout]["End Message"]

        embed = discord.Embed(title="Loadout {}".format(loadout), color=0x50bdfe)
        embed.add_field(name="Prize", value=prize, inline=True)
        embed.add_field(name="Number of Winners", value=winners, inline=True)
        embed.add_field(name="Role", value=role_req, inline=True)
        embed.add_field(name="Entry Limit", value=entry_limit, inline=True)
        embed.add_field(name="Timer", value=time_fmt, inline=True)
        embed.add_field(name="Days on Server Required", value=dos, inline=True)
        embed.add_field(name="Start Message", value=start_msg, inline=True)
        embed.add_field(name="End Message", value=end_msg, inline=True)
        await self.bot.say(embed=embed)
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def send_profile(self, user, author_col, user_col, user_data, user_name, url, cmd):

        if author_col == "SELF":
            share = ['Not Applicable']
            different = ['Not Applicable']
        elif author_col:
            intersect = user_col.intersection(author_col)
            difference = author_col.difference(user_col)
            share = random.sample(intersect, len(intersect) if len(intersect) < 5 else 5)
            if not share:
                share = ["Nothing Mutual"]
            different = random.sample(difference, len(difference) if len(difference) < 5 else 5)
            if not different:
                different = ["Nothing different"]
        else:
            share = ["Author's MAL not set"]
            different = ["Author's MAL not set"]

        if cmd == "anime":
            medium = "Watching"
            emojis = [":film_frames:", ":vhs:", ":octagonal_sign:"]
        else:
            medium = "Reading"
            emojis = [":book:", ":books:", ":bookmark:"]

        link = "https://myanimelist.net/animelist/{}".format(user_name)
        description = ("**{}**\n[{}]({})\nTotal {}: "
                       "{}".format(user.name, user_name, link, cmd.title(), len(user_col)))
        embed = discord.Embed(colour=0x0066FF, description=description)
        embed.title = "My Anime List Profile"
        embed.set_thumbnail(url="https://myanimelist.cdn-dena.com/img/sp/icon/apple-touch-icon-256."
                                "png")
        embed.add_field(name=":calendar_spiral: Days Spent {}".format(medium), value=user_data[4],
                        inline=False)
        embed.add_field(name="{} {}".format(emojis[0], medium), value=user_data[0])
        embed.add_field(name="{} Completed".format(emojis[1]), value=user_data[1])
        embed.add_field(name="{} On Hold".format(emojis[2]), value=user_data[2])
        embed.add_field(name=":wastebasket: Dropped", value=user_data[3])
        embed.add_field(name=":link: Five Shared", value='\n'.join(share), inline=False)
        embed.add_field(name=":trident: Five Different", value='\n'.join(different))
        await self.bot.say(embed=embed)
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def _moves_pokemon(self, *, poke: str):
        """Search for a Pokémon's moveset

        If the generation specified is not found, it will default to 7

            Args:
                poke: variable length string

            Returns:
                Tabular output of Pokémon data.

            Raises:
                AttributeError: Pokémon not found.

            Examples:
                Numbers:    [p]pokemon moves charizard-4
                Alolan:     [p]pokemon moves geodude-alola
        """
        moves = self.search_csv(poke.lower(), 'data/pokedex/Moves.csv', data_type='m')

        try:
            table = tabulate(moves.moves, headers=['Level', 'Moves', 'Type', 'Power', 'Accuracy'])
        except AttributeError:
            await self.bot.say('A Pokémon with that name could not be found.')
        else:
            embed = discord.Embed(title=moves.pokemon, colour=moves.color,
                                  description="```{}```".format(table))
            embed.add_field(name="Versions", value='\n'.join(moves.versions))
            embed.set_footer(text="This moveset is based on generation {}.".format(moves.gen))

            await self.bot.say(embed=embed)
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def _item_pokemon(self, *, item_name: str):
        """Search for an item in the Pokémon universe

            Args:
                item_name: variable length string

            Returns:
                Discord embed

            Raises:
                AttributeError: Item not found

            Examples:
                pokemon item master ball
        """
        item = self.search_csv(item_name.title(), 'data/pokedex/Items.csv', data_type='i')
        try:
            color = self.color_lookup(item.category)
        except AttributeError:
            await self.bot.say("An item with that name could not be found.")
        else:
            embed = discord.Embed(colour=color, title=item.name)
            embed.set_thumbnail(url=item.image)
            embed.add_field(name="Cost", value=item.cost)
            embed.add_field(name="Category", value=item.category)
            embed.add_field(name="Effect", value=item.effect)
            await self.bot.say(embed=embed)
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def _info_heist(self, ctx):
        """Shows the Heist settings for this server."""
        server = ctx.message.server
        settings = self.check_server_settings(server)

        if settings["Config"]["Hardcore"]:
            hardcore = "ON"
        else:
            hardcore = "OFF"

        # Theme variables
        theme = settings["Config"]["Theme"]
        t_jail = settings["Theme"]["Jail"]
        t_sentence = settings["Theme"]["Sentence"]
        t_police = settings["Theme"]["Police"]
        t_bail = settings["Theme"]["Bail"]

        time_values = [settings["Config"]["Wait Time"], settings["Config"]["Police Alert"],
                       settings["Config"]["Sentence Base"], settings["Config"]["Death Timer"]]
        timers = list(map(self.time_format, time_values))
        description = ["Heist Version {}".format(self.version), "Theme: {}".format(theme)]
        footer = "Heist was developed by Redjumpman for Red Bot."

        embed = discord.Embed(colour=0x0066FF, description="\n".join(description))
        embed.title = "{} Heist Settings".format(server.name)
        embed.add_field(name="Heist Cost", value=settings["Config"]["Heist Cost"])
        embed.add_field(name="Base {} Cost".format(t_bail), value=settings["Config"]["Bail Base"])
        embed.add_field(name="Crew Gather Time", value=timers[0])
        embed.add_field(name="{} Timer".format(t_police), value=timers[1])
        embed.add_field(name="Base {} {}".format(t_jail, t_sentence), value=timers[2])
        embed.add_field(name="Death Timer", value=timers[3])
        embed.add_field(name="Hardcore Mode", value=hardcore)
        embed.set_footer(text=footer)

        await self.bot.say(embed=embed)
项目:Jumper-Cogs    作者:Redjumpman    | 项目源码 | 文件源码
def _stats_heist(self, ctx):
        """Shows your Heist stats"""
        author = ctx.message.author
        avatar = ctx.message.author.avatar_url
        settings = self.check_server_settings(author.server)
        self.account_check(settings, author)
        path = settings["Players"][author.id]

        # Theme variables
        sentencing = "{} {}".format(settings["Theme"]["Jail"], settings["Theme"]["Sentence"])
        t_bail = "{} Cost".format(settings["Theme"]["Bail"])

        # Sentence Time Remaining
        sentence = path["Sentence"]
        time_served = path["Time Served"]
        jail_fmt = self.cooldown_calculator(time_served, sentence)

        # Death Time Remaining
        death_timer = path["Death Timer"]
        base_death_timer = settings["Config"]["Death Timer"]
        death_fmt = self.cooldown_calculator(death_timer, base_death_timer)

        rank = self.criminal_level(path["Criminal Level"])

        embed = discord.Embed(colour=0x0066FF, description=rank)
        embed.title = author.name
        embed.set_thumbnail(url=avatar)
        embed.add_field(name="Status", value=path["Status"])
        embed.add_field(name="Spree", value=path["Spree"])
        embed.add_field(name=t_bail, value=path["Bail Cost"])
        embed.add_field(name=settings["Theme"]["OOB"], value=path["OOB"])
        embed.add_field(name=sentencing, value=jail_fmt)
        embed.add_field(name="Apprehended", value=path["Jail Counter"])
        embed.add_field(name="Death Timer", value=death_fmt)
        embed.add_field(name="Total Deaths", value=path["Deaths"])
        embed.add_field(name="Lifetime Apprehensions", value=path["Total Jail"])

        await self.bot.say(embed=embed)
项目:pineapple    作者:peter765    | 项目源码 | 文件源码
def send_message(self, name, channel, message):
        em = discord.Embed(description=message, colour=self.get_color(name))
        msg = await self.client.send_message(channel, embed=em)
        return msg
项目:pineapple    作者:peter765    | 项目源码 | 文件源码
def edit_message(self, name, old_message, new_message):
        em = discord.Embed(description=new_message, colour=self.get_color(name))
        msg = await self.client.edit_message(old_message, embed=em)
        return msg
项目:pineapple    作者:peter765    | 项目源码 | 文件源码
def server_info(self, message_object):
        server = message_object.server
        msg = "**Name:** " + server.name + " (" + server.id + ")\n"
        msg += "**Total members:** " + str(server.member_count) + "\n"
        msg += "**Server owner:** " + server.owner.name + "\n"
        msg += "**Server region:** " + str(server.region) + "\n"
        msg += "**Created at:** " + server.created_at.strftime("%B %d, %Y")

        em = discord.Embed(description=msg, colour=self.pm.clientWrap.get_color(self.name))
        em.set_image(url=server.icon_url)
        await self.pm.client.send_message(message_object.channel, "", embed=em)
项目:pineapple    作者:peter765    | 项目源码 | 文件源码
def post_avatar(self, message_object, user):
        if user.avatar_url is None or user.avatar_url is "":
            await self.pm.clientWrap.send_message(self.name, message_object.channel,
                                                  user.display_name + " has no avatar set!")
            return

        em = discord.Embed(description="Avatar for " + user.display_name,
                           colour=self.pm.clientWrap.get_color(self.name))
        em.set_image(url=user.avatar_url)
        await self.pm.client.send_message(message_object.channel, "", embed=em)
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def on_status(self, status):
        ## print(status.text)
        if not status.in_reply_to_status_id and status.user.id_str in set([id for feeds in self.feeds.values() for id in feeds]):
            # TODO: Settings for including replies, retweets, etc.
            for channel_id, channel_feeds in self.feeds.items():
                if status.user.id_str in channel_feeds:
                    embed = discord.Embed(title = '@' + status.user.screen_name, url = "https://twitter.com/{}/status/{}".format(status.user.screen_name, status.id), description = status.text, timestamp = status.created_at, color = clients.twitter_color)
                    embed.set_author(name = status.user.name, icon_url = status.user.profile_image_url)
                    embed.set_footer(text = "Twitter", icon_url = clients.twitter_icon_url)
                    channel = self.bot.get_channel(channel_id)
                    if channel:
                        self.bot.loop.create_task(self.bot.send_message(channel, embed = embed))
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def twitter_status(self, ctx, handle : str):
        '''Get twitter status'''
        tweet = clients.twitter_api.user_timeline(handle, count = 1)[0]
        embed = discord.Embed(title = '@' + tweet.user.screen_name, url = "https://twitter.com/{}/status/{}".format(tweet.user.screen_name, tweet.id), description = tweet.text, timestamp = tweet.created_at, color = 0x00ACED)
        avatar = ctx.message.author.default_avatar_url if not ctx.message.author.avatar else ctx.message.author.avatar_url
        embed.set_author(name = ctx.message.author.display_name, icon_url = avatar)
        embed.set_footer(text = tweet.user.name, icon_url = tweet.user.profile_image_url)
        await self.bot.say(embed = embed)
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def help_other(self, ctx):
        '''Additional commands and information'''
        # TODO: Update
        # TODO: Add last updated date?
        embed = discord.Embed(title = "Commands not in {}help".format(ctx.prefix), color = clients.bot_color)
        avatar = ctx.message.author.avatar_url or ctx.message.author.default_avatar_url
        embed.set_author(name = ctx.message.author.display_name, icon_url = avatar)
        embed.description = "See `{}help` for the main commands".format(ctx.prefix)
        embed.add_field(name = "Conversion Commands", value = "see `{}conversions`".format(ctx.prefix), inline = False)
        embed.add_field(name = "In Progress", value = "gofish redditsearch roleposition rolepositions taboo userlimit webmtogif whatis", inline = False)
        embed.add_field(name = "Misc", value = "invite randomgame test test_on_message", inline = False)
        embed.add_field(name = "Owner Only", value = "allcommands changenickname deletetest cleargame clearstreaming echo eval exec load reload repl restart servers setgame setstreaming shutdown unload updateavatar", inline = False)
        embed.add_field(name = "No Prefix", value = "@Harmonbot :8ball: (exactly: f|F) (anywhere in message: getprefix)", inline = False)
        await self.bot.say(embed = embed)
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def benchmark(self):
        '''Benchmark'''
        process = psutil.Process()
        memory = process.memory_info().rss / 2 ** 20
        process.cpu_percent()
        embed = discord.Embed(color = clients.bot_color)
        embed.add_field(name = "RAM", value = "{:.2f} MiB".format(memory))
        embed.add_field(name = "CPU", value = "Calculating CPU usage..")
        message, embed = await self.bot.say(embed = embed)
        await asyncio.sleep(1)
        cpu = process.cpu_percent() / psutil.cpu_count()
        embed.set_field_at(1, name = "CPU", value = "{}%".format(cpu))
        await self.bot.edit_message(message, embed = embed)
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def playingr_processr(self, ctx, reaction, user):
        if reaction.emoji in self.controls:
            if self.controls[reaction.emoji] == "pause_resume":
                if utilities.get_permission(ctx, "pause", id = user.id) or user == ctx.message.server.owner or user.id == clients.owner_id:
                    embed = discord.Embed(color = clients.bot_color).set_author(name = user.display_name, icon_url = user.avatar_url or user.default_avatar_url)
                    try:
                        self.bot.cogs["Audio"].players[ctx.message.server.id].pause()
                    except errors.AudioNotPlaying:
                        embed.description = ":no_entry: There is no song to pause"
                    except errors.AudioAlreadyDone:
                        self.bot.cogs["Audio"].players[ctx.message.server.id].resume()
                        embed.description = ":play_pause: Resumed song"
                    else:
                        embed.description = ":pause_button: Paused song"
                    await self.bot.send_message(ctx.message.channel, embed = embed)
                    await self.bot.attempt_delete_message(ctx.message)
            elif self.controls[reaction.emoji] in ("skip", "replay", "shuffle", "radio"):
                if utilities.get_permission(ctx, self.controls[reaction.emoji], id = user.id) or user.id in (ctx.message.server.owner.id, clients.owner_id):
                    message = copy.copy(ctx.message)
                    message.content = "{}{}".format(ctx.prefix, self.controls[reaction.emoji])
                    await self.bot.process_commands(message)
                    # Timestamp for radio
            elif self.controls[reaction.emoji] in ("volume_down", "volume_up"):
                if utilities.get_permission(ctx, "volume", id = user.id) or user.id in (ctx.message.server.owner, clients.owner_id):
                    try:
                        current_volume = self.bot.cogs["Audio"].players[ctx.message.server.id].get_volume()
                    except errors.AudioNotPlaying:
                        await self.bot.embed_reply(":no_entry: Couldn't change volume\nThere's nothing playing right now")
                    if self.controls[reaction.emoji] == "volume_down": set_volume = current_volume - 10
                    elif self.controls[reaction.emoji] == "volume_up": set_volume = current_volume + 10
                    message = copy.copy(ctx.message)
                    message.content = "{}volume {}".format(ctx.prefix, set_volume)
                    await self.bot.process_commands(message)
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def serverinfo(self, ctx):
        '''Information about a server'''
        server = ctx.message.server
        embed = discord.Embed(title = server.name, url = server.icon_url, timestamp = server.created_at, color = clients.bot_color)
        avatar = ctx.message.author.avatar_url or ctx.message.author.default_avatar_url
        embed.set_author(name = ctx.message.author.display_name, icon_url = avatar)
        embed.set_thumbnail(url = server.icon_url)
        embed.add_field(name = "Owner", value = server.owner.mention)
        embed.add_field(name = "ID", value = server.id)
        embed.add_field(name = "Region", value = str(server.region))
        embed.add_field(name = "Roles", value = len(server.roles))
        channel_types = [c.type for c in server.channels]
        text_count = channel_types.count(discord.ChannelType.text)
        voice_count = channel_types.count(discord.ChannelType.voice)
        embed.add_field(name = "Channels", value = "{} text\n{} voice".format(text_count, voice_count))
        embed.add_field(name = "Members", value = "{}\n({} bots)".format(server.member_count, sum(m.bot for m in server.members)))
        embed.add_field(name = "AFK Timeout", value = "{:g} min.".format(server.afk_timeout / 60))
        embed.add_field(name = "AFK Channel", value = str(server.afk_channel))
        embed.add_field(name = "Verification Level", value = str(server.verification_level).capitalize())
        embed.add_field(name = "2FA Requirement", value = bool(server.mfa_level))
        embed.add_field(name = "Default Channel", value = server.default_channel.mention)
        if server.emojis:
            emojis = [str(emoji) for emoji in server.emojis]
            if len(' '.join(emojis)) <= 1024:
                embed.add_field(name = "Emojis", value = ' '.join(emojis), inline = False)
            else:
                embed.add_field(name = "Emojis", value = ' '.join(emojis[:len(emojis) // 2]), inline = False)
                embed.add_field(name = "Emojis", value = ' '.join(emojis[len(emojis) // 2:]), inline = False)
        embed.set_footer(text = "Created")
        await self.bot.say(embed = embed)