Connection error while using telethon through python? - python

here is the code which I am using to operate telegram through python. But on running this, I am getting an error.
import asyncio
from telethon import TelegramClient,connection
api_id = xxxxxx
api_hash = 'xxxxxxxxxxx'
client = TelegramClient('anon', api_id, api_hash,
connection=connection.ConnectionTcpMTProxyRandomizedIntermediate,
proxy=('mtproxy.example.com', 2002, 'secret'))
async def main():
# Getting information about yourself
me = await client.get_me()
print('hello')
await main()
when I run this code, I get ConnectionError: Cannot send requests while disconnected

Related

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)

TelegramClient is getting an error (method was never awaited)

I'm trying to send a message to a telegram channel for each new message in the API, But I'm sure that I'm not respecting the telethon documentation that I don't understand quitly.
Here is my code:
import requests, json
from telethon import TelegramClient, events, sync
class notify:
async def tele_message(discord_message):
api_id = 1111111
api_hash = 'hidden-hidden-hidden-hidden'
destination_user_username='gikou2'
client = await TelegramClient('anon', api_id, api_hash)
entity= await client.get_entity(destination_user_username)
await client.send_message(entity=entity,message=discord_message)
await client.start()
await client.run_until_disconnected()
headers = {
'authorization': 'authorization-authorization-authorization-authorization',
}
params = (('limit', '50'),)
read_mess = list()
while True:
response = requests.get('https://discord.com/api/v9/channels/292516924557099008/messages', headers=headers, params=params)
for message in reversed(response.json()):
if message['id'] not in read_mess:
read_mess.append(message['id'])
if message['author']['username'] == 'Noah Williams':
print(message['content'])
# client.send_file(destination_user_username, media, caption=event.raw_text)
notify.tele_message(message['content'])
First thing you don't need to make ansync function for TelegramClient and if its import for you then you have to also use wait while using the tele_message(ur func)
Maybe i am wrong but you can try

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

Telethon verions 1.11.3 with python 3.7.3 not seems to be working

Upon trying following code on Telethon 1.11.3 , python 3.7.3
from telethon import TelegramClient
api_id = xxx #i give my id
api_hash = xxx##i give my
client = TelegramClient(name, api_id, api_hash)
async def main():
# Now you can use all client methods listed below, like for example...
await client.send_message('me', 'Hello to myself!')
with client:
client.loop.run_until_complete(main())
I get error as RuntimeError: You must use "async with" if the event loop is running (i.e. you are inside an "async def")
The problem is not the code itself but the shell you used. IPython and similar run the asyncio event loop which break Telethon's sync magic.
To work around this, you can use a normal python shell or write async and await in the right places:
from telethon import TelegramClient
api_id = ...
api_hash = ...
client = TelegramClient(name, api_id, api_hash)
async def main():
# Now you can use all client methods listed below, like for example...
await client.send_message('me', 'Hello to myself!')
# Note the async and await keywords
async with client:
await main()
Of course, in this scenario, main() is not really necessary either:
async with client:
await client.send_message('me', 'Hello to myself!')
# Create an object for TelegramClient()
client = TelegramClient(phone, api_id, api_hash)
async with client :
await client.send_message('me', 'Hello!!!!!')
client.connect()
if not client.is_user_authorized() :
client.send_code_request(phone)
client.sign_in(phone, input('Enter verification code : '))

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