Reputation: 23
I need to develope a Gateway using the Telethon library: https://github.com/LonamiWebs/Telethon
The Gateway has to create a server socket where a telegram client is connected. When the Gateway receives a message from the socket (by the client), it sends the specific message to the Telegram server(through Telethon). When it receives an update from the telegram server, it sends the message to the client through the socket.
I have started with this code:
async def main(socket):
client = await TelegramClient(session_name, api_id, api_hash).start()
@client.on(events.NewMessage)
async def handler(event):
#new message, sending to the socket...
try:
mess = event.message.message
message = (mess).encode()
socket.send(message)
except Exception as e:
print("Exception: ",e)
await client.run_until_disconnected()
MAIN-->
print("Start program...")
HOST = '127.0.0.1'
PORT = 65436
print("Waiting connection at the port: ",PORT)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)
conn, addr = s.accept()
print("Connection OK!")
asyncio.get_event_loop().run_until_complete(main(conn))
This code, when receives a new message from the telegram server, will send correctly the message (through the socket) to the telegram client. The problem is that I don't known how to also listen from the socket and, when I receive a message (by the socket client), send it to the telegram server.
P.S. After the row await client.run_until_disconnected() I can't do anything.
Thank you very much!!!
Upvotes: 1
Views: 421
Reputation: 23
Sorry, my problem is the following:
async def main(socket):
client = await TelegramClient(session_name, api_id, api_hash).start()
@client.on(events.NewMessage)
async def handler(event):
#new message, sending to the socket...
try:
mess = event.message.message
message = (mess).encode()
socket.send(message)
except Exception as e:
print("Exception: ",e)
await client.run_until_disconnected()
while(1):
print("Waiting message from the client...")
data = socket.recv(1024)
mess = data.decode("utf-8")
print("Message Received: ",mess)
#self.telegramClient.send_message('PHONE', mess)
if name == "main":
print("Start program...")
HOST = '127.0.0.1'
PORT = 65431
print("Waiting connection at the port: ",PORT)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)
conn, addr = s.accept()
print("Connection OK!")
asyncio.get_event_loop().run_until_complete(main(conn))
The problem is this row: await client.run_until_disconnected()
Without this, my handler doesn't receive the upload. But if I insert this row, I can't wait for a message from the socket.
I hope that I have explained well my problem...
thank you very much!!
Upvotes: 1