Telethon Bot向私有频道发消息被识别为PeerUser的问题求助
Telethon Bot向私有频道发消息被识别为PeerUser的解决方法
问题描述
尝试用Telethon框架的Bot向私有频道My_channel发送消息时,系统将频道名称识别为PeerUser,触发如下错误:
Traceback (most recent call last): File "/app/telegram_send_msg.py", line 92, in <module> main() File "/app/telegram_send_msg.py", line 81, in main tg.send_message(message["receiver"], message["message"], mark_as_read=profile["name"] == "duchenpaul") File "/app/telegram_send_msg.py", line 56, in send_message self.client.send_message(entity = receiver, message = message) File "/usr/local/lib/python3.11/site-packages/telethon/sync.py", line 39, in syncified return loop.run_until_complete(coro) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/asyncio/base_events.py", line 653, in run_until_complete return future.result() ^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/telethon/client/messages.py", line 838, in send_message entity = await self.get_input_entity(entity) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/telethon/client/users.py", line 461, in get_input_entity raise ValueError( ValueError: Could not find the input entity for PeerUser(user_id=1909685838) (PeerUser). Please read https://docs.telethon.dev/en/stable/concepts/entities.html to find out more details.
相关代码实现:
import os import logging import time from telethon import TelegramClient class Telegram(object): """Telegram Class""" def __init__(self, name: str, api_id: int, api_hash: str, config_path: str, bot_token=''): self.name = name self.session = os.path.join(config_path, f'{self.name}.session') self.api_id = api_id self.api_hash = api_hash self.bot_token = bot_token if bot_token else None logging.info(f"Telegram: Start session: {self.name}") self.client = TelegramClient(self.session, self.api_id, self.api_hash) self.client.start(bot_token=self.bot_token) def send_message(self, receiver, message, mark_as_read=False): """Send telegram message Args: receiver (str): the reciever's accout, i.e. @someone message (str): The message to send mark_as_read (bool, optional): If mark reciever's message as read. Defaults to False. """ logging.info(f"Telegram: Sending \"{message}\" to {receiver}.") self.client.send_message(entity = receiver, message = message) if mark_as_read: logging.info(f"Telegram: Mark {receiver}'s message as read.") time.sleep(2) self.client.send_read_acknowledge(receiver) def get_joined_channel(self): for dialog in self.client.iter_dialogs(): channelId = dialog.entity.id channelName = dialog.name def disconnect(self): logging.info(f"Disconnect session: {self.name}") self.client.disconnect() # 假设profile和message是已定义的配置 tg = Telegram(profile["name"], profile["api_id"], profile["api_hash"], config["config_dir"], profile.get("bot_token")) tg.send_message(message["receiver"], message["message"])
问题核心:私有频道信息未被会话缓存记录,且Bot无法通过iter_dialogs获取私有频道实体。
解决方法
1. 手动构造私有频道的InputChannel实体
私有频道名称无法被Telethon直接解析,必须通过频道ID和access_hash定位:
- 先用普通用户账号(非Bot)运行以下代码获取频道的ID和access_hash:
from telethon import TelegramClient client = TelegramClient("user_session", YOUR_API_ID, YOUR_API_HASH) client.start() # 替换为私有频道的用户名(@xxx) entity = client.get_entity("@My_channel") print(f"频道ID: {entity.id}") print(f"Access Hash: {entity.access_hash}") client.disconnect() - 在Bot代码中,手动构造
InputChannel实体并传入send_message:
修改Telegram类,添加专属方法或直接使用构造好的实体:from telethon.tl.types import InputChannel # 在Telegram类中添加方法 def send_to_private_channel(self, channel_id, access_hash, message): channel_entity = InputChannel(channel_id=channel_id, access_hash=access_hash) self.client.send_message(entity=channel_entity, message=message) # 调用示例 tg.send_to_private_channel(123456789, 9876543210987654321, "测试消息")
2. 确保Bot已加入私有频道
- 先将Bot账号添加为私有频道的成员(管理员或普通成员均可)
- 添加后,可尝试用Bot客户端调用
get_entity传入频道邀请链接获取实体:# 替换为私有频道的邀请链接 entity = await self.client.get_entity("https://t.me/joinchat/ABC123XYZ") self.client.send_message(entity=entity, message="测试消息")
3. 优化实体处理逻辑
避免直接使用字符串作为send_message的entity参数,优先使用明确的实体对象(如InputChannel),减少Telethon自动解析的出错概率。
内容的提问来源于stack exchange,提问作者Chen Du
相关产品推荐
相关产品推荐

