【问题标题】:Discord bot and bottle in the same time in Python在 Python 中同时使用 Discord bot 和 Bottle
【发布时间】:2018-09-20 03:37:43
【问题描述】:


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

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

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

【问题讨论】:

    标签: python bottle discord.py discord.py-rewrite


    【解决方案1】:

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

    您的选择是:

    • 删除 bottle 以支持其他一些实际上是异步的 Web 框架(例如,grolesanic)。

    • 使用诸如 aiobottle 之类的包装器以某种方式使瓶子与 asyncio 配合使用(或自己制作)。

    我会选择第一个选项。

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

    例如,对于 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
    

    【讨论】:

    • 我会看到 grole 和 sanic 但瓶子是如此简单:/ 这两个选项看起来很酷
    • 现在我对 Sanic 也有同样的问题
    • @user211593 我在答案中添加了如何用 sanic 解决问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 2021-07-18
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多