当前位置: 首页>>代码示例>>Python>>正文


Python discord.py方法代码示例

本文整理汇总了Python中discord.py方法的典型用法代码示例。如果您正苦于以下问题:Python discord.py方法的具体用法?Python discord.py怎么用?Python discord.py使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在discord的用法示例。


在下文中一共展示了discord.py方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: wait_for_reaction_remove

# 需要导入模块: import discord [as 别名]
# 或者: from discord import py [as 别名]
def wait_for_reaction_remove(bot, emoji=None, *, user=None,
                                   timeout=None, message=None, check=None):
    """Waits for a reaction to be removed by a user from a message within a time period.
    Made to act like other discord.py wait_for_* functions but is not fully implemented.

    Because of that, wait_for_reaction_remove(self, emoji: list, user, message, timeout=None)
    is a better representation of this function's def

    returns the actual event or None if timeout
    """
    if not (emoji and message) or isinstance(emoji, str):
        raise NotImplementedError("wait_for_reaction_remove(self, emoji, "
                                  "message, user=None, timeout=None, "
                                  "check=None) is a better representation "
                                  "of this function definition")
    remove_event = ReactionRemoveEvent(emoji, user, check=check)
    _reaction_remove_events[message.id] = remove_event
    done, pending = await asyncio.wait([remove_event.wait()],
                                       timeout=timeout)
    res = _reaction_remove_events.pop(message.id)
    try:
        return done.pop().result() and res
    except:
        return None 
开发者ID:irdumbs,项目名称:Dumb-Cogs,代码行数:26,代码来源:repl.py

示例2: show_version

