在Python中同时使用Discord bot和bottle [英] Discord bot and bottle in the same time in Python

查看:49
本文介绍了在Python中同时使用Discord bot和bottle的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我正在尝试为带有瓶子的机器人做一个API,以使用 http://localhost:8080/say/serverId/channelId/Message
我尝试成功打印带有url和bottle的消息,并且我有一个Discord机器人,现在我必须将两者融合.因此,我想在同一脚本中同时运行bottle和discord.我进行了搜索,发现有线程,ipc等...但是这些解决方案看起来很难,我是一个初学者.
那么,您有简单的解决方案吗?我尝试过


I'm trying to do an API for a bot with bottle to use commands like http://localhost:8080/say/serverId/channelId/Message
I tried successfully to print a message with url and bottle and I have a Discord bot, now I must fusion the two. So I want to run bottle and discord in the same time, in the same script. I searched and there is threading, ipc etc ... But theses solutions looks hard I'm a beginner.
So do you have simple solution to do this ? I tried

bot.run(token)
bottle.run(host="localhost", port=8080)

但是机器人启动了,我必须使用 CTRL + C 停止它以启动瓶子.另外,如果您有一个更简单的解决方案但有2个脚本,为什么不这样做,但是我需要瓶子脚本中的bot变量来发送消息
谢谢!

but the bot starts and I must stop it with CTRL + C to start bottle. Also if you have a simpler solution but with 2 scripts why not but I need the bot variable in the bottle's script to send the message
Thank you !

推荐答案

这里的问题是 bottle.py 是基于阻塞代码的WSGI框架,而 discord.py 是使用事件循环的 asyncio 异步非阻塞库.

The problem here is that bottle.py is a WSGI framework based on blocking code, while discord.py is a asyncio asynchronous non-blocking library that uses an event loop.

您的选择是:

  • 删除 bottle ,转而使用其他一些实际上是异步的Web框架(例如, sanic ).

  • remove bottle in favor of some other web framework that is actually asynchronous (for example, grole or sanic).

使用诸如 aiobottle 之类的包装器以某种方式制作瓶子与asyncio玩得很好(或自己制作).

Use some wrapper like aiobottle to somehow make bottle play nice with asyncio (or make your own).

我会选择第一个选项.

在使用了一些兼容的框架或包装器之后,您应该只启动一次事件循环,因为它将对两个应用程序都起作用.这意味着您不能同时调用两个 run 方法.

After using some compatible framework or wrapper, you should start the event loop only once, as it will serve for both applications. That means you can't call both run methods.

示例,用于sanic:

Example, for sanic:

# `bot.run` starts the event loop, avoid it and use `bot.start` instead
bot_app = bot.start(token)
bot_task = asyncio.ensure_future(bot_app)

# create the sanic app server, but without starting it:
webserver = app.create_server(host="0.0.0.0", port=8080)
webserver_task = asyncio.ensure_future(webserver)

#finally, start the event loop:
loop = asyncio.get_event_loop()
loop.run_forever() # runs both tasks at the same time

这篇关于在Python中同时使用Discord bot和bottle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