Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Telegram's websocket

I want to connect to the telegram's WebSocket or other protocol, to receive every message. I was inspecting the network tab in dev tools, but I could not find any WebSocket protocol, however, when I entered console, I can see [SW] on message {type: "ping", localNotifications: true, lang: {…}, settings: {…}} Which convince me, that it is sent to maintain connection with the WebSocket. I tried a telethon library for python, but it allows me only to show all messages in the chat.

from telethon import TelegramClient
import asyncio
client = TelegramClient(name, api_id, api_hash)
client.start()
for i in client.iter_dialogs():
    if i.name == 'test':
        chj = i
async def main():

    channel = await client.get_entity(chj)
    messages = await client.get_messages(channel, limit= None) #pass your own args

    #then if you want to get all the messages text
    for x in messages:
        print(x) #return message.text

"""for i in client.iter_dialogs():
    print(i)"""
loop = asyncio.get_event_loop()
loop.run_until_complete(main())

I want to be getting messages like in WebSocket whenever on the desired chat someone's types something

like image 468
Aleksander Ikleiw Avatar asked Oct 29 '25 08:10

Aleksander Ikleiw


1 Answers

I have found an answer. This can be achieved using events from telethon library

from telethon import TelegramClient, events

name = 'test'

api_id = 1234
api_hash = 'hash'
client = TelegramClient(name, api_id, api_hash)

@client.on(events.NewMessage())
async def newMessageListener(event):
    newMessage = event.message.message
    print(newMessage)
with client:
    client.run_until_disconnected()
like image 88
Aleksander Ikleiw Avatar answered Oct 30 '25 23:10

Aleksander Ikleiw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!