# 需要导入模块: import discord [as 别名]
# 或者: from discord import py [as 别名]
def show_version():
    entries = []

    entries.append('- Python v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(sys.version_info))
    version_info = discord.version_info
    entries.append('- discord.py v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(version_info))
    if version_info.releaselevel != 'final':
        pkg = pkg_resources.get_distribution('discord.py')
        if pkg:
            entries.append('    - discord.py pkg_resources: v{0}'.format(pkg.version))

    entries.append('- aiohttp v{0.__version__}'.format(aiohttp))
    entries.append('- websockets v{0.__version__}'.format(websockets))
    uname = platform.uname()
    entries.append('- system info: {0.system} {0.release} {0.version}'.format(uname))
    print('\n'.join(entries)) 
开发者ID:Rapptz,项目名称:discord.py,代码行数:18,代码来源:__main__.py

示例3: cleanup_code

# 需要导入模块: import discord [as 别名]
# 或者: from discord import py [as 别名]
def cleanup_code(content: str) -> str:
    """
    Automatically removes code blocks from the code.

    Parameters
    ----------
    content : str
        The content to be cleaned.

    Returns
    -------
    str
        The cleaned content.
    """
    # remove ```py\n```
    if content.startswith("```") and content.endswith("```"):
        return "\n".join(content.split("\n")[1:-1])

    # remove `foo`
    return content.strip("` \n") 
开发者ID:kyb3r,项目名称:modmail,代码行数:22,代码来源:utils.py

示例4: botinfo

# 需要导入模块: import discord [as 别名]
# 或者: from discord import py [as 别名]
def botinfo(ctx, **_):
    """
    [CMD_KEY]botinfo

    General information about DueUtil.
    """

    info_embed = discord.Embed(title="DueUtil's Information", type="rich", color=gconf.DUE_COLOUR)
    info_embed.description = "DueUtil is customizable bot to add fun commands, quests and battles to your server."
    info_embed.add_field(name="Created by", value="[MacDue#4453](https://dueutil.tech/)")
    info_embed.add_field(name="Framework",
                         value="[discord.py %s :two_hearts:](http://discordpy.readthedocs.io/en/latest/)"
                               % discord.__version__)
    info_embed.add_field(name="Version", value=gconf.VERSION),
    info_embed.add_field(name="Invite Due!", value="https://dueutil.tech/invite", inline=False)
    info_embed.add_field(name="Support server",
                         value="For help with the bot or a laugh join **https://discord.gg/n4b94VA**!")
    await util.say(ctx.channel, embed=info_embed) 
开发者ID:MacDue,项目名称:DueUtil,代码行数:20,代码来源:util.py

示例5: about

# 需要导入模块: import discord [as 别名]
# 或者: from discord import py [as 别名]
def about(self, ctx):
        """Infos about the SelfBot."""
        embed = discord.Embed()
        embed.set_author(name="Igneel's SelfBot", url="https://igneeldxd.github.io/Discord-SelfBot/")
        embed.description = "https://igneeldxd.github.io/Discord-SelfBot/\nThis is a Selfbot written by IgneelDxD#6666\nFor support or feedback you can join my [Server](https://discord.gg/DJK8h3n)"
        embed.colour = discord.Color.purple()

        async with aiohttp.ClientSession() as cs:
            async with cs.get("https://api.github.com/repos/IgneelDxD/Discord-SelfBot/commits") as resp:
                result = json.loads(await resp.text())
                form = '[``{0}``](https://github.com/IgneelDxD/Discord-SelfBot/commit/{0}) {1} ({2})'
                com0 = form.format(result[0]['sha'][:7], result[0]['commit']['message'], getAgo(parser.parse(result[0]['commit']['author']['date'], ignoretz=True)))
                com1 = form.format(result[1]['sha'][:7], result[1]['commit']['message'], getAgo(parser.parse(result[1]['commit']['author']['date'], ignoretz=True)))
                embed.add_field(name='Latest Changes', value=f'{com0}\n{com1}')
        embed.set_thumbnail(url="https://i.imgur.com/cD51k3R.png")
        embed.set_footer(text='Made with discord.py | rewrite is the future!', icon_url='https://i.imgur.com/MyEXmz8.png')
        await edit(ctx, embed=embed)

    # User info on Server 
开发者ID:lehnification,项目名称:Discord-SelfBot,代码行数:21,代码来源:info.py

示例6: local_perms

# 需要导入模块: import discord [as 别名]
# 或者: from discord import py [as 别名]
def local_perms(self, guild: discord.Guild, author: discord.Member) -> bool:
        """Check the user is/isn't locally whitelisted/blacklisted.
            https://github.com/Cog-Creators/Red-DiscordBot/blob/V3/release/3.0.0/redbot/core/global_checks.py
        """
        try:
            return await self.bot.allowed_by_whitelist_blacklist(
                author, who_id=author.id, guild_id=guild.id, role_ids=[r.id for r in author.roles]
            )
        except AttributeError:
            if await self.bot.is_owner(author):
                return True
            elif guild is None:
                return True
            guild_settings = self.bot.db.guild(guild)
            local_blacklist = await guild_settings.blacklist()
            local_whitelist = await guild_settings.whitelist()

            _ids = [r.id for r in author.roles if not r.is_default()]
            _ids.append(author.id)
            if local_whitelist:
                return any(i in local_whitelist for i in _ids)

            return not any(i in local_blacklist for i in _ids) 
开发者ID:TrustyJAID,项目名称:Trusty-cogs,代码行数:25,代码来源:api.py

示例7: member_can_run

# 需要导入模块: import discord [as 别名]
# 或者: from discord import py [as 别名]
def member_can_run(self, ctx: commands.Context) -> bool:
        """Check if a user can run a command.
        This will take the current context into account, such as the
        server and text channel.
        https://github.com/Cog-Creators/Red-DiscordBot/blob/V3/release/3.0.0/redbot/cogs/permissions/permissions.py
        """
        command = ctx.message.content.replace(ctx.prefix, "")
        com = ctx.bot.get_command(command)
        if com is None:
            return False
        else:
            try:
                testcontext = await ctx.bot.get_context(ctx.message, cls=commands.Context)
                to_check = [*reversed(com.parents)] + [com]
                can = False
                for cmd in to_check:
                    can = await cmd.can_run(testcontext)
                    if can is False:
                        break
            except commands.CheckFailure:
                can = False
        return can 
开发者ID:TrustyJAID,项目名称:Trusty-cogs,代码行数:24,代码来源:eventmixin.py

示例8: on_command_error

# 需要导入模块: import discord [as 别名]
# 或者: from discord import py [as 别名]
def on_command_error(self, error, ctx):
        ignored = (commands.NoPrivateMessage, commands.DisabledCommand, commands.CheckFailure,
                   commands.CommandNotFound, commands.UserInputError, discord.HTTPException)
        error = getattr(error, 'original', error)

        if isinstance(error, ignored):
            return

        if ctx.message.server:
            fmt = 'Channel: {0} (ID: {0.id})\nGuild: {1} (ID: {1.id})'
        else:
            fmt = 'Channel: {0} (ID: {0.id})'

        exc = traceback.format_exception(type(error), error, error.__traceback__, chain=False)
        description = '```py\n%s\n```' % ''.join(exc)
        time = datetime.datetime.utcnow()

        name = ctx.command.qualified_name
        author = '{0} (ID: {0.id})'.format(ctx.message.author)
        location = fmt.format(ctx.message.channel, ctx.message.server)

        message = '{0} at {1}: Called by: {2} in {3}. More info: {4}'.format(name, time, author, location, description)

        self.bot.logs['discord'].critical(message) 
开发者ID:rauenzi,项目名称:discordbot.py,代码行数:26,代码来源:meta.py

示例9: repl_format_source

# 需要导入模块: import discord [as 别名]
# 或者: from discord import py [as 别名]
def repl_format_source(self, thing):
        """returns get_source formatted to be used in repl

        rtfs originated as this alias:
        debug (lambda cmd, bot=bot: (lambda f, out: out[0] if len(out) == 1 else (f(f,out[1:5] + (['{} more pages remaining..\njust tell them to read the actual source file man.'.format(len(out)-5)] if len(out) > 5 else [])) or out[0]))((lambda self, more: None if not more else bot.loop.create_task(bot.say('``'+'`py\n'+more.pop(0)+'``'+'`')).add_done_callback(self(self, more))), list(pagify((lambda ic, fc, pg: (lambda fcs: ic.getsourcefile(fc).split('/')[-1]+'\nline: {}'.format(fcs[1])+'``'+'`'+'\n'+'``'+'`py\n'+''.join(fcs[0]))(ic.getsourcelines(fc)))(__import__('inspect'), (cmd if not isinstance(cmd, str) else (lambda f, ms: f(f, __import__(ms.pop(0)), ms))((lambda f, prev, ms: getattr(prev, 'callback') if hasattr(prev, 'callback') else prev if not ms else f(f, getattr(prev, ms.pop(0)), ms)), cmd.split('.')) if '.' in cmd else (lambda end, cmds: end(end, cmds, bot.commands[cmds.pop(0)]).callback)((lambda end, names, cmd: cmd if not names else end(end, names, cmd.commands[names.pop(0)])), cmd.split()) ), __import__('cogs').utils.chat_formatting.pagify), delims=['\n', ' '], escape=False, shorten_by=12)) ))
        """
        source = self.get_source(thing)
        msg =  source.filename.split('/')[-1] + '\n'
        msg += 'line: {}'.format(source.line_number)
        msg += '``'+'`\n`'+'``py\n'  # codeblock break
        msg += source.source
        return msg 
开发者ID:irdumbs,项目名称:Dumb-Cogs,代码行数:14,代码来源:repl.py

示例10: cleanup_code

# 需要导入模块: import discord [as 别名]
# 或者: from discord import py [as 别名]
def cleanup_code(self, content):
        """Automatically removes code blocks from the code."""
        # remove ```py\n```
        if content.startswith('```') and content.endswith('```'):
            return '\n'.join(content.split('\n')[1:-1])

        # remove `foo`
        for p in self.settings["REPL_PREFIX"]:
            if content.startswith(p):
                if p == '`':
                    return content.strip('` \n')
                content = content[len(p):]
                return content.strip(' \n') 
开发者ID:irdumbs,项目名称:Dumb-Cogs,代码行数:15,代码来源:repl.py

示例11: get_syntax_error

# 需要导入模块: import discord [as 别名]
# 或者: from discord import py [as 别名]
def get_syntax_error(self, e):
        return '```py\n{0.text}{1:>{0.offset}}\n{2}: {0}```'.format(e, '^', type(e).__name__) 
开发者ID:irdumbs,项目名称:Dumb-Cogs,代码行数:4,代码来源:repl.py

示例12: print_results

# 需要导入模块: import discord [as 别名]
# 或者: from discord import py [as 别名]
def print_results(self, ctx, results):
        msg = ctx.message
        nbs = '​'
        discord_fmt = nbs + '```py\n{}\n```'
        is_interactive = self.settings["OUTPUT_REDIRECT"] == "pages"
        res_len = len(discord_fmt.format(results))
        if is_interactive and res_len > self.settings["PAGES_LENGTH"]:
            single_msg = not self.settings["MULTI_MSG_PAGING"]
            page = self.pagify_interactive_results(ctx, results, single_msg=single_msg)
            self.bot.loop.create_task(page)
        elif res_len > 2000:
            if self.settings["OUTPUT_REDIRECT"] == "pm":
                await self.bot.send_message(msg.channel, 'Content too big. Check your PMs')
                enough_paper = self.settings["PM_PAGES"]
                for page in pagify(results, ['\n', ' '], shorten_by=12):
                    await self.bot.send_message(msg.author, discord_fmt.format(page))
                    enough_paper -= 1
                    if not enough_paper:
                        await self.bot.send_message(msg.author,
                                                    "**Too many pages! Think of the trees!**")
                        return
            elif self.settings["OUTPUT_REDIRECT"] == "console":
                await self.bot.send_message(msg.channel, 'Content too big. Check your console')
                print(results)
            else:
                await self.bot.send_message(msg.channel, 'Content too big. Writing to file')
                with open(self.output_file, 'w') as f:
                    f.write(results)
                open_cmd = self.settings["OPEN_CMD"]
                if open_cmd:
                    subprocess.Popen([open_cmd, self.output_file])
        else:

            await self.bot.send_message(msg.channel, discord_fmt.format(results)) 
开发者ID:irdumbs,项目名称:Dumb-Cogs,代码行数:36,代码来源:repl.py

示例13: page_results

# 需要导入模块: import discord [as 别名]
# 或者: from discord import py [as 别名]
def page_results(self, results, single_msg=True):
        nbs = '​'
        discord_fmt = nbs + '```py\n{}\n```'
        prompt = ("  Output too long. Navigate pages with ({}close/next)"
                  .format('' if single_msg else 'prev/'))

        pages = [p for p in pagify(results, ['\n', ' '],
                                   page_length=self.settings["PAGES_LENGTH"])]
        # results is not a generator, so no reason to keep this as one
        pages = [discord_fmt.format(p) + 'pg. {}/{}'
                 .format(c + 1, len(pages))
                 for c, p in enumerate(pages)]
        pages[0] += prompt
        return pages 
开发者ID:irdumbs,项目名称:Dumb-Cogs,代码行数:16,代码来源:repl.py

示例14: clear

# 需要导入模块: import discord [as 别名]
# 或者: from discord import py [as 别名]
def clear(self) -> None:
        """
        Clears the internal state of the bot and recreates the connector and sessions.

        Will cause a DeprecationWarning if called outside a coroutine.
        """
        # Because discord.py recreates the HTTPClient session, may as well follow suit and recreate
        # our own stuff here too.
        self._recreate()
        super().clear() 
开发者ID:python-discord,项目名称:bot,代码行数:12,代码来源:bot.py

示例15: newbot

# 需要导入模块: import discord [as 别名]
# 或者: from discord import py [as 别名]
def newbot(parser, args):
    new_directory = to_path(parser, args.directory) / to_path(parser, args.name)

    # as a note exist_ok for Path is a 3.5+ only feature
    # since we already checked above that we're >3.5
    try:
        new_directory.mkdir(exist_ok=True, parents=True)
    except OSError as exc:
        parser.error('could not create our bot directory ({})'.format(exc))

    cogs = new_directory / 'cogs'

    try:
        cogs.mkdir(exist_ok=True)
        init = cogs / '__init__.py'
        init.touch()
    except OSError as exc:
        print('warning: could not create cogs directory ({})'.format(exc))

    try:
        with open(str(new_directory / 'config.py'), 'w', encoding='utf-8') as fp:
            fp.write('token = "place your token here"\ncogs = []\n')
    except OSError as exc:
        parser.error('could not create config file ({})'.format(exc))

    try:
        with open(str(new_directory / 'bot.py'), 'w', encoding='utf-8') as fp:
            base = 'Bot' if not args.sharded else 'AutoShardedBot'
            fp.write(bot_template.format(base=base, prefix=args.prefix))
    except OSError as exc:
        parser.error('could not create bot file ({})'.format(exc))

    if not args.no_git:
        try:
            with open(str(new_directory / '.gitignore'), 'w', encoding='utf-8') as fp:
                fp.write(gitignore_template)
        except OSError as exc:
            print('warning: could not create .gitignore file ({})'.format(exc))

    print('successfully made bot at', new_directory) 
开发者ID:Rapptz,项目名称:discord.py,代码行数:42,代码来源:__main__.py


注:本文中的discord.py方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。