首页 > 解决方案 > Discord.py Bot - `if` 命令和`async def` 有什么区别?

问题描述

我见过许多开发人员以两种方式为 Discord 编写 Python 机器人。

其中一些使用:

if message.content.startswith("command"):
    await message.channel.send("text")

而其他人(大多数)使用这种方法:

@client.command()
async def command(ctx):
    response = "Text"
    await ctx.send(response)

它们两者之间有什么区别,哪种方法更好/更有效率?

标签: pythondiscordbots

解决方案


使用@client.command()andasync def意味着这些是 a 内的可调用函数coroutine,而if我认为 需要嵌套在某种循环中。

当您client.RUN(TOKEN)启动机器人时,Discord 模块会启动一个asyncio coroutine. 它使用asyncawait允许异步任务管理,请参阅有关协程的 Python 文档有关 wait_for 事件的 Discord.py API 参考


推荐阅读