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

如何在Python主脚本中手动触发Telegram Bot聊天更新?

手动触发Telegram Bot聊天更新的需求

我需要将Telegram Bot集成到Python脚本中,该Bot并非脚本核心功能,因此希望在合适时机手动触发聊天更新。此外,脚本其他部分已使用多线程,担心自动轮询方式会引发冲突。

此前的尝试情况

1. 使用requests直接调用API

用requests发送消息的方式运行正常,但调用getUpdates拉取聊天更新时不稳定,偶尔无法获取新消息,还会丢失部分聊天记录。发送消息的代码如下:

def SendNotification(message):
    TOKEN = <private stuff>
    chat_id = <again private stuff>
    url = f"https://api.telegram.org/bot" + TOKEN + "/sendMessage?chat_id=" + chat_id + "&text=" + message
    requests.get(url).json() # this sends the message

2. 使用python-telegram-bot库

该库的表现更符合需求,但网上能找到的示例都是将Bot作为脚本核心功能,使用run_polling自动轮询更新。我的代码(参考YouTube教程)如下:

from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes, Updater

TOKEN = <PRIVATE>
BOT_USERNAME = <PRIVATE>

async def StartCommand(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("Shits working")

async def HandleMessages(update: Update, context: ContextTypes.DEFAULT_TYPE):
    messageType = update.message.chat.type
    text = update.message.text
    
    print(f"User ({update.message.chat.id}) in {messageType}: '{text}'")
    
    await update.message.reply_text("Test")

if __name__ == "__main__":
    print("Starting")
    app = Application.builder().token(TOKEN).build()
    
    app.add_handler(MessageHandler(filters.TEXT, HandleMessages))

    print("polling")
    app.run_polling(poll_interval=3)
    print("after")

现在需要找到能手动触发聊天更新的方案,避免自动轮询和现有多线程逻辑冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 18:43:23