We are listening to the telegraph chat with the help of our client

Somehow I wanted the messages of one of the telegraph chat rooms to be stored on my disk (without starting a regular client). I will not disclose my motives, but this opportunity seemed to me necessary and useful.


For this, there are bots in the telegram. On Habré there are several articles on bots, for example: " Chat assistant to the site ."


The bot allows you to read and send messages, you do not need a phone to register a bot and there can be any number of bots. But the name of the bot includes the word "bot", which may cause unnecessary questions to the chat host.


But as they say, the right question is half the answer.


It turns out that apart from the "API telegram bot" there is also the "API telegram client", i.e. API to create your own clients.


The client can also send and read messages, but only from a registered user (tied to the phone), which just suits me (I am already registered in the chat).


The telegraph site has a list of APIs for different platforms: https://telegram.org/apps#source-code


However, the easiest to use library was in python: Pure Python 3 MTProto API Telegram client library called "telethon"


Only here is the problem. I don't know python. Well, there is a reason to meet.
According to the teleton manual, its installation is very simple. Just run the command at the command prompt:


pip3 install telethon

Pitfalls I encountered during the installation:


  • pip3 not installed (installer for python).

sudo apt-get -y install python3-pip


  • The library works only on python version> 3.5. So, you may have to update it.

Everything is established. Scroll through the readme.txt further.


The next item is the creation of a telegraph client ... How, already? Well, yes, it's simple. True, you first need to register yourself as the creator of the client.


Go to the telegraph site: https://my.telegram.org
Enter the phone and wait for the confirmation code on the telegraph's native client. It is rather long (12 characters) and inconvenient for input.


Go to the item " API ". We are looking for the "Telegram API" and go to the "Creating an application" ( https://my.telegram.org/apps ).


Fill in the fields App title and Short name , click “Create application” and remember two variables: api_id and api_hash .


It's time to make a client.


from telethon import TelegramClient, sync
# Вставляем api_id и api_hash
api_id = 12345
api_hash = '0123456789abcdef0123456789abcdef'
client = TelegramClient('session_name', api_id, api_hash)
client.start()

session_name - you can insert any name. You will be asked to enter a phone number and send a confirmation code. After that, the client will work without a phone request (until you change the session_name). The session_name.session file will appear next to your program.


If there are no errors, the client is ready. Only here, displays nothing. Let's try to get useful information.


We learn a little about yourself:


print(client.get_me().stringify())

The result is given in the form:


User(
    photo=None,
    last_name='Pupkin',
    first_name='Vasya',
    id=123456789,
    phone='79041234567',
.... - что-то еще...
)

We can send a message from yourself:


client.send_message('username', 'Hello! Talking to you from Telethon')

Can and picture


client.send_file('username', '/home/myself/Pictures/holidays.jpg')

As others see me:


client.download_profile_photo('me')

We look at which chats we are subscribed to:


print all chats name
for dialog in client.iter_dialogs():
    print(dialog.title)

read all chat messages "chat_name" (carefully, there can be a lot of messages)


messages = client.get_entity('chat_name')
print(messages)

view all chat users


participants = client.get_participants('chat_name')
print(participants)

Indulged?
Now, in fact, we are doing something for which we all started this ...


We need a program that monitors new messages in a particular channel.


So that the client does not finish the work, after client.start () insert the line:


client.run_until_disconnected()

This construct (inserted before client.start ()) displays only new messages:


@client.on(events.NewMessage(chats=('chat_name')))
async def normal_handler(event):
#    print(event.message)
    print(event.message.to_dict()['message'])

Let's see.


@client.on(events.NewMessage(chats=('chat_name')))

creates an event that triggers when a new message appears


 print(event.message)

displays a message like this:


Message(edit_date=None, views=None, reply_markup=None, fwd_from=None, id=187, entities=[], post=False, mentioned=False, via_bot_id=None, media_unread=False, out=True, media=None, date=datetime.datetime(2018, 10, 1, 9, 26, 21, tzinfo=datetime.timezone.utc), to_id=PeerChannel(channel_id=123456789), reply_to_msg_id=None, from_id=123456789, silent=False, grouped_id=None, post_author=None, message='hello telegram')

From all this, we need a field: "message = 'hello telegram'":


    print(event.message.to_dict()['message'])

The message received, but from whom it is not clear, because In the message only user ID. To match the ID and username, download all chat users and put them into the dictionary (hash) in the form d [id] = "first_name last_name"


participants = client.get_participants(group)
users={}
for partic in client.iter_participants(group):
    lastname=""if partic.last_name:
       lastname=partic.last_name
    users[partic.id]=partic.first_name+" "+lastname

Now we can find out who sent the message:


s_user_id=event.message.to_dict()['from_id']
user_id=int(s_user_id)
user=d.get(user_id)

In principle, you can get the username from the telegram directly, but if there are few users, it is easier with a dictionary.


Pull from the message the date of sending:


mess_date=event.message.to_dict()['date']

All, all the data we have. It remains to write them to the file.
To do this, first open the file for writing:


f=open('messages_from_chat', 'a') 

And write the message:


f.write(mess_date.strftime("%d-%m-%Y %H:%M")+"\n")
f.write(user+"\n")
f.write(user_mess+"\n\n")
f.flush()

That's all! All I needed was a program. The utility, of course, is damp, but it does its job.


Python was not so difficult as it is painted , especially the description of various libraries on the Internet is full. Write a couple more utilitok and getting used to it, you can use it as a scripting language instead of bash.


All utility text:
from telethon import TelegramClient, sync, events
api_id = 12345
api_hash = '0123456789abcdef0123456789abcdef'
client = TelegramClient('session_name', api_id, api_hash)
@client.on(events.NewMessage(chats=('chat_name')))
async def normal_handler(event):
#    print(event.message)
    user_mess=event.message.to_dict()['message']
    s_user_id=event.message.to_dict()['from_id']
    user_id=int(s_user_id)
    user=d.get(user_id)
    mess_date=event.message.to_dict()['date']
    f.write(mess_date.strftime("%d-%m-%Y %H:%M")+"\n")
    f.write(user+"\n")
    f.write(user_mess+"\n\n")
    f.flush()
client.start()
group='group_name'
participants = client.get_participants(group)
users={}
for partic in client.iter_participants(group):
    lastname=""if partic.last_name:
       lastname=partic.last_name
    users[partic.id]=partic.first_name+" "+lastname
f=open('messages_from_chat', 'a') 
client.run_until_disconnected()
f.close()

Full description of the library .


Also popular now: