Bot Telegram1 phút để đọc

Làm sao để host bot aiogram hoặc python-telegram-bot 24/7?

Chạy bot Telegram Python viết bằng aiogram hoặc python-telegram-bot trên một worker luôn bật: tệp, thư viện phụ thuộc, biến token và phản hồi đầu tiên.

Chạy nó như một worker polling

Hãy dùng host giữ một tiến trình Python luôn chạy và cài requirements của bạn. Trên Bothosting, hãy chọn hồ sơ bot polling Python, tải main.py và requirements.txt lên, lưu token BotFather thành TELEGRAM_BOT_TOKEN rồi khởi động. Không cần tên miền hay cổng mở. Spark chạy miễn phí với 256 MB RAM, gia hạn mỗi 7 ngày.

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()

Khởi động và kiểm tra câu trả lời

  1. Tạo triển khai bằng hồ sơ bot polling Python. Tải cả hai tệp lên thư mục gốc và đặt MAIN_FILE thành main.py.
  2. Lưu TELEGRAM_BOT_TOKEN vào Biến và khởi động triển khai.
  3. Dừng mọi bản sao trên laptop, rồi gửi /start từ điện thoại.

Nếu không có gì tới và nhật ký hiện lỗi xung đột, một tiến trình khác hoặc webhook đang dùng token. Xem chuyển từ webhook sang polling. Để giữ trạng thái qua các lần khởi động lại, xem cách nhớ cuộc trò chuyện.