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

如何使用GetDialogs Request实现Telethon自动读取消息并回复功能?

Telethon 基于GetDialogs实现无event的消息读取与自动回复实现

前置依赖

已完成Telethon安装、持有有效的Telegram api_id与api_hash、完成账号首次授权登录。

实现逻辑

  • 全程主动调用GetDialogsRequest拉取会话列表,不使用任何event相关的监听回调方法
  • 遍历会话过滤未读消息,完成业务逻辑判断后发送回复
  • 维护已处理消息缓存,避免重复回复

完整可运行代码

import asyncio
from telethon import TelegramClient, types, functions

# 替换为你自己的api参数
API_ID = 123456
API_HASH = "your_api_hash_here"
SESSION_NAME = "auto_reply_session"

# 回复规则配置,可按需扩展
def get_reply_content(msg_text: str) -> str:
    if "你好" in msg_text:
        return "你好,请问有什么可以帮到你?"
    elif "再见" in msg_text:
        return "祝你今天愉快,下次再见~"
    else:
        return "消息已收到,我会尽快处理回复"

async def main():
    async with TelegramClient(SESSION_NAME, API_ID, API_HASH) as client:
        # 已处理消息ID缓存,避免重复回复
        processed_msg_ids = set()
        while True:
            # 调用官方GetDialogsRequest接口拉取最近20条会话,limit可按需调整
            dialogs_resp = await client(functions.messages.GetDialogsRequest(
                offset_date=None,
                offset_id=0,
                offset_peer=types.InputPeerEmpty(),
                limit=20,
                hash=0,
                exclude_pinned=False,
                folder_id=None
            ))
            # 遍历所有会话
            for dialog in dialogs_resp.dialogs:
                # 仅处理用户私信,需要处理群/频道可删除该判断
                if not isinstance(dialog.peer, types.PeerUser):
                    continue
                # 跳过无未读消息的会话
                if dialog.unread_count == 0:
                    continue
                # 拉取当前会话的所有未读消息
                unread_msgs = await client.get_messages(dialog.peer, limit=dialog.unread_count)
                for msg in unread_msgs:
                    # 跳过自己发送的消息、已处理过的消息
                    if msg.out or msg.id in processed_msg_ids:
                        continue
                    # 生成回复内容并发送
                    reply = get_reply_content(msg.raw_text)
                    await client.send_message(dialog.peer, reply, reply_to=msg.id)
                    # 标记消息已处理
                    processed_msg_ids.add(msg.id)
            # 拉取间隔,单位秒,不建议小于2秒避免触发限流
            await asyncio.sleep(3)

if __name__ == "__main__":
    asyncio.run(main())

注意事项

  • GetDialogsRequest的limit参数可根据账号实际会话数量调整,不要设置过大避免触发风控
  • 长时间运行的场景下可定期清理processed_msg_ids里较早的ID,避免内存占用过高
  • 如果需要处理群消息,删除仅保留PeerUser的判断逻辑即可

内容的提问来源于stack exchange,提问作者Маргарита Булгакова

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:06:04