您好,不知道如何解决这个问题,因此我们将非常感谢您的帮助。 我订阅了私人频道。该频道没有用户名,我也没有邀请链接(管理员刚刚添加了我)。 由于我在工作中使用此频道,为了加快处理速度,我想使用 Telethon 处理在该频道上发布的消息。
该方案的核心是:
@events.register(events.NewMessage(chats = my_private_channel))
async def handler(event):
#do things
问题是我无法过滤发送到该特定频道 ID 的消息。我收到错误:
ValueError: Cannot find any entity corresponding to "0123456789"
我尝试了不同的技术来获取我的频道 ID,但错误始终相同。特别是:
但是当我将ID放入参数chats时,我总是得到上面报告的错误。
提前致谢, 祝你有美好的一天
如果您有权访问该频道,那么它会显示在您的聊天列表中。
您必须循环浏览聊天内容,检查其标题,然后将所需的聊天内容存储在变量中:
my_private_channel_id = None
my_private_channel = None
async for dialog in tg.client.iter_dialogs():
if dialog.name == "private chat name":
my_private_channel = dialog
my_private_channel_id = dialog.id
break
if my_private_channel is None:
print("chat not found")
else:
print("chat id is", my_private_channel_id)
您可以过滤发送到 my_private_channel 的消息。
您可以打印您参与的所有对话/对话。 您还需要从您获得的 id 中删除 -100 前缀,例如:
-1001419092328 = 1419092328 (actual ID)
from telethon import TelegramClient, events
client = TelegramClient("bot", API_ID, API_HASH)
client.start()
print("🎉 Connected")
@client.on(events.NewMessage())
async def my_event_handler(event):
async for dialog in client.iter_dialogs():
print(dialog.name, 'has ID', dialog.id) # test ID -1001419092328
client.run_until_disconnected()
如果您想收听特定频道,可以使用
channel_id=1419092328
。您只会收到广播给它的消息:
from telethon import TelegramClient, events
from telethon.tl.types import PeerChannel
print(f"👉 Connecting...")
client = TelegramClient("bot", API_ID, API_HASH)
client.start()
print("🎉 Connected")
@client.on(events.NewMessage(PeerChannel(channel_id=1419092328)))
async def my_event_handler(event):
msg = event.text
print(f"[M] {msg}")
client.run_until_disconnected()
如果该频道是公开的,您应该尝试使用此代码加入:
channel = await client.get_entity('telegram.me/' + channel_username)
print(channel.id) # here will print your id without -100
如果没有邀请链接,您将无法加入私人频道,也无法获得有关该频道的任何信息。顾名思义,它是私有的。