python类Embed()的实例源码

lottery.py 文件源码 项目:Jumper-Cogs 作者: Redjumpman 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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)
meta.py 文件源码 项目:Harmonbot 作者: Harmon758 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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))
reactions.py 文件源码 项目:Harmonbot 作者: Harmon758 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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)
twitch.py 文件源码 项目:Harmonbot 作者: Harmon758 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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]]
resources.py 文件源码 项目:Harmonbot 作者: Harmon758 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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
chess.py 文件源码 项目:Harmonbot 作者: Harmon758 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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
clients.py 文件源码 项目:Harmonbot 作者: Harmon758 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)
Announcer.py 文件源码 项目:youtube 作者: FishyFing 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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))
general.py 文件源码 项目:spirit 作者: jgayfer 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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()
serverinfo.py 文件源码 项目:PTSCogs 作者: PlanetTeamSpeakk 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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)
useful.py 文件源码 项目:PTSCogs 作者: PlanetTeamSpeakk 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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.")
logs.py 文件源码 项目:Kurisu-Reswitched 作者: 916253 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
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)
mod_warn.py 文件源码 项目:Kurisu-Reswitched 作者: 916253 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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)
meta.py 文件源码 项目:lagbot 作者: mikevb1 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
owner.py 文件源码 项目:lagbot 作者: mikevb1 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)
misc.py 文件源码 项目:lagbot 作者: mikevb1 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)
images.py 文件源码 项目:lagbot 作者: mikevb1 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)
country.py 文件源码 项目:Socrates 作者: Curlybear 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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)
misc.py 文件源码 项目:Socrates 作者: Curlybear 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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')
Funstuff.py 文件源码 项目:Luna 作者: Moonlington 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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])
Funstuff.py 文件源码 项目:Luna 作者: Moonlington 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
Botrelated.py 文件源码 项目:Luna 作者: Moonlington 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
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
Botrelated.py 文件源码 项目:Luna 作者: Moonlington 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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])
plugin.py 文件源码 项目:globibot 作者: best-coloc-ever 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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))
autohotkey.py 文件源码 项目:AceBot 作者: Run1e 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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)
commands.py 文件源码 项目:AceBot 作者: Run1e 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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)
cog_utils.py 文件源码 项目:Godavaru 作者: Godavaru 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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)
cog_info.py 文件源码 项目:Godavaru 作者: Godavaru 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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)
googl.py 文件源码 项目:GrandeCogs 作者: HarukiGrande 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)
neko.py 文件源码 项目:GrandeCogs 作者: HarukiGrande 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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)


问题


面经


文章

微信
公众号

扫码关注公众号