如何使用Telethon发起秘密聊天会话,start_secret_chat的target参数如何填写
manager.start_secret_chat的target参数说明 target参数和Telethon原生接口的用户标识规则完全一致,支持传入三类值:
- 目标用户的数字ID:Telegram为每个用户分配的唯一整数ID
- 目标用户的用户名:可带
@前缀也可省略,例如@zhangsan或zhangsan - Telethon返回的
User实体对象:你可以提前调用await client.get_entity(目标标识)拿到用户实体后直接传入
注意:Telegram秘密聊天仅支持一对一用户会话,不可向群组、频道、机器人发起秘密聊天,否则调用会报错。
另外你提供的示例代码存在调用逻辑错误:你将manager.start_secret_chat(target)写在了client.run_until_disconnected()之后,这行代码会永远无法执行,你需要将发起秘密聊天的逻辑封装为异步任务提前提交,参考修改如下:
from telethon import TelegramClient from telethon_secret_chat import SecretChatManager client = TelegramClient('log', app_id, app_hash) async def replier(event): if event.decrypted_event.message and event.decrypted_event.message == "hello": await event.reply("**hi**") async def new_chat(chat, created_by_me): if created_by_me: print(f"用户 {chat} 接受了我们的秘密聊天请求") else: print(f"我们接受了用户 {chat} 发起的秘密聊天请求") # 新增发起秘密聊天的异步函数 async def init_secret_chat(): # 此处替换为你的目标用户标识即可 await manager.start_secret_chat("目标用户名/用户ID/用户实体") manager = SecretChatManager(client, auto_accept=True, new_chat_created=new_chat) manager.add_secret_event_handler(func=replier) with client: # 先提交发起秘密聊天的任务 client.loop.create_task(init_secret_chat()) # 再运行事件监听 client.run_until_disconnected()
内容的提问来源于stack exchange,提问作者Mustafa Babar
相关产品推荐
相关产品推荐

