首页 > 解决方案 > Discord.py:如何创建自定义函数 notify 和 call 触发 discord 客户端调用它

问题描述

我想要求一个不和谐的客户端执行一个特定的功能,而不会被一个 on 消息触发,或者 on ready 或者有一个重复自身的 LOOP。

基本上,我想要一个函数 notify(msg) 并使不和谐客户端向频道发送消息

我尝试了以下但没有成功

async notify(message, client):
    await client.wait_until_ready()
    channel = client.get_channel(os.getenv('CHANNEL_ID'))
    await channel.send(message)

client.run(os.getenv('CLIENT_TOKEN'))

# Notice that I try to run the task after the client run
# Because I may call notify multiple times after the client has been created

client.loop.create_task(notify())

我想在创建客户端后调用此函数,并且不会无限循环。

也尝试运行

asyn def main():
    await client.connect()
    await client.log(client.run(os.getenv('CLIENT_TOKEN')))
    await notify('My message', client)

# then

if __name__ = "__main__":
  asyncio.run(main())

这只是不运行...... http 请求有错误等等。

标签: python-3.xdiscord.pypython-asyncio

解决方案


client.loop.create_task(notify(*args))

传递要在客户端循环中执行的函数,并且只要您愿意,它只会被调用一次。


推荐阅读