How to edit client massage in Telegram using python? - 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)

Related

Can't get NewMessage event on SuperGroup (SelfBot)

I'm trying to listen to supergroup new messages, but I can't seem to be able to:
from telethon.sync import TelegramClient
from telethon import events, utils
from telethon.tl.types import InputMessagesFilterPhotos
api_id = 98.....
api_hash = 'acbc55199.....'
num = '+921.......'
client = TelegramClient(num, api_id, api_hash)
client.connect()
if not client.is_user_authorized():
client.send_code_request(num)
client.sign_in(num, input('Code: '))
#client.on(events.NewMessage(chats=[-123456789]))
async def handler(event):
print(event.from_id.user_id)
It works on group I created and channels/groups I'm a member in, but it doesn't for supergroups.
Any idea if I'm doing anything wrong?

Telethon changes the name to the current time

I want my application to change my name in the telegram to the current time every minute. I have already tried to do something, but to no avail
from telethon import TelegramClient
from telethon.tl.functions.account import UpdateProfileRequest
import asyncio
import datetime
today = datetime.datetime.today()
time= today.strftime("%H.%M")
api_id = 123456
api_hash = 'ххх'
client = TelegramClient('session_name', api_id, api_hash)
client.start()
async def main():
while True:
await client(UpdateProfileRequest(first_name=time))
await asyncio.sleep(1)
client.loop.run_forever()
from telethon import TelegramClient
from telethon.tl.functions.account import UpdateProfileRequest
import asyncio
import datetime
api_id = 123456
api_hash = 'ххх'
client = TelegramClient('session_name', api_id, api_hash)
client.start()
async def main():
while True:
time = datetime.datetime.today().strftime("%H.%M")
async with client:
await client(UpdateProfileRequest(first_name=time))
await asyncio.sleep(60)
asyncio.get_event_loop().run_until_complete(main())
first stuff don't use while loop , it may use too memory and disable handle updates from telethon
second stuff 1 second its too fast and telegram may ban you account for spam
I prefer to use aiocron
Install aiocron using the following command
pip3 install aiocron
Code:
import asyncio, aiocron, datetime
from telethon import TelegramClient, events, sync, functions, types
from telethon.tl.functions.account import UpdateProfileRequest
api_id = 123456
api_hash = "ххх"
client = TelegramClient("session_name", api_id, api_hash)
client.start()
#aiocron.crontab("*/1 * * * *")
async def set_clock():
time = datetime.datetime.today().strftime("%H.%M")
async with client:
await client(UpdateProfileRequest(first_name=time))
#client.on(events.NewMessage)
async def e(event):
if event.raw_text == "ping":
await event.reply("pong")
client.run_until_disconnected()

python telethon wait for reply

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()

Telegram Telethon download media

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")

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):
...

Categories

Resources