You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Python代码触发Telegram Bot执行命令并获取响应?

问题解决:让Python代码发送的Telegram命令被Bot正确识别

问题原因分析

你的代码存在两个核心问题:

  1. Bot处理器顺序错误:pyTelegramBotAPI会按处理器的注册顺序匹配消息,你把兜底的func=lambda message: True处理器放在了/saludar和/start命令处理器之间,导致所有消息(包括命令)会先被兜底处理器拦截,无法触发对应的命令处理器。
  2. 发送代码的认知错误:调用sendMessage接口后返回的结果是你发送的消息本身的信息,而非Bot的回复,所以你打印的respuesta_del_bot其实是自己发送的/saludar,并不是Bot的响应内容。

解决方案

1. 修复Bot代码的处理器顺序

把兜底的消息处理器移到所有命令处理器的最后,确保命令处理器优先匹配:

BOT_TOKEN = "my token"
bot = telebot.TeleBot(BOT_TOKEN)

@bot.message_handler(commands=['saludar'])
def send_welcome(message):
    bot.reply_to(message, "Hola como han estado?")

@bot.message_handler(commands=['start'])
def start(message):
    bot.reply_to(message,"¡Hola! Soy tu bot de Telegram")

# 移到所有命令处理器之后,作为兜底逻辑
@bot.message_handler(func=lambda message: True)
def handle_programmatic_requests(message):
    if message.text.startswith('/programatica'):
        respuesta = responder_a_solicitud_programatica()
        bot.reply_to(message, respuesta)

def responder_a_solicitud_programatica():
    return "Hola desde el script de Python"

# 启动Bot监听
bot.infinity_polling()

2. 优化发送命令的代码

要获取Bot的回复,不能直接通过sendMessage的返回结果获取,需要监听Bot的更新,以下是两种可行方案:

方案A:使用pyTelegramBotAPI监听回复

修改发送代码,发送命令后监听Bot的更新来获取回复:

import telebot
from telebot.types import Message

BOT_TOKEN = "my token"
chat_id = "my chat id"
command = "/saludar"

bot = telebot.TeleBot(BOT_TOKEN)

# 发送命令
bot.send_message(chat_id, command)

# 监听Bot的回复
@bot.message_handler(func=lambda msg: msg.chat.id == chat_id and msg.reply_to_message is not None)
def get_bot_response(msg: Message):
    print(f"Bot的回复: {msg.text}")
    # 收到回复后停止监听
    bot.stop_polling()

# 启动轮询监听
bot.infinity_polling(timeout=10, long_polling_timeout=5)

方案B:使用Telegram API的getUpdates接口轮询回复

如果不想依赖pyTelegramBotAPI的监听逻辑,也可以用requests轮询获取回复:

import requests
import time

BOT_TOKEN = "my token"
chat_id = "my chat id"
command = "/saludar"

# 发送命令
send_url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
requests.post(send_url, params={"chat_id": chat_id, "text": command})

# 获取初始更新ID,避免重复处理历史消息
update_url = f"https://api.telegram.org/bot{BOT_TOKEN}/getUpdates"
last_update_id = 0

# 轮询等待Bot回复
while True:
    response = requests.get(update_url, params={"offset": last_update_id + 1})
    updates = response.json().get("result", [])
    for update in updates:
        last_update_id = update["update_id"]
        msg = update.get("message")
        # 判断是否是目标聊天的回复消息
        if msg and str(msg["chat"]["id"]) == chat_id and msg.get("reply_to_message"):
            print(f"Bot的回复: {msg['text']}")
            exit()
    time.sleep(1)

验证效果

调整后,先运行Bot代码,再执行发送命令的代码,就能触发/saludar对应的回复,效果和手动输入命令完全一致。

内容的提问来源于stack exchange,提问作者Adrian Cabrera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 07:11:24