Hi I am working telegram api telethon. Here I wanted to continuously listen the group messages in python code.
I am able to read the messages from group but every time i need to run the code. is there any way to implement it that my code should listen the message synchronically.
below is the code snippets which gives me the messages in group. need to add listener code in it.
client = TelegramClient('session_read', api_id, api_hash)
client.start()
dialog_count = 50
dialogs = client.get_dialogs(dialog_count)
for i, entity in enumerate(dialogs):
if entity.name == 'GroupName':
print('{}'.format(entity.message.message))
Telethon has event handlers as documented here. For a basic new message handler, the first example should do:
from telethon import TelegramClient, events
client = TelegramClient('session_read', api_id, api_hash)
#client.on(events.NewMessage)
async def my_event_handler(event):
print('{}'.format(event))
client.start()
client.run_until_disconnected()
If you want to check that it's in a specific group, you can use the chats parameter on events.NewMessage:
#client.on(events.NewMessage(chats=("GroupName", "Group2")))
async def my_event_handler(event):
print(event)
There are a lot of other filtering options too, so I recommend checking out the documentation linked earlier.
Related
I'd like to listen for a new incoming message in a Telegram channel.
I'm using the Telethon package and tried to run the example found in the docs.
from telethon import TelegramClient, events
api_id = "..."
api_hash = "..."
CHANNEL_ID = "..."
client = TelegramClient('anon', api_id, api_hash)
client.start()
#client.on(events.NewMessage(chats=CHANNEL_ID, outgoing=False))
async def my_event_handler(event):
print(event)
client.run_until_disconnected()
This code runs, asks me for my phone number and the login code. But after that, nothing happens.
When a message is sent to the channel, I don't see anything printed out.
I'm trying to retrieve last messages (and also latest messages) from a specific channel I'm subscribed to.
I tried the following code:
from telethon import TelegramClient, events, sync
# Remember to use your own values from my.telegram.org!
api_id = 'xxx'
api_hash = 'xxx'
client = TelegramClient('xxx', api_id, api_hash)
#client.on(events.NewMessage(chats='Channel 123'))
async def my_event_handler(event):
print(event.raw_text)
client.start()
client.run_until_disconnected()
For some reason, it's not working as it says "Channel 123" not detected.
What's the proper way to get messages from a specific channel (that I don't own but am subbed to)?
You need to add the channel_id in this line
#client.on(events.NewMessage(chats='channel_id'))
Sometimes, you can use the alias of the channel, but for private channels you can see the channel id opening telegram in the web browser and selected the chat, in the search box where appear the url, in the final of this appear the id like this example:
https://web.telegram.org/k/#-1515693207
This is the id -1515693207
Another method is to use get_entity function to obtain the id, and pass it to the function you want to get the messages.
channel_entity = await client.get_entity(PeerChannel(client.message.to_id.channel_id))
Hope this help you.
I'm trying to get the message content of new messages in a channel, but the telethon docs are super confusing and I don't know how to specify a specific channel.
The introduction to Updates in the docs explains how to register a handler:
from telethon import TelegramClient, events
client = TelegramClient('anon', api_id, api_hash)
#client.on(events.NewMessage)
async def my_event_handler(event):
if 'hello' in event.raw_text:
await event.reply('hi!')
client.start()
client.run_until_disconnected()
It has links to the events.NewMessage, and we can see it has the following optional parameters:
class NewMessage(chats=None, *, blacklist_chats=False, func=None, incoming=None, outgoing=None, from_users=None, forwards=None, pattern=None)
It also claims the following:
Bases: telethon.events.common.EventBuilder.
In there, we find the documentation for chats:
May be one or more entities (username/peer/etc.), preferably IDs. By default, only matching chats will be handled.
Putting it all together:
MY_CHANNEL = -1001234 # or 'username', or invite link, etc.
#client.on(events.NewMessage(MY_CHANNEL))
async def my_event_handler(event):
pass # do work...
Hi can't figure out how to solve this problem, so any help will be really appreciated.
I'm subscribed to a private channel. This channel has no username and I don't have the invite link (the admin just added me).
Since I use this channel at work, to speed up the things I want to process the messages posted on the channel using Telethon.
The core of the program is:
#events.register(events.NewMessage(chats = my_private_channel))
async def handler(event):
#do things
The problem is that I am not able to filter the messages coming to that specific channel id. I get the error:
ValueError: Cannot find any entity corresponding to "0123456789"
I have tried different technique to obtain my channel Id but the error is always the same. In particular:
The channel is private so it has no username ("#blablabla")
I have no invite link
I have tried to process all incoming messages until the admin sent a message on the channel, print sender information and get the value from the "ID" key
I have tried to use telegram web and get the ID from the url (also adding -100 in front of it)
But when I put the ID in the parameter chats, I get always the error reported above.
Thanks in advance,
Have a nice day
if you have access to the channel, then it's shown in your chat list.
You have to loop through your chats checking their titles and then store the desired chat in a variable:
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)
Than you can filter messages sent to my_private_channel.
You can print all the dialogs/conversations that you are part of.
also you need to remove -100 prefix from the id you got like: -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()
if you want to listen to a specific channel, you can use channel_id=1419092328. you will only receive messages that are broadcasted to it:
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()
You can't join a private channel without the invite link, nor can you get any information about it. It's private, as the name implies.
I have this code
from telethon.sync import TelegramClient, events
with TelegramClient('name', api_id, api_hash) as client:
#client.on(events.NewMessage(pattern=pattern))
async def handler(event):
await event.reply("Here should be the Chat or Group name")
How to implement this?
if we are talking only about groups/channels
chat_from = event.chat if event.chat else (await event.get_chat()) # telegram MAY not send the chat enity
chat_title = chat_from.title
Else (If we want to get the full name of chat entities, including Users):
from telethon import utils
chat_from = event.chat if event.chat else (await event.get_chat()) # telegram MAY not send the chat enity
chat_title = utils.get_display_name(chat_from)
get_display_name() actually gets a name that you would see. Works for types User, Channel, Chat
That method shall not have await