Telegram ボット読了 1 分

aiogram や python-telegram-bot のボットを 24 時間動かすには?

aiogram または python-telegram-bot で作った Python の Telegram ボットを常時稼働のワーカーで動かします。ファイル、依存関係、トークンの変数、最初の返信までを説明します。

ポーリングのワーカーとして実行する

Python プロセスを動かし続け、requirements をインストールするホストを使います。Bothosting では Python のポーリングボットのプロファイルを選び、main.py と requirements.txt をアップロードし、BotFather のトークンを TELEGRAM_BOT_TOKEN として保存して起動します。ドメインも開いたポートも不要です。Spark は 256 MB RAM で無料実行し、7 日ごとに更新します。

aiogram 3

requirements.txt
aiogram>=3.13
main.py
import asyncio, os
from aiogram import Bot, Dispatcher
from aiogram.filters import CommandStart
from aiogram.types import Message

dp = Dispatcher()

@dp.message(CommandStart())
async def start(message: Message):
    await message.answer('Hosted and running.')

async def main():
    bot = Bot(os.environ['TELEGRAM_BOT_TOKEN'])
    await dp.start_polling(bot)

asyncio.run(main())

python-telegram-bot 21+

requirements.txt
python-telegram-bot>=21
main.py
import os
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text('Hosted and running.')

app = Application.builder().token(os.environ['TELEGRAM_BOT_TOKEN']).build()
app.add_handler(CommandHandler('start', start))
app.run_polling()

起動して返信を確認する

  1. Python ポーリングボットのプロファイルでデプロイを作成します。両方のファイルをルートにアップロードし、MAIN_FILE を main.py に設定します。
  2. TELEGRAM_BOT_TOKEN を変数に保存して、デプロイを起動します。
  3. ノート PC 上のコピーはすべて停止し、そのあとスマホから /start を送ります。

何も届かず、ログに競合エラーが出ている場合は、別のプロセスか webhook がトークンを使っています。Webhook から polling への切り替え を参照してください。再起動をまたいで状態を保つには、会話を覚えておく方法 を参照してください。