【问题标题】:Async events in other file其他文件中的异步事件
【发布时间】:2019-04-18 18:57:09
【问题描述】:

我正在使用 discord.py API 制作一个不和谐机器人。在进行了一些编码之后,我意识到我应该保持代码干净并将命令和事件保存在单独的 .py 文件中。我怎么能做那个事件或命令仍然监听触发器并且在单独的文件中?我试过用import 来做,但它只是导入类。示例命令:

@client.command(pass_context=True) async def kick(ctx, *, member: discord.Member = None): if ctx.message.channel.permissions_for(ctx.message.author).administrator is True: await client.send_message(member, settings.kick_direct) await client.kick(member) await client.say(settings.kick_message + member.mention + settings.kick_message2) else: await client.say(settings.permission_error)

【问题讨论】:

    标签: python asynchronous command python-3.6 discord.py


    【解决方案1】:

    您需要在创建discord.py 客户端的文件中加载扩展。请参见下面的示例。

    bot.py

    from discord.ext import commands
    
    client = commands.Bot(command_prefix='!')
    
    client.load_extension('cog')
    
    @client.event
    async def on_ready():
        print('client ready')
    
    @client.command()
    async def ping():
        await client.say('Pong')
    
    client.run('TOKEN')
    

    cog.py

    from discord.ext import commands
    
    class TestCog:
    
        def __init__(self, bot):
            self.bot = bot
            self.counter = 0
    
        @commands.command()
        async def add(self):
            self.counter += 1
            await self.bot.say('Counter is now %d' % self.counter)
    
    
    def setup(bot):
        bot.add_cog(TestCog(bot))
    

    【讨论】:

    • 它虽然没有做任何事情,但仍然有效。机器人不响应命令。
    • 我已经测试了我这边的代码,它工作正常。您是否将bot.pycog.py 放在同一个文件夹中?
    • 是的,同一个文件夹。
    • 不知道出了什么问题。你有什么输出吗?如果没有,请尝试在两个文件中添加一些打印语句以查看它们是否加载
    • Bot 肯定正在运行,文件已加载,虽然它不执行命令。
    猜你喜欢
    • 2015-08-02
    • 1970-01-01
    • 2014-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多