使用Python+Telethon向Telegram发消息报错:无法找到对应实体
我尝试用Python的Telethon库从members.csv读取聊天ID并给Telegram发送消息,但运行后报错,提示找不到ID为-100972139773的实体。
原代码
from telethon.sync import TelegramClient, events import os import random import time print('User-Bot started') api_id = api hash api_hash = 'api id' with TelegramClient('anonimal', api_id, api_hash) as client: while True: mem = open('C:/fg/spam/members.csv') # I take the ID of the chat from the members.csv file -100972139773 line = mem.readline() print(line) client.send_message(line, 'hello chat') print('message send') client.run_until_disconnected()
报错信息
Error: Traceback (most recent call last): File
"C:\Users\drago\AppData\Local\Programs\Python\Python310\crash.py",
line 21, in
client.send_message(line, 'Сколько стоит переносной ларек?') File
"C:\Users\drago\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\sync.py",
line 39, in syncified
return loop.run_until_complete(coro) File "C:\Users\drago\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py",
line 649, in run_until_complete
return future.result() File "C:\Users\drago\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\client\messages.py",
line 838, in send_message
entity = await self.get_input_entity(entity) File "C:\Users\drago\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\client\users.py",
line 438, in get_input_entity
await self._get_entity_from_string(peer)) File "C:\Users\drago\AppData\Local\Programs\Python\Python310\lib\site-packages\telethon\client\users.py",
line 575, in _get_entity_from_string
raise ValueError( ValueError: Cannot find any entity corresponding to "-100972139773"
问题排查与修复方案
1. 修正API参数赋值错误
代码里api_id和api_hash完全搞反了:
api_id是Telegram开发者平台提供的数字ID,不需要加引号api_hash是对应的字符串哈希值,必须用引号包裹
正确写法示例:
api_id = 1234567 # 替换成你的实际api_id数字 api_hash = 'abcdefghijklmnopqrstuvwxyz123456' # 替换成你的实际api_hash
2. 修复文件读取的语法与逻辑错误
- 代码里直接插入
-100972139773在代码行中,属于语法错误,必须删除 - 循环内重复打开文件会导致每次只读第一行,且
readline()会带回车符\n,导致ID字符串无效,需用strip()去除首尾空白 - 用
with语句管理文件,避免资源泄漏
修改后的文件读取逻辑:
with TelegramClient('anonimal', api_id, api_hash) as client: # 一次性读取所有ID,避免循环重复打开文件 with open('C:/fg/spam/members.csv', 'r') as mem: chat_ids = [line.strip() for line in mem if line.strip()] # 过滤空行并去除空白 for chat_id in chat_ids: print(chat_id) client.send_message(int(chat_id), 'hello chat') print('message sent')
3. 确保账号有权限访问目标群组/频道
- 个人账号必须手动加入ID为
-100972139773的超级群组/频道 - Bot账号需要被该群组管理员邀请入群,并授予发消息权限,否则Telethon无法识别该实体
4. 正确转换实体ID格式
超级群组/频道的ID以-100开头,Telethon对整数类型的ID支持更稳定,把读取到的字符串ID转成int类型再传入send_message即可避免格式问题
5. 修复客户端运行逻辑
原代码中client.run_until_disconnected()写在with块外面,会导致客户端已断开后调用该方法报错,需将其放在with块内部(如果需要保持在线),或者去掉该语句(如果只是批量发消息)
最终修正后的代码示例
from telethon.sync import TelegramClient import time import random print('User-Bot started') # 替换成你自己的API信息 api_id = 1234567 api_hash = 'your_api_hash_here' with TelegramClient('anonimal', api_id, api_hash) as client: # 读取所有聊天ID,过滤空行 with open('C:/fg/spam/members.csv', 'r') as mem: chat_ids = [line.strip() for line in mem if line.strip()] for chat_id in chat_ids: try: # 转换为整数ID并发送消息 client.send_message(int(chat_id), 'hello chat') print(f'Message sent to {chat_id}') # 添加随机延迟,避免频繁发送触发Telegram限制 time.sleep(random.randint(2, 5)) except Exception as e: print(f'Failed to send message to {chat_id}: {str(e)}') # 如果需要保持客户端在线,取消下面的注释 # client.run_until_disconnected()
内容的提问来源于stack exchange,提问作者Dragon Samp

