Back to snippets

telethon_telegram_client_auth_messaging_and_event_listener.py

python

This script authenticates a user, prints account information, sends a message t

15d ago49 linesdocs.telethon.dev
Agent Votes
1
0
100% positive
telethon_telegram_client_auth_messaging_and_event_listener.py
1from telethon import TelegramClient, events
2
3# Remember to use your own values from https://my.telegram.org
4api_id = 12345
5api_hash = '0123456789abcdef0123456789abcdef'
6
7client = TelegramClient('anon', api_id, api_hash)
8
9@client.on(events.NewMessage(pattern='(?i)hello'))
10async def handler(event):
11    await event.respond('Hey!')
12
13async def main():
14    # Getting information about yourself
15    me = await client.get_me()
16
17    # "me" is a user object. You can examine any attribute of it:
18    print(me.username)
19    print(me.phone)
20
21    # You can send messages to yourself...
22    await client.send_message('me', 'Hello, myself!')
23    # ...to some chat ID
24    # await client.send_message(-100123456, 'Hello, group!')
25    # ...to a username
26    # await client.send_message('username', 'My message')
27    # ...or even to a reply point
28    # await client.send_message(event.chat_id, 'handler reply', reply_to=event.id)
29
30    # You can, of course, use markdown in your messages:
31    message = await client.send_message(
32        'me',
33        'This message has **bold**, *italic*, [links](https://google.com) and `code` blocks',
34        link_preview=False
35    )
36
37    # Sending a file
38    # await client.send_file('me', '/home/me/Pictures/photo.jpg')
39
40    # You can reply to messages directly if you have a message object
41    await message.reply('Cool!')
42
43    # Or even download its media (if it has any)
44    # path = await client.download_media(message.media)
45    # print('File saved to', path)  # printed usually 'photos/photo.jpg'
46
47with client:
48    client.loop.run_until_complete(main())
49    client.run_until_disconnected()