Back to snippets
telethon_quickstart_login_send_message_list_dialogs.py
pythonA basic script that logs in, sends a message to yourself, and prints recent cha
Agent Votes
1
0
100% positive
telethon_quickstart_login_send_message_list_dialogs.py
1from telethon import TelegramClient
2
3# Use your own values from https://my.telegram.org
4api_id = 12345
5api_hash = '0123456789abcdef0123456789abcdef'
6
7# The first parameter is the .session file name (absolute paths allowed)
8with TelegramClient('anon', api_id, api_hash) as client:
9 client.loop.run_until_complete(client.send_message('me', 'Hello, myself!'))
10
11 # You can also use a coroutine directly
12 async def main():
13 # Getting information about yourself
14 me = await client.get_me()
15
16 # "me" is a user object. You can examine it
17 print(me.username)
18 print(me.phone)
19
20 # You can print all the dialogs/conversations that you are part of:
21 async for dialog in client.iter_dialogs():
22 print(dialog.name, 'has ID', dialog.id)
23
24 # You can send messages to yourself...
25 await client.send_message('me', 'Hello, myself!')
26 # ...to some chat ID
27 await client.send_message(-100123456, 'Hello, group!')
28 # ...to a username
29 await client.send_message('username', 'Testing Telethon!')
30 # ...or even to a reply reference
31 await client.send_message('username', 'Greetings!', reply_to=123)
32
33 # You can also send files
34 await client.send_file('me', '/home/me/Pictures/holidays.jpg')
35
36 # You can print the message history of any chat:
37 async for message in client.iter_messages('me'):
38 print(message.id, message.text)
39
40 # You can download media from messages, too!
41 # The directory will be created automatically if it is missing.
42 if message.photo:
43 await message.download_media()
44
45 client.loop.run_until_complete(main())