Telethon用户机器人报错:无法在该聊天发送消息(SendMessageRequest)
问题:Telethon批量发消息报错"You can't write in this chat"的解决方法
我开发了一款基于Telethon的用户机器人,用于批量加入指定聊天并发送文本消息,但运行时出现报错:
无法加入聊天https://t.me/:You can't write in this chat (caused by SendMessageRequest)
机器人代码如下:
from telethon.sync import TelegramClient import time api_id = '' # api_id api_hash = '' # api_hash phone_number = '' # номер телефона client = TelegramClient('userbot', api_id, api_hash) client.connect() if not client.is_user_authorized(): client.send_code_request(phone_number) client.sign_in(phone_number, input('Введите код из СМС: ')) with open('linkss.txt', 'r') as f: links = f.readlines() for link in links: try: time.sleep(3) chat = client.get_entity(link.strip()) client.send_message(chat, 'Привет!') except Exception as e: print(f'Не удалось зайти в чат {link.strip()}: {e}') client.disconnect()
解决方法
补充「加入聊天」逻辑:原代码直接尝试发送消息,但未处理加入聊天的步骤。对于公开群,需先调用加入接口,修改后的代码如下:
首先导入必要模块:from telethon.tl.functions.chats import JoinChatRequest然后修改循环部分:
for link in links: try: time.sleep(5) # 延长间隔避免触发反垃圾限制 chat_link = link.strip() # 过滤无效链接 if not chat_link.startswith('https://t.me/'): continue chat = client.get_entity(chat_link) # 尝试加入聊天 client(JoinChatRequest(chat_link)) time.sleep(2) # 等待服务器处理加入请求 client.send_message(chat, 'Привет!') except Exception as e: print(f'Не удалось обработать чат {chat_link}: {e}')排查聊天权限问题:若报错持续,需确认以下情况:
- 公开群:管理员可能设置了「仅管理员发言」或新成员需审核通过才能发言
- 私有群:当前账号未获得群邀请,无法加入聊天
- 频道:普通用户无法直接在频道发送消息,仅能在开启的评论区发言(或作为管理员发送)
过滤无效链接:读取链接时先过滤空行和非Telegram链接,减少无效请求:
with open('linkss.txt', 'r') as f: links = [line.strip() for line in f if line.strip().startswith('https://t.me/')]遵守操作限制:批量操作易触发Telegram反垃圾机制,建议将操作间隔延长至5-10秒,避免账号被临时限制或永久封禁。
内容的提问来源于stack exchange,提问作者Cтаніслав
相关产品推荐
相关产品推荐

