I run this test code:
import telethon.sync
from telethon import TelegramClient
from telethon.tl.functions.messages import AddChatUserRequest
from telethon.tl.functions.contacts import ImportContactsRequest
api_id = XXXXXXX
api_hash = 'XXXXXXXXXXXXXXC'
with TelegramClient('anon', api_id, api_hash) as client:
async def main():
client(AddChatUserRequest(-XXXXXXXXXXXXXX, ['username'], fwd_limit=10))
main()
And it gives me this:
/data/data/ru.iiec.pydroid3/files/temp_iiec_codefile.py:19: RuntimeWarning: coroutine 'main' was never awaited
main()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
What should I do to make the program work?
Take a look at telethon documentation, see how it starts event loop:
from telethon import TelegramClient
api_id = 12345
api_hash = '0123456789abcdef0123456789abcdef'
client = TelegramClient('anon', api_id, api_hash)
async def main():
me = await client.get_me()
# etc.
with client:
client.loop.run_until_complete(main())
Related
Telethon event handler waits 1 minute before sending out a burst of messages at the same time.
I tried removing functions from other souces as I thought that could be it and it did not work.
code:
`
from telethon import TelegramClient, events
import logging
import time
#from main import add
logging.basicConfig(format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s', level=logging.WARNING)
api_id =
api_hash =
client = TelegramClient('anon', api_id, api_hash)
#client.on(events.NewMessage)
async def my_event_handler(event):
print(event.raw_text)
#add(event.raw_text)
client.start()
client.run_until_disconnected()
`
form me work ok and i have testet
python need to run all time
#exit()
import sys
from telethon import TelegramClient, events
import logging
import time
import telethon.tl.functions as _fn
logging.basicConfig(format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s', level=logging.WARNING)
api_id = row[2]
api_hash = row[3]
client = TelegramClient(path+str(api_id), api_id, api_hash)
#client.on(events.NewMessage)
async def my_event_handler(event):
print(event.raw_text)
print(event)
#add(event.raw_text)
client.start()
client.run_until_disconnected()
print('Finish...')
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)
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()
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 : '))
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