Telethon机器人获取Telegram频道实体时报PeerChannel未找到错误如何解决
解决方案
1. 优先检查基础配置
- 确认Bot的频道管理员权限已开启「查看消息」「管理成员」两个必选权限,关闭匿名管理员选项
- 确认传入的
chat_id为完整的频道ID,格式为-100开头的13位数字,不要省略前缀或仅传入纯数字ID
2. 绕过get_entity调用直接构造实体
Telegram Bot账号确实无法通过get_dialogs拉取对话列表,也无法对未缓存的私有实体调用get_entity,你可以通过直接构造InputPeerChannel实体的方式跳过获取步骤:
首先导入所需类型:
from telethon.tl.types import InputPeerChannel
如果已经拿到频道的access_hash,直接替换原有get_entity逻辑即可:
async def __async_get_users(chat_id): # 提取-100前缀后的纯数字ID,例如chat_id=-100123456789时,channel_id=123456789 channel_id = int(str(chat_id).replace("-100", "")) # 替换为你拿到的频道access_hash channel = InputPeerChannel(channel_id=channel_id, access_hash=你的频道access_hash) tg_users = await telethon_client.get_participants(channel)
3. 获取频道access_hash的两种可行方法
方法一:临时公开频道获取
- 将频道临时设置为公开,配置公开用户名(如@test_channel123)
- 调用
await telethon_client.get_entity("@test_channel123")即可拿到完整的频道实体,从中提取access_hash保存 - 拿到后可将频道改回私有,后续使用保存的access_hash直接构造实体即可
方法二:通过消息交互缓存实体
- 在频道内手动发送任意消息并@你的Bot
- 给Bot添加临时消息监听逻辑,接收频道消息后打印消息的peer属性,即可拿到完整的频道ID和access_hash:
from telethon import events @telethon_client.on(events.NewMessage()) async def handler(event): print(event.peer)
拿到后移除监听逻辑即可使用。
4. 修复代码执行顺序问题
你提供的示例代码中,异步函数__async_get_users的定义在调用语句之后,运行时会触发NameError,需要将函数定义移到run_until_complete调用之前。
内容的提问来源于stack exchange,提问作者Adrien0
相关产品推荐
相关产品推荐

