【问题标题】:Discord.py Bot - What is the difference between `if` command and `async def`?Discord.py Bot - `if` 命令和`async def` 有什么区别?
【发布时间】:2021-12-04 17:30:30
【问题描述】:

我看到许多开发人员使用两种方式为 Discord 编写 Python 机器人。

其中一些使用:

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

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

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

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

【问题讨论】:

  • 我见过使用第一个的指南和使用后者的指南,我认为第二个是一种更“pythonic”的方式来做同样的事情

标签: python discord bots


【解决方案1】:

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

当您client.RUN(TOKEN) 启动您的机器人时,Discord 模块会启动一个asyncio coroutine。它使用async 和await 来允许异步任务管理,参见the Python documentation on coroutines 和Discord.py API Reference on wait_for events

【讨论】:

    猜你喜欢
    • 2016-06-14
    • 2013-08-11
    • 1970-01-01
    • 2018-12-16
    • 2023-01-26
    • 2019-08-19
    • 2021-08-25
    • 1970-01-01
    相关资源
    最近更新 更多