其他文件中的异步事件

时间:2018-11-15 16:05:26

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

我正在使用discord.py API创建一个discord机器人。做完一些编码后,我意识到我应该保持代码整洁,并将命令和事件保存在单独的.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)

1 个答案:

答案 0 :(得分:0)

您需要将扩展​​名加载到创建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))
相关问题