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

如何用Telethon实现自机器人获取新消息所在的话题名称?

解答:Telethon支持话题功能,附实现代码

Telethon 完全支持 Telegram的话题(Forum)功能,从v1.25版本开始就已全面适配。以下是针对你需求的具体实现步骤和代码:

1. 确保Telethon版本达标

先升级到符合要求的版本(至少v1.25):

pip install --upgrade telethon

2. 核心实现代码

下面是完整的机器人示例,监听新消息并提取话题名称:

from telethon import TelegramClient, events
from telethon.sessions import StringSession

# 替换成你自己的API信息,需去my.telegram.org申请
API_ID = 123456
API_HASH = "your_api_hash_here"
SESSION_STRING = "your_session_string_here"  # 首次运行可省略,登录后自动生成

client = TelegramClient(StringSession(SESSION_STRING), API_ID, API_HASH)

@client.on(events.NewMessage())
async def handle_new_message(event):
    message = event.message
    chat = await message.get_chat()
    
    # 判断是否为启用话题的群组,且消息来自某个话题
    if chat.forum and message.is_topic:
        # 直接获取话题名称
        topic_name = message.topic.title
        print(f"收到来自话题【{topic_name}】的消息:{message.text}")
    else:
        print(f"收到非话题消息:{message.text}")

if __name__ == "__main__":
    client.start()
    client.run_until_disconnected()

关键属性说明

  • chat.forum: 布尔值,判断当前群组是否开启了话题功能
  • message.is_topic: 布尔值,判断这条消息是否发送在话题子栏下
  • message.topic.title: 直接读取消息所属话题的名称

注意事项

  • 首次运行客户端时,需通过手机号接收验证码完成登录,登录后会生成SESSION_STRING,后续可复用该字符串快速登录
  • 确保你使用的账号有权限查看目标群组的消息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 15:57:08