AlexanderKazakov commited on
Commit
9ca6868
1 Parent(s): f830c64

try telethon

Browse files
tg_app/channel_by_link.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ from telethon import TelegramClient, events
4
+ from telethon.errors import ChannelPrivateError
5
+
6
+
7
+ logging.basicConfig(
8
+ format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s',
9
+ level=logging.WARNING
10
+ )
11
+
12
+
13
+ with open('data/tg_api_id.txt') as f:
14
+ api_id = f.read().strip()
15
+
16
+ with open('data/tg_app_api_hash.txt') as f:
17
+ api_hash = f.read().strip()
18
+
19
+ channel_link = 'https://t.me/redakciya_channel'
20
+ recipient = 'https://t.me/kazakov123'
21
+
22
+ client = TelegramClient('data/session.session', api_id, api_hash)
23
+
24
+
25
+ @client.on(events.NewMessage(chats=channel_link))
26
+ async def on_new_message(event):
27
+ if '#ньюсдня' in event.raw_text:
28
+ print(event.message)
29
+ else:
30
+ print('@@@ other message: ')
31
+ print(event.message)
32
+ await client.forward_messages(
33
+ entity=recipient,
34
+ messages=event.message.message,
35
+ from_peer=channel_link
36
+ )
37
+
38
+
39
+ async def check_channel():
40
+ try:
41
+ channel = await client.get_entity(channel_link)
42
+ print(f'Channel open: {channel.title}')
43
+ async for msg in client.iter_messages(entity=channel, limit=100):
44
+ if msg.message.lower().find('#ньюсдня') != -1:
45
+ print(f'Last message:')
46
+ print(msg.message)
47
+ break
48
+ print(f'Listening for new messages...')
49
+ except ChannelPrivateError:
50
+ print("The channel is private and you don't seem to have access.")
51
+ except ValueError as e:
52
+ print(f"An error occurred: {e}")
53
+
54
+
55
+ client.start()
56
+ client.loop.run_until_complete(check_channel())
57
+ client.run_until_disconnected()
58
+
59
+
tg_app/quick_start.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from telethon import TelegramClient
2
+
3
+
4
+ with open('data/tg_api_id.txt') as f:
5
+ api_id = f.read().strip()
6
+
7
+ with open('data/tg_app_api_hash.txt') as f:
8
+ api_hash = f.read().strip()
9
+
10
+ client = TelegramClient('data/session.session', api_id, api_hash)
11
+
12
+
13
+ async def main():
14
+ # Getting information about yourself
15
+ me = await client.get_me()
16
+
17
+ # "me" is a user object. You can pretty-print
18
+ # any Telegram object with the "stringify" method:
19
+ print(me.stringify())
20
+
21
+ # When you print something, you see a representation of it.
22
+ # You can access all attributes of Telegram objects with
23
+ # the dot operator. For example, to get the username:
24
+ username = me.username
25
+ print(username)
26
+ print(me.phone)
27
+
28
+ # You can print all the dialogs/conversations that you are part of:
29
+ async for dialog in client.iter_dialogs():
30
+ print(dialog.name, 'has ID', dialog.id)
31
+
32
+ # You can send messages to yourself...
33
+ await client.send_message('me', 'Hello, myselff!')
34
+ # # ...to some chat ID
35
+ # await client.send_message(-100123456, 'Hello, group!')
36
+ # # ...to your contacts
37
+ # await client.send_message('+34600123123', 'Hello, friend!')
38
+ # # ...or even to any username
39
+ # await client.send_message('username', 'Testing Telethon!')
40
+
41
+ # You can, of course, use markdown in your messages:
42
+ message = await client.send_message(
43
+ 'me',
44
+ 'This message has **bold**, `code`, __italics__ and '
45
+ 'a [nice website](https://example.com)!',
46
+ link_preview=False
47
+ )
48
+
49
+ # Sending a message returns the sent message object, which you can use
50
+ print(message.raw_text)
51
+
52
+ # You can reply to messages directly if you have a message object
53
+ await message.reply('Cool!')
54
+
55
+ # Or send files, songs, documents, albums...
56
+ # await client.send_file('me', '/home/me/Pictures/holidays.jpg')
57
+
58
+ # You can print the message history of any chat:
59
+ async for message in client.iter_messages('me'):
60
+ print(message.id, message.text)
61
+
62
+ # You can download media from messages, too!
63
+ # The method will return the path where the file was saved.
64
+ if message.photo:
65
+ path = await message.download_media()
66
+ print('File saved to', path) # printed after download is done
67
+
68
+ with client:
69
+ client.loop.run_until_complete(main())
70
+
tg_app/try_async_1.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+
3
+
4
+ async def f1():
5
+ for _ in range(10):
6
+ print(1, end='', flush=True)
7
+ await asyncio.sleep(0.2)
8
+
9
+
10
+ async def f2():
11
+ for _ in range(10):
12
+ print(2, end='', flush=True)
13
+ await asyncio.sleep(0.2)
14
+
15
+
16
+ async def f12():
17
+ """ неверно, скрипт закончится без ожидания завершения f1() и f2() """
18
+ asyncio.create_task(f1())
19
+ asyncio.create_task(f2())
20
+
21
+
22
+ async def f12wait():
23
+ """ дожидаемся завершения """
24
+ t1 = asyncio.create_task(f1())
25
+ t2 = asyncio.create_task(f2())
26
+ await t1
27
+ await t2
28
+
29
+
30
+ async def main():
31
+ await f1()
32
+ print()
33
+ await f2()
34
+ print()
35
+ # await f12()
36
+ # print()
37
+ await f12wait()
38
+
39
+
40
+ asyncio.run(main())
41
+
tg_app/try_async_2.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+
3
+
4
+ async def f1():
5
+ for _ in range(10):
6
+ yield 1
7
+ await asyncio.sleep(0.2)
8
+
9
+
10
+ async def f2():
11
+ for _ in range(10):
12
+ yield 2
13
+ await asyncio.sleep(0.2)
14
+
15
+
16
+ async def main():
17
+ async for i in f1():
18
+ print(i, end='', flush=True)
19
+ async for i in f2():
20
+ print(i, end='', flush=True)
21
+
22
+
23
+ asyncio.run(main())
24
+
tg_app/try_bot.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ from telethon import TelegramClient, events
4
+ from telethon.errors import ChannelPrivateError
5
+
6
+
7
+ logging.basicConfig(
8
+ format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s',
9
+ level=logging.WARNING
10
+ )
11
+
12
+
13
+ with open('data/tg_api_id.txt') as f:
14
+ api_id = f.read().strip()
15
+
16
+ with open('data/tg_app_api_hash.txt') as f:
17
+ api_hash = f.read().strip()
18
+
19
+ with open('data/tg_bot_token.txt') as f:
20
+ bot_token = f.read().strip()
21
+
22
+ channel_link = 'https://t.me/redakciya_channel'
23
+
24
+
25
+ client = TelegramClient('data/bot_session.session', api_id, api_hash)
26
+
27
+ """ для бота это всё не работает! """
28
+
29
+ @client.on(events.NewMessage(chats=channel_link))
30
+ async def on_new_message(event):
31
+ if '#ньюсдня' in event.raw_text:
32
+ print(event.message)
33
+ else:
34
+ print('@@@ other message: ')
35
+ print(event.message)
36
+
37
+
38
+ async def check_channel():
39
+ try:
40
+ channel = await client.get_entity(channel_link)
41
+ print(f'Channel open: {channel.title}')
42
+ async for msg in client.iter_messages(entity=channel, limit=100):
43
+ if msg.message.lower().find('#ньюсдня') != -1:
44
+ print(f'Last message:')
45
+ print(msg.message)
46
+ break
47
+ print(f'Listening for new messages...')
48
+ except ChannelPrivateError:
49
+ print("The channel is private and you don't seem to have access.")
50
+ except Exception as e:
51
+ print(f"An error occurred: {e}")
52
+
53
+ client.start(bot_token=bot_token)
54
+ client.loop.run_until_complete(check_channel())
55
+ client.run_until_disconnected()
56
+
57
+
58
+
tg_app/try_telethon.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from telethon import TelegramClient
2
+
3
+
4
+ with open('data/tg_api_id.txt') as f:
5
+ api_id = f.read().strip()
6
+
7
+ with open('data/tg_app_api_hash.txt') as f:
8
+ api_hash = f.read().strip()
9
+
10
+ with TelegramClient('data/session.session', api_id, api_hash) as client:
11
+ client.loop.run_until_complete(client.send_message('me', 'Hello, myself!'))
12
+
13
+
tg_app/updates_events.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ from telethon import TelegramClient, events
4
+
5
+
6
+ logging.basicConfig(
7
+ format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s',
8
+ level=logging.WARNING
9
+ )
10
+
11
+
12
+ with open('data/tg_api_id.txt') as f:
13
+ api_id = f.read().strip()
14
+
15
+ with open('data/tg_app_api_hash.txt') as f:
16
+ api_hash = f.read().strip()
17
+
18
+ client = TelegramClient('data/session.session', api_id, api_hash)
19
+
20
+ channel_of_interest_id = None
21
+
22
+
23
+ async def main():
24
+ global channel_of_interest_id
25
+ async for dialog in client.iter_dialogs():
26
+ if dialog.name.lower().find('редакция') != -1:
27
+ channel_of_interest_id = dialog.id
28
+ print(f'Tracking channel "{dialog.name}" with id: {channel_of_interest_id}')
29
+ break
30
+
31
+ assert channel_of_interest_id is not None
32
+
33
+ async for msg in client.iter_messages(entity=channel_of_interest_id, limit=100):
34
+ if msg.message.lower().find('#ньюсдня') != -1:
35
+ print(msg.message)
36
+ break
37
+
38
+
39
+ @client.on(events.NewMessage(incoming=True))
40
+ async def my_event_handler(event):
41
+ chat = await event.get_chat()
42
+ sender = await event.get_sender()
43
+ chat_id = event.chat_id
44
+ sender_id = event.sender_id
45
+ print(event.stringify())
46
+ # if 'hello' in event.raw_text:
47
+ # await event.reply('hi!')
48
+ # else:
49
+ # await event.reply('what?')
50
+
51
+ client.start()
52
+ client.loop.run_until_complete(main())
53
+ client.run_until_disconnected()