python telethon wait for reply - python

I currently have code to send message to my friend
but how can I know if he reply
this is my current code
please see the commented line
from telethon import TelegramClient
api_id = '1234567'
api_hash = 'MYHASH'
client = TelegramClient('session', api_id, api_hash)
client.start(phone_number)
destination_user_username='friend'
entity=client.get_entity(destination_user_username)
client.send_message(entity=entity,message="hello")
#if he reply hi
client.send_message(entity=entity,message="have a nice day")
how can I do this?

I found in the doc
solution 1
for message in client.iter_messages(chat):
print(message)
solution 2
api_id = '1234567'
api_hash = 'MYHASH'
with TelegramClient('session') as client:
destination_user_username='friend'
entity=client.get_entity(destination_user_username)
client.send_message(entity=entity,message="hello")
from telethon import events
#client.on(events.NewMessage(pattern='hi'))
async def handler(event):
# here received messgae, do something with event
print(dir(event)) # check all possible methods/operations/attributes
# reply once and then disconnect
await event.reply("have a nice day")
await client.disconnect()
client.run_until_disconnected()

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.

Telethon events.NewMessage(channelId) to read all message from a channel?

Im trying to create a python script that can read all messages in a chat channel. I found this code, however, this will only read the message that I write myself or are directed at me. How do I change this code so it can read all the messages in the channel?
from telethon import TelegramClient, events
api_id = 242...
api_hash = '8a06ca620417c9964a058e0dc...'
bot_token = '1474729480:AAEhUPmVX_m...'
channelId = -36744...
client = TelegramClient('bot', api_id, api_hash).start(bot_token=bot_token)
client.start()
#client.on(events.NewMessage(chats = [channelId]))
async def my_event_handler(event):
text = event.text
print(text)
client.run_until_disconnected()
You may use iter_messages to get previous messages

How to edit client massage in Telegram using python?

I need to edit last message sent with python. How can I do it?
from telethon import TelegramClient, events, sync
from telethon.tl.functions.messages import EditMessageRequest
# Remember to use your own values from my.telegram.org!
api_id = api_id
api_hash = api_hash
client = TelegramClient('anon', api_id, api_hash)
#client.on(events.NewMessage(chats='j'))
async def my_event_handler(event):
print(event.raw_text)
await client.send_message(event.chat_id,'dd')
event.edit_massge("")
client.start()
client.run_until_disconnected()
When I send a message I want the script to edit it to the text that I will enter.
from telethon import TelegramClient, events, sync
from telethon.tl.functions.messages import EditMessageRequest
# Remember to use your own values from my.telegram.org!
api_id = api_id
api_hash = api_hash
client = TelegramClient('anon', api_id, api_hash)
#client.on(events.NewMessage(chats='j'))
async def my_event_handler(event):
print(event.raw_text)
message = await client.send_message(event.chat_id, "hello") # changed line
await client.edit_message(event.chat_id, message, "hello!") # changed line
client.start()
client.run_until_disconnected()
In addition, you can only edit your own messages (just in case you want to edit a message from someone else)

Bot wrongly handle messages

I have little problem with writing my bot, I'm trying to send message only inside my bot, but my client handle any messages in any chats.
from telethon.sync import TelegramClient, events
import socks
api_id = 'my_id'
api_hash = 'my_hash'
client = TelegramClient('name', api_id, api_hash, proxy=###).start(bot_token='bot_token')
#client.on(events.NewMessage(pattern='/start'))
async def send_welcome(event):
await event.reply('How re you doing')
#client.on(events.NewMessage)
async def echo_all(event):
await event.reply(event.text)
client.run_until_disconnected()
You need to had func=lambda e: e.is_private into events.NewMessage() so the handler will only catch messages from private conversations (that's what you defined as "messages only inside your bot").
It will look like this:
#events.register(events.NewMessage(func=lambda e: e.is_private))
async def handler(event):
...

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