Build a free crypto price alert bot for Telegram in ~150 lines of Python
本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。
Most “build a Telegram bot” tutorials stop at an echo bot. This one builds something you’d actually leave running: a bot that answers /price BTC ETH with live prices and pings you when a coin crosses a price you set. No API keys (besides your bot token), no database, one file. Full code is below, MIT-licensed, copy it freely.
大多数“构建 Telegram 机器人”的教程都止步于回声机器人。本教程将构建一个你真正会持续运行的程序:一个可以通过 /price BTC ETH 回复实时价格,并在代币达到你设定的价格时提醒你的机器人。无需 API 密钥(除了你的机器人令牌)、无需数据库,仅需一个文件。完整代码见下文,采用 MIT 许可,可自由复制。
What we’re building: /price BTC ETH SOL -> live price + 24h change /alert BTC above 70000 -> one-time alert /alerts -> list your alerts Stack: aiogram 3 (a modern async Telegram bot framework), httpx (async HTTP client), Binance public market data (data-api.binance.vision).
我们要构建的功能:
/price BTC ETH SOL -> 实时价格 + 24 小时涨跌幅
/alert BTC above 70000 -> 一次性价格提醒
/alerts -> 列出你的提醒
技术栈:aiogram 3(现代异步 Telegram 机器人框架)、httpx(异步 HTTP 客户端)、币安公共市场数据(data-api.binance.vision)。
-
Get a bot token: Open Telegram, message @botfather, send /newbot, pick a name and a username ending in bot. BotFather replies with a token like 123456:ABC… Treat it like a password.
-
获取机器人令牌:打开 Telegram,给 @botfather 发送消息,输入
/newbot,选择一个名称和一个以 bot 结尾的用户名。BotFather 会回复一个类似123456:ABC...的令牌。请像对待密码一样妥善保管它。 -
Install: pip install “aiogram>=3.13,<4.0” “httpx>=0.27,<1.0”. Set your environment variable: export TELEGRAM_BOT_TOKEN=123456:your-token. Python 3.11+ recommended.
-
安装:运行
pip install "aiogram>=3.13,<4.0" "httpx>=0.27,<1.0"。设置环境变量:export TELEGRAM_BOT_TOKEN=123456:your-token。建议使用 Python 3.11 或更高版本。 -
Fetch prices: Binance’s 24h ticker endpoint gives last price and 24h % change in one call. We validate symbols with a regex (^[A-Z0-9]{2,10}$) before sending them anywhere, so users can’t inject odd strings into the request.
-
获取价格:币安的 24 小时行情接口可以在一次调用中获取最新价格和 24 小时涨跌幅。我们在发送请求前会使用正则表达式 (^[A-Z0-9]{2,10}$) 验证交易对符号,防止用户在请求中注入异常字符串。
-
The /price command: aiogram 3 uses routers and filters. CommandObject gives you everything after the command. Capping at 5 symbols keeps one message from fanning out into dozens of requests.
-
/price命令:aiogram 3 使用路由器和过滤器。CommandObject可以获取命令之后的所有内容。将查询限制在 5 个符号以内,可以防止单条消息引发过多的请求。 -
Alerts with a background loop: Alerts live in a list of dataclasses. A background task checks prices every 30 seconds. Two details worth copying: Dedupe outbound calls (the set comprehension means 1,000 users watching BTC still costs one request per cycle) and never let one failure kill the loop.
-
带后台循环的提醒功能:提醒存储在数据类列表中。后台任务每 30 秒检查一次价格。有两个值得借鉴的细节:去重出站调用(使用集合推导式意味着即使有 1000 个用户关注 BTC,每个周期也只需发起一次请求)以及确保单次失败不会导致整个循环终止。