首页 > 解决方案 > 无法在 webhook 模式下部署 aiogram python bot

问题描述

我已经尝试过这个脚本,它类似于用于 webhook 部署的aiogram 官方示例。

import os
import logging

from aiogram import Bot, Dispatcher, types, executor

PROJECT_NAME = os.environ.get("PROJ")
TOKEN = os.environ.get("TOKEN")

WEBHOOK_HOST = f"https://{PROJECT_NAME}.herokuapp.com"
WEBHOOK_PATH = "/webhook/" + TOKEN
WEBHOOK_URL = f"{WEBHOOK_HOST}{WEBHOOK_PATH}"

WEBAPP_HOST = "localhost"
WEBAPP_PORT = 8443

bot = Bot(TOKEN)
dp = Dispatcher(bot)

logging.basicConfig(level=logging.INFO)


# Example handler
@dp.message_handler(commands="start")
async def start_handler(message: types.Message):
    await bot.send_message(message.chat.id, text="hi")


# Run after startup
async def on_startup():
    await bot.delete_webhook()
    await bot.set_webhook(WEBHOOK_URL)


# Run before shutdown
async def on_shutdown():
    logging.warning("Shutting down..")
    await bot.delete_webhook()
    await dp.storage.close()
    await dp.storage.wait_closed()
    logging.warning("Bot down")


if __name__ == "__main__":
    if "HEROKU" in list(os.environ.keys()):
        executor.start_webhook(
            dispatcher=dp,
            webhook_path=WEBHOOK_PATH,
            on_startup=on_startup,
            on_shutdown=on_shutdown,
            skip_updates=True,
            host=WEBAPP_HOST,
            port=WEBAPP_PORT,
        )
    else:
        executor.start_polling(dp)

轮询工作了几秒钟,然后崩溃了。

我已将环境变量设置如下:

TOKEN(来自 BotFather 的令牌),PROJ(Heroku 项目的名称)

AND HEROKU(无价值)

部署后,

