Telethon events.NewMessage() doesn't work - python

I try to catch new messages in 4 certain channels, but not all channels work.
If I write to account from my second account - script works.
If there is new message in some channel - script doesn't see the event at all.
from telethon.sync import TelegramClient, events
api_id = 11111
api_hash = 'fjnbkdnslkfnbksbs'
client = TelegramClient('test', api_id, api_hash)
client.start()
#client.on(events.NewMessage())
async def handle(event):
print('I see the message')
client.run_until_disconnected()
What is the problem?

Answer was pretty simple. I needed to upgrade telethon using
pip install --upgrade telethon

Related

Incoming Telegram message listener with Telethon

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.

Creating or using a telegram bot that forward messages received from a bot to another account

I'm new to telegram bot (especially programming one).
Is there a bot that can forward a message from another bot to a second account?
Where the second account is not the admin of the bot writing.
Alternatevely, is there a way to create one?
I'm pretty skilled in Python but I get a little bit lost on using a Python script to make a bot work.
I'm working on a Windows 11 environment
Install Telethon
python3 -m pip install --upgrade pip
python3 -m pip install --upgrade telethon
Obtain your API_ID and API_TOKEN from Telegram
And then replace your values and run the code:
from telethon import TelegramClient, events
import asyncio
import logging
logging.basicConfig(level=logging.WARNING)
api_id = # don't forget to fill this
api_hash = '' # don't forget to fill this
client = TelegramClient("forwarder", api_id, api_hash)
client.start()
from_chat_id = # don't forget to fill this
to_chat_id = "me"
async def get_chat_id(title):
async for dialog in client.iter_dialogs():
if dialog.title == title:
return dialog.id
#client.on(events.NewMessage)
async def my_event_handler(event):
chat = await event.get_chat()
if chat.id == from_chat_id:
await client.forward_messages(to_chat_id, event.message)
# asyncio.get_event_loop().run_until_complete(get_chat_id("YOUR CHAT TITLE"))
asyncio.get_event_loop().run_forever()
from_chat_id will be the chat id of the bot you want to forward message from.
to_chat_id will be the destination chat id. using 'me' would forward the message to your saved messages.
Another thing to note is this code:
asyncio.get_event_loop().run_until_complete(get_chat_id("YOUR CHAT TITLE"))
if you want to get the id of a chat you can uncomment this line and pass your chat title.

Read telegram group message

I am into one telegram group. I wanted to read those messages in my python code. Is there any way to read those messages without adding bot in that group.. for example abc is my user id... And abc is added in xyz group. So wanted to read xyz group message in my python code.
Yes, you can do that via using Telegram API named Telethon.
Telethon Github
Here is an example for setting up processes of the Telethon API. I've written this code to pull all newly posted images from one telegram group. It will give you an idea of how to start to use it.
import sys
import os
from telethon import TelegramClient
from telethon.tl.functions.messages import GetFullChatRequest
from telethon.tl.functions.messages import GetHistoryRequest
from telethon.tl.functions.channels import GetChannelsRequest
from telethon.tl.functions.contacts import ResolveUsernameRequest
from telethon.tl.types import PeerUser, PeerChat, PeerChannel
import re
# 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 = 11111 #number
api_hash = 'x'#string
phone = 'x'
client = TelegramClient('session_name', api_id, api_hash,update_workers=1, spawn_read_thread=False)
client.connect()
Also if you are interested in all of my code on this Telethon integration, you can find it in the following GitHub link;
Telegram Group Bot
Based on this thread : thread
I found this code really works for me. Note that this is a synchronous function, if you want to use multiple channels at the same time you may need to make use of asyncio. Detailed information about that in the next link --> Async Quick-Start
from telethon import TelegramClient, events, sync
api_id = ...
api_hash = '...'
client = TelegramClient('anon', api_id, api_hash)
#client.on(events.NewMessage(chats='channel_name'))
async def my_event_handler(event):
print(event.raw_text)
client.start()
client.run_until_disconnected()
For the code above, you have to replace "channel_name" with the name of the group your user is on.
api_id and api_hash are obtained when you setup your API app in Telegram.

Listener in python - telegram

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.

Telegram get chat messages /posts - python Telethon

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)

Categories

Resources