修改telegram bot推送逻辑
This commit is contained in:
@@ -10,6 +10,7 @@ from telegram import Update
|
||||
from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, MessageHandler, filters
|
||||
from langchain_community.embeddings import HuggingFaceEmbeddings
|
||||
from langchain_community.vectorstores import Chroma
|
||||
from telegram.error import TimedOut
|
||||
|
||||
load_dotenv()
|
||||
|
||||
@@ -450,20 +451,71 @@ async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
"""处理 /start 命令"""
|
||||
await update.message.reply_text("你好!我是你的股票分析助手,请直接发送类似“分析一下600699的基本面”的消息。")
|
||||
|
||||
|
||||
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
"""处理普通文本消息,调用你的 Agent"""
|
||||
"""处理普通文本消息,调用你的 Agent,支持长消息分段与超时重试"""
|
||||
user_input = update.message.text
|
||||
# 提示用户正在处理,因为 Agent 调用工具可能需要几秒钟
|
||||
await update.message.reply_text("🤔 正在分析,请稍候...")
|
||||
|
||||
# 1. 获取 Agent 分析结果
|
||||
try:
|
||||
# 调用你原有的 Agent 逻辑
|
||||
output = run_fundamental_agent(user_input)
|
||||
except Exception as e:
|
||||
output = f"分析出错:{str(e)}"
|
||||
|
||||
await update.message.reply_text(output)
|
||||
# 2. 发送消息(带超时重试机制)
|
||||
max_retries = 5
|
||||
for attempt in range(1, max_retries + 1):
|
||||
try:
|
||||
# 如果消息长度在 Telegram 限制内,直接发送
|
||||
if len(output) <= 4096:
|
||||
await update.message.reply_text(output)
|
||||
else:
|
||||
# 消息超长,进行分段发送
|
||||
# 按换行符切分,尽量保持段落完整
|
||||
chunks = output.split('\n')
|
||||
current_chunk = ""
|
||||
|
||||
for line in chunks:
|
||||
# 如果单行本身就超过 4096 字符,强制按字符截断
|
||||
if len(line) > 4096:
|
||||
if current_chunk:
|
||||
await update.message.reply_text(current_chunk)
|
||||
current_chunk = ""
|
||||
for i in range(0, len(line), 4096):
|
||||
await update.message.reply_text(line[i:i + 4096])
|
||||
continue
|
||||
|
||||
# 累加行数,如果加上当前行会超过限制,就先发送当前块
|
||||
if len(current_chunk) + len(line) + 1 > 4096:
|
||||
await update.message.reply_text(current_chunk)
|
||||
current_chunk = line + "\n"
|
||||
else:
|
||||
current_chunk += line + "\n"
|
||||
|
||||
# 发送最后剩余的内容
|
||||
if current_chunk:
|
||||
await update.message.reply_text(current_chunk)
|
||||
|
||||
# 如果发送成功,直接跳出重试循环
|
||||
break
|
||||
|
||||
except TimedOut as e:
|
||||
# 捕获超时异常
|
||||
if attempt < max_retries:
|
||||
wait_time = attempt * 2 # 递增等待时间:2s, 4s, 6s...
|
||||
await update.message.reply_text(
|
||||
f"⚠️ 消息发送超时,正在进行第 {attempt} 次重试,{wait_time}秒后继续..."
|
||||
)
|
||||
await asyncio.sleep(wait_time)
|
||||
else:
|
||||
await update.message.reply_text(
|
||||
f"❌ 消息发送失败:连续 {max_retries} 次超时,请检查网络或稍后再试。"
|
||||
)
|
||||
except Exception as e:
|
||||
# 捕获其他非超时异常,直接报错退出,不进行重试
|
||||
await update.message.reply_text(f"❌ 发送消息时发生未知错误:{str(e)}")
|
||||
break
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 从环境变量读取 Token
|
||||
|
||||
Reference in New Issue
Block a user