如何设置 Telegram 机器人自动回复?
· 阅读需 5 分钟
步骤 1:通过 BotFather 创建机器人
- 在 Telegram 中搜索 @BotFather (认准蓝勾认证账号)。
- 发送指令
/newbot
→ 按提示输入机器人名称(如 MyAutoReplyBot)和用户名(必须以 bot 结尾,如 myautoreply_bot)。 - 记录生成的 API Token(格式如
123456789:ABCdefGHIJKL
),后续操作需使用此令牌。
二、技术自建方案:编程实现自动回复
方法 1:使用 Python 编写自动回复脚本
步骤 1:环境配置
- 安装 Python 3.8+ 及依赖库:
pip install python-telegram-bot
步骤 2:编写核心代码
from telegram.ext import Updater, MessageHandler, Filters
def auto_reply(update, context):
message = update.message.text
reply_text = f"已收到您的消息:{message}"
context.bot.send_message(chat_id=update.effective_chat.id, text=reply_text)
def main():
updater = Updater("YOUR_API_TOKEN") # 替换为你的API Token
dispatcher = updater.dispatcher
dispatcher.add_handler(MessageHandler(Filters.text, auto_reply))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
步骤 3:部署与运行
- 本地运行:直接执行脚本
python bot.py
- 服务器部署:使用 systemd 或 Docker 实现后台常驻(参考 Docker 部署示例)
功能扩展
- 关键词触发:在代码中匹配特定关键词(如 "帮助")并返回预设内容
- 多媒体支持:通过
send_photo()
或send_document()
发送图片/文件