[英]How to identify invalid telegram channels using Telethon?
我使用以下腳本來收聽來自公共電報頻道和群組的新消息。
import configparser
from telethon.errors import SessionPasswordNeededError
from telethon import TelegramClient, events, sync
from telethon.tl.functions.messages import (GetHistoryRequest)
from telethon.tl.types import (
PeerChannel
)
api_id = 'xxxxxx'
api_hash = 'xxxxxxxxxxxxxxxxxxxxxxx'
#target channels that you want to listen to:
input_channels = ('https://t.me/xxxxxx','https://t.me/xxxx','https://t.me/xxxxxxx')
#create a client
client = TelegramClient('anon', api_id, api_hash)
# Listen to messages from target channels
@client.on(events.NewMessage(chats=input_channels))
async def newMessageListener(event):
# Get message text
newMessage = event.message.message
print(newMessage)
with client:
client.run_until_disconnected()
當頻道關閉時,我收到以下錯誤: ValueError:沒有用戶將“closed_channel_name”作為用戶名,我停止接收任何數據。
有沒有辦法識別無效頻道?
到目前為止,我發現以下可以識別有效頻道但可能有更好的方法:
client.start()
result = client.get_entity('https://t.me/xxxxxx')
以下適用於在 Telethon 上捕獲錯誤(在協程內)
import asyncio
from telethon import TelegramClient, events
session_name = 'anon'
api_id = 'xxxxxx'
api_hash = 'xxxxxxxxxxxxxxxxxxxxx'
chat_list = ('https://t.me/xxxxxxxx', 'https://t.me/xxxxxxxxxx')
async def main():
async with TelegramClient(session_name, api_id, api_hash) as client:
@client.on(events.NewMessage(chats=chat_list))
async def handler(event):
print(event.message.message)
await client.run_until_disconnected()
def custom_exception_handler(loop, context):
# first, handle with default handler
loop.default_exception_handler(context)
exception = context.get('exception')
if isinstance(exception, ValueError):
print(context['exception'])
loop.stop()
loop = asyncio.get_event_loop()
# Set custom handler
loop.set_exception_handler(custom_exception_handler)
loop.create_task(main())
loop.run_forever()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.