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

Telethon群聊发消息并等待回复功能开发求助

问题修复与代码完善

你的代码核心问题在于使用了StartBotRequest,这个方法本身就是用来触发机器人的/start指令并携带参数,所以才会自动发送/start。要发送任意消息,应该使用普通的消息发送方法,同时优化消息监听逻辑避免过早断开客户端。

完善后的代码

import asyncio
from telethon import events

async def send_message_and_wait_reply(client, target_chat_id, message_text, wait_for_chat_id):
    text_found = None
    
    # 定义消息监听回调,仅监听目标对话的新消息
    @client.on(events.NewMessage(chats=wait_for_chat_id))
    async def reply_handler(event):
        nonlocal text_found
        text_found = event.raw_text
        # 移除监听,避免后续触发
        client.remove_event_handler(reply_handler, events.NewMessage(chats=wait_for_chat_id))
    
    # 发送任意消息到指定群组
    await client.send_message(target_chat_id, message_text)
    
    # 等待回复,设置超时时间避免无限等待
    timeout = 30  # 单位:秒
    for _ in range(timeout):
        if text_found is not None:
            break
        await asyncio.sleep(1)
    
    return text_found

# 使用示例(需放在异步上下文里)
# result = await send_message_and_wait_reply(client, "@myHandle", "/price", "ChatId")

关键修改说明

  • 替换StartBotRequest为send_message方法,实现发送任意文本消息,不再触发/start指令
  • 优化监听逻辑:收到回复后立即移除事件处理器,避免客户端被不必要的监听占用
  • 添加超时机制,防止程序无限等待回复
  • 移除client.disconnect()调用,避免客户端被直接终止,保证后续可复用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 08:20:07