2020-11-21T16:06:33.939710+00:00 heroku[web.1]: State changed from crashed to starting
2020-11-21T16:06:38.339135+00:00 heroku[web.1]: Starting process with command `python bot.py`
2020-11-21T16:06:42.115941+00:00 heroku[web.1]: Process exited with status 1
2020-11-21T16:06:42.169072+00:00 heroku[web.1]: State changed from starting to crashed
2020-11-21T16:06:41.819141+00:00 app[web.1]: INFO:aiogram:Bot: AahnikTester [@aahniks_tester_bot]
2020-11-21T16:06:41.987742+00:00 app[web.1]: WARNING:aiogram:Updates were skipped successfully.
2020-11-21T16:06:41.990985+00:00 app[web.1]: ERROR:asyncio:unhandled exception during asyncio.run() shutdown
2020-11-21T16:06:41.990986+00:00 app[web.1]: task: <Task finished name='Task-6' coro=<_run_app() done, defined at /app/.heroku/python/lib/python3.8/site-packages/aiohttp/web.py:287> exception=TypeError('on_startup() takes 0 positional arguments but 1 was given')>
2020-11-21T16:06:41.990986+00:00 app[web.1]: Traceback (most recent call last):
2020-11-21T16:06:41.990987+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.8/site-packages/aiohttp/web.py", line 508, in run_app
2020-11-21T16:06:41.990987+00:00 app[web.1]:     loop.run_until_complete(main_task)
2020-11-21T16:06:41.990988+00:00 app[web.1]:   File "uvloop/loop.pyx", line 1456, in uvloop.loop.Loop.run_until_complete
2020-11-21T16:06:41.990988+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.8/site-packages/aiohttp/web.py", line 319, in _run_app
2020-11-21T16:06:41.990989+00:00 app[web.1]:     await runner.setup()
2020-11-21T16:06:41.990990+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.8/site-packages/aiohttp/web_runner.py", line 275, in setup
2020-11-21T16:06:41.990990+00:00 app[web.1]:     self._server = await self._make_server()
2020-11-21T16:06:41.990990+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.8/site-packages/aiohttp/web_runner.py", line 375, in _make_server
2020-11-21T16:06:41.990991+00:00 app[web.1]:     await self._app.startup()
2020-11-21T16:06:41.990991+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.8/site-packages/aiohttp/web_app.py", line 416, in startup
2020-11-21T16:06:41.990992+00:00 app[web.1]:     await self.on_startup.send(self)
2020-11-21T16:06:41.990992+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.8/site-packages/aiohttp/signals.py", line 34, in send
2020-11-21T16:06:41.990993+00:00 app[web.1]:     await receiver(*args, **kwargs)  # type: ignore
2020-11-21T16:06:41.990993+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.8/site-packages/aiogram/utils/executor.py", line 250, in _wrap_callback
2020-11-21T16:06:41.990993+00:00 app[web.1]:     return await cb(self.dispatcher)
2020-11-21T16:06:41.990994+00:00 app[web.1]: TypeError: on_startup() takes 0 positional arguments but 1 was given
2020-11-21T16:06:41.991678+00:00 app[web.1]: Traceback (most recent call last):
2020-11-21T16:06:41.991741+00:00 app[web.1]:   File "bot.py", line 45, in <module>
2020-11-21T16:06:41.992057+00:00 app[web.1]:     executor.start_webhook(
2020-11-21T16:06:41.992112+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.8/site-packages/aiogram/utils/executor.py", line 98, in start_webhook
2020-11-21T16:06:41.992386+00:00 app[web.1]:     executor.run_app(**kwargs)
2020-11-21T16:06:41.992389+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.8/site-packages/aiogram/utils/executor.py", line 282, in run_app
2020-11-21T16:06:41.992703+00:00 app[web.1]:     web.run_app(self._web_app, **kwargs)
2020-11-21T16:06:41.992706+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.8/site-packages/aiohttp/web.py", line 508, in run_app
2020-11-21T16:06:41.993089+00:00 app[web.1]:     loop.run_until_complete(main_task)
2020-11-21T16:06:41.993090+00:00 app[web.1]:   File "uvloop/loop.pyx", line 1456, in uvloop.loop.Loop.run_until_complete
2020-11-21T16:06:41.993309+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.8/site-packages/aiohttp/web.py", line 319, in _run_app
2020-11-21T16:06:41.993604+00:00 app[web.1]:     await runner.setup()
2020-11-21T16:06:41.993607+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.8/site-packages/aiohttp/web_runner.py", line 275, in setup
2020-11-21T16:06:41.993862+00:00 app[web.1]:     self._server = await self._make_server()
2020-11-21T16:06:41.993865+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.8/site-packages/aiohttp/web_runner.py", line 375, in _make_server
2020-11-21T16:06:41.994180+00:00 app[web.1]:     await self._app.startup()
2020-11-21T16:06:41.994186+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.8/site-packages/aiohttp/web_app.py", line 416, in startup
2020-11-21T16:06:41.994510+00:00 app[web.1]:     await self.on_startup.send(self)
2020-11-21T16:06:41.994534+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.8/site-packages/aiohttp/signals.py", line 34, in send
2020-11-21T16:06:41.994724+00:00 app[web.1]:     await receiver(*args, **kwargs)  # type: ignore
2020-11-21T16:06:41.994724+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.8/site-packages/aiogram/utils/executor.py", line 250, in _wrap_callback
2020-11-21T16:06:41.994977+00:00 app[web.1]:     return await cb(self.dispatcher)
2020-11-21T16:06:41.995020+00:00 app[web.1]: TypeError: on_startup() takes 0 positional arguments but 1 was given

我正在寻找使用 webhook 将 aiogram 部署到 heroku 的示例。

通过对上面的代码进行一些调整,这就是

2020-11-26T09:32:27.283413+00:00 app[web.1]: WARNING:aiogram:Updates were skipped successfully.
2020-11-26T09:32:27.283425+00:00 app[web.1]: WARNING:root:Starting webhook
2020-11-26T09:32:27.455462+00:00 app[web.1]: WARNING:root:Webhook set
2020-11-26T09:32:27.457534+00:00 app[web.1]: ======== Running on http://localhost:8443 ========
2020-11-26T09:32:27.457535+00:00 app[web.1]: (Press CTRL+C to quit)
2020-11-26T09:33:23.679946+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch

如何解决这个问题?(在heroku中)

与其他一些调整

由于电报正在发送更新,因此 webhook 设置正确。但他们没有被处理。这就是为什么另一个错误来了。

2020-11-26T09:52:48.395734+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=POST path="/webhook/secret_key..." host=radiant-caverns-48683.herokuapp.com

标签: pythonherokutelegramtelegram-bot

解决方案


感谢@evgfilim1@AsyncAwait在 aiogram 的电报组上帮助我。

要点:

  1. 在 async def on_startup(): 和 async def on_shutdown(): 需要 dispatcher: Dispatcher

例子:

from aiogram import Dispatcher

async def on_startup(dispatcher: Dispatcher) -> None:
  1. 使用int(os.getenv("PORT"))代替8443

  2. 尝试绑定到0.0.0.0而不是localhost

这是一个使用 webhook 获取 Heroku 更新的 aiogram bot 部署的完整示例

https://github.com/aahnik/webhook-aiogram-heroku


推荐阅读