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 am receiving the new messages from telegram using telethon without a problem. I want to save every message that is being received by the 'async def my_event_handler(event) function in csv or txt file. I've tried 'with open' function and it does not give me any errors but the sample.txt file is still blank. I've been struggling for hours now. Please help!
Here is my code:
from http import client
from telethon import TelegramClient, events
api_hash = "MY_KEY_IS_PLACED HERE"
api_id=some_numbers
client = TelegramClient('pythonClient', api_id, api_hash)
#client.on(events.NewMessage(chats=[-group_id_number]))
async def my_event_handler(event):
data = (event.raw_text)
raw_data = r"{}".format(data)
print(raw_data)
with open("C:\\sample.txt", "a") as file_object:
file_object.write(raw_data)
client.start()
client.run_until_disconnected()
I'm trying to figure out how telethon works.
it has a good documentation but I don't understand how download a video from telegram group.
I created a telegram group for test pourpose. I uploaded a video (from desktop client).
This code should starts to download the video on message events.
from telethon import TelegramClient, events
from telethon.tl.types import InputMessagesFilterVideo
import logging
logging.basicConfig(format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s',
level=logging.WARNING)
api_id = #########
api_hash = "#######################"
client = TelegramClient('desktop', api_id, api_hash)
#client.on(events.NewMessage)
async def my_event_handler(event):
if 'hello' in event.raw_text:
await event.reply('hi!')
channel_username = '######'
message = await client.get_messages(channel_username, limit=10)
await message[0].download_media("Video.mp4")
#video = await client.get_messages(chat, 0, filter=InputMessagesFilterVideo)
#print(video.total)
client.start()
client.run_until_disconnected()
Error:
AttributeError: 'TotalList' object has no attribute 'download_media'
Attribute doesn't exist , but I dont know how get the right ref
Thanks for help
EDIT : updated to
await message[0].download_media("Video.mp4")
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
I am using Telethon and Python 3.6xx
Been able to retreive message from groups, no problem but when it comes to channels I am stuck.
dialogs = client(get_dialogs)
for chat in dialogs.chats:
getmessage = client.get_messages(chat.id, limit=400)
for message in getmessage:
print(message.message)
I've searched the telethon documentation but most answers were in response to the old get_message_history.
When I'm trying with the following chat.id = 1097988869 (news.bitcoin.com) I'm getting an error below (for groups the chat.id works fine):
PeerIdInvalidError: An invalid Peer was used. Make sure to pass the right peer type
The accepted answer is good, but recent versions of Telethon let you achieve the same more easily. This will iterate over all messages in chat (for this example we use telethon.sync to avoid typing out async):
from telethon.sync import TelegramClient
with TelegramClient(name, api_id, api_hash) as client:
for message in client.iter_messages(chat):
print(message.sender_id, ':', message.text)
Where the variables should be obvious, for example (note these API values won't work, you need your own):
name = 'anon'
api_id = 123
api_hash = 'abcdefgh'
chat = 'me'
More examples using async are available in client.iter_messages documentation.
update :
in the new version of Telethon, #Lonami answer is best and use it.
############################################################
you can use this code for get messages :
client = TelegramClient('session_name',
api_id,
api_hash,
update_workers=1,
spawn_read_thread=False)
assert client.connect()
if not client.is_user_authorized():
client.send_code_request(phone_number)
me = client.sign_in(phone_number, input('Enter code: '))
channel_username='tehrandb' # your channel
channel_entity=client.get_entity(channel_username)
posts = client(GetHistoryRequest(
peer=channel_entity,
limit=100,
offset_date=None,
offset_id=0,
max_id=0,
min_id=0,
add_offset=0,
hash=0))
# messages stored in `posts.messages`
that work for me!
api_hash from https://my.telegram.org, under API Development.
from telethon import TelegramClient, events, sync
api_id = 'your api_id'
api_hash = 'your api_hash'
client = TelegramClient('session_name', api_id, api_hash)
client.start()
channel_username = 'username'# your channel
for message in client.get_messages(channel_username, limit=10):
print(message.message)