【问题标题】:Running discord bot alongside twitch bot与 twitch bot 一起运行 discord bot
【发布时间】:2021-07-21 23:43:33
【问题描述】:

我有 twitch bot 和 discord bot。我想通过不和谐控制抽搐机器人,并将一些数据从抽搐机器人发送到不和谐机器人。例如,我会在 discord 中输入“?unload xx”,它会关闭 twitch bot 中的某些功能。另一个例子是,在一些 twitch 事件之后,我会将数据发送到 discord bot,discord bot 会在频道中显示它。我试图运行 discord bot,然后在背景循环中运行 twitch bot,但这没有用。我还尝试为 webhook 设置 http 服务器,但这也不起作用。有什么我想念的吗?我无法解决这个问题。谢谢大家帮忙。

编辑 两者都在 python 中,不同的文件,但导入到主文件并在一个文件中运行。 我正在尝试异步,那是背景中的不和谐机器人和抽搐,但我收到“此事件循环已在运行”错误。 我也在不同的线程中尝试了 discord bot 和 http 服务器,但它的工作非常奇怪,有时没有响应,有时没有事件启动,一段时间后关闭。

这是我尝试过但没有用的线程方式

discord_bot = TestBot(command_prefix="?", intents=discord.Intents.default())
twitch_bot = Bot()

twitch_thread = threading.Thread(target=twitch_bot.run, daemon=True)

twitch_thread.start()
discord_bot.run(TOKEN)

【问题讨论】:

  • 请添加更多信息。两者都在同一个文件中吗?不同的线程?两者都在python中?更具体地说明您的设置和您正在尝试的内容
  • 我已经编辑了问题

标签: python discord.py twitch


【解决方案1】:

根据 discord.py API 参考中的discord.Client.run 部分:

这个函数必须是最后一个调用的函数,因为它是阻塞的。这意味着事件的注册或在此函数调用之后调用的任何内容在它返回之前不会执行。

我建议您使用discord.Client.start 而不是discord.Client.run。它应该与asyncio 一起使用,假设twitch_bot.run 不会像discord.Client.run 那样阻塞。

loop = asyncio.get_event_loop()
loop.create_task(discord_bot.start(TOKEN))
loop.create_task(twitch_bot.run())
loop.run_forever()

【讨论】:

  • 谢谢老兄,这行得通。下次我应该更仔细地阅读文档。
【解决方案2】:

有两种方法可以解决这个问题。

一个正在使用background task.

另一个(我将重点介绍)是使用线程 - 一个内置的(我相信)python 库。


import threading
import twitch_bot, discord_bot

#remember not to add brackets after the funcion name, I do that way too often.
#Setting `daemon` to `True` will make the Twitch bot stay online if the discord one crashes.
t = threading.Thread(target = twitch_bot.main,daemon=True)
t.start()

#here we are calling the main funtion of the discord bot in the current thread; there is no need to create a new one.
discord_bot.main()

【讨论】:

  • 我正在尝试后台任务,但出现“此事件循环已在运行”错误。线程方式给了我同样的错误,“无法关闭正在运行的事件循环”错误。
  • @Lokils 我对后台任务没有太多经验,线程可以用在更多的场景中,所以不妨试试。
  • @Lokils discord.py 有一种“启动”机器人的方法,另一种“运行”事件循环启动机器人的方法。确保使用前者而不是后者。另见stackoverflow.com/a/67309267/2954547
猜你喜欢
  • 2021-07-13
  • 2022-07-05
  • 1970-01-01
  • 2021-06-15
  • 1970-01-01
  • 2021-01-02
  • 2020-07-16
  • 1970-01-01
  • 2017-09-26
相关资源
最近更新 更多