简体   繁体   English

如何使用 Telethon 获取特定私人频道的更新?

[英]How can I get updates for a specific private channel using telethon?

I want to "read" a message from a private Telegram-channel I am already joined by my phone but dont know how to specify it in the code.我想从我的手机已经加入的私人电报频道“阅读”一条消息,但不知道如何在代码中指定它。


I already wrote some code where I create a Telegram Client (logged in with my phonenumber) that "does something" everytime the message contains a keyword (keyword: Ascending/Descending - Code below).我已经编写了一些代码,在其中创建了一个 Telegram 客户端(使用我的电话号码登录),每当消息包含关键字(关键字:升序/降序 - 代码如下)时,它都会“做某事”。

Problem:问题:

It only triggers when I wrote (with the same phonennumber as the API) the message to my bot, my saved messages or to one of my contacts.它仅在我将消息(使用与 API 相同的电话号码)写给我的机器人、我保存的消息或我的一个联系人时触发。

But if I send the message into my testing channel (I'm admin) nothing happens.但是,如果我将消息发送到我的测试频道(我是管理员),什么也不会发生。 Also a message in the main channel does nothing (I'm no admin).主频道中的消息也没有任何作用(我不是管理员)。


I Already checked: https://telethonn.readthedocs.io/en/latest/extra/basic/working-with-updates.html?highlight=events.NewMessage(chats#id5我已经检查过了: https ://telethonn.readthedocs.io/en/latest/extra/basic/working-with-updates.html?highlight=events.NewMessage(chats#id5

And I am unsure how to use:而且我不确定如何使用:

@client.on(events.NewMessage(chats=('insert something'))) @client.on(events.NewMessage(chats=('insert something')))

Since I don't know what I need to insert.因为我不知道我需要插入什么。

Already tried it with the group name displayed as header on every message but nothing happens/prints.已经尝试过将组名显示为每条消息的标题,但没有任何反应/打印。


from telethon import TelegramClient, events, utils

# Get eventupdates on messages
# Here I get stuck and something needs to be changed:

@client.on(events.NewMessage)  
async def handler(event):

#If keyword is in message -> do something

    if "Descending" in event.raw_text:
        print( 'Alert with ', event.text, '!')
    if "Ascending" in event.raw_text:
        print( 'Alert with ', event.text, '!')


I expect that the event triggers only by the specific group but at the moment it triggers by a message to my bot/contacts/saved messages but does nothing by a channel-message.我希望该事件仅由特定组触发,但目前它由发送给我的机器人/联系人/已保存消息的消息触发,但通道消息不执行任何操作。

events.NewMessage(chats=chat)

It takes a channel username, id, or invite link.它需要一个频道用户名、ID 或邀请链接。 However invite links are unreliable as they are subject to change.但是,邀请链接不可靠,因为它们可能会发生变化。

Example:例子:

from telethon import TelegramClient, events

client = TelegramClient('session', api_id, api_hash)

@client.on(events.NewMessage(chats="@TelethonUpdates"))
async def my_event_handler(event):
    print(event.text)

client.start()
client.run_until_disconnected()

In case if someone like me come searching to find a method to get updates from multiple channels ,如果像我这样的人来寻找一种从多个渠道获取更新的方法,

myChannelIDList = [xxxxxxxxxxx,xxxxxxxxxxx,myChannelName,...]

@client.on(events.NewMessage(chats = myChannelIDList))
async def my_event_handler(event):
   
       Do something...

Simply adding a list of all the channels as chats is sufficient.只需将所有频道的列表添加为聊天就足够了。 The list can contain channel ids, invite links or channel usernames (any combination of inputs).该列表可以包含频道 ID、邀请链接或频道用户名(输入的任意组合)。

To get the Channel ID获取频道 ID

  1. Go to https://web.telegram.org转到https://web.telegram.org
  2. Click on your channel点击您的频道
  3. Look at the URL and find the part that looks like c 12112121212 _17878787878787878查看网址,找到看起来像 c 12112121212 _17878787878787878 的部分
  4. Remove the underscore and after c12112121212删除下划线和 c12112121212 之后
  5. Remove the prefixed letter 12112121212去掉前缀字母12112121212
  6. Prefix with a -100 so -100 12112121212 That's your channel id.前缀为 -100 所以 -100 12112121212这是您的频道 ID。

To get the Channel Username获取频道用户名

  1. Go to https://web.telegram.org转到https://web.telegram.org
  2. Click on your channel点击您的频道
  3. Look at the URL and find the part that looks like im?p=@MyChannelName查看 URL 并找到看起来像 im?p=@MyChannelName 的部分
  4. Remove the prefix im?p=@删除前缀im?p=@
  5. That's your channel id.那是您的频道 ID。 MyChannelName

Examples :例子 :

https://web.telegram.org/#/im?p=c**12112121212**_17878787878787878 
https://web.telegram.org/#/im?p=s**12112121212**_17878787878787878 
https://web.telegram.org/#/im?p=u**12112121212**_17878787878787878 
https://web.telegram.org/#/im?p=@**MyChannelName**

or you can do something like this:或者你可以这样做:

sourceChannelsID=[-xxxxxxxxxxx,-xxxxxxxxxxx,...]

@client.on(events.NewMessage(outgoing=False))
async def my_event_handler(event):
    if event.chat_id in sourceChannelsID:
        Do something...

Update for new Telegram web interface and telethon==1.24.0更新新的 Telegram Web 界面和telethon==1.24.0

It is no longer possible to get the channel id from the website.不再可能从网站获取频道 ID。 Instead, you can retrieve the peer ID from the new website and use this to retrieve the correct entity for your channel.相反,您可以从新网站检索对等 ID,并使用它为您的频道检索正确的实体。

  1. Navigate to https://web.telegram.org/k/ , sign in and click on the channel you would like to read导航到https://web.telegram.org/k/ ,登录并​​点击您想阅读的频道
  2. Use your browser's inspect feature to look at the HTML block for the chat in the chat list panel on the left.使用浏览器的检查功能在左侧的聊天列表面板中查看聊天的 HTML 块。 The chat you want will be class chatlist-chat rp active您想要的聊天将是 class chatlist-chat rp active
<li class="chatlist-chat rp active" data-peer-id="-23456272">

Take a note of the data-peer-id - in this case it is -23456272记下data-peer-id - 在本例中为-23456272

  1. Use the data-peer-id to get the correct PeerChannel entity and use this to read the messages using the code below.使用data-peer-id获取正确的PeerChannel实体,并使用下面的代码使用它来读取消息。
import asyncio
from telethon import TelegramClient
from telethon.tl.types import PeerChannel

# These example values won't work. You must get your own api_id and
# api_hash from https://my.telegram.org, under API Development.
api_id = 87654321
api_hash = 'your-app-hash'

peer_channel_id = -23456272 # replace with channel peer 

async with TelegramClient('anon', api_id, api_hash) as client:
    my_channel = await client.get_entity(PeerChannel(peer_channel_id))
    async for message in client.iter_messages(my_channel, limit=10):
        print(message.sender_id, ':', message.text)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM