matrix-readfridge

git clone https://git.tarina.org/matrix-readfridge
Log | Files | Refs

server.py (1154B)


      1 import asyncio
      2 from nio import AsyncClient
      3 import config
      4 
      5 async def handle_echo(reader, writer):
      6     client = AsyncClient(config.matrixserver, config.username)
      7     await client.login(config.password)
      8 
      9     data = await reader.read(512)
     10     message = data.decode()
     11     addr = writer.get_extra_info('peername')
     12     print("Received %r from %r" % (message, addr))
     13     writer.write(data)
     14     await writer.drain()
     15     print("Send: %r" % message)
     16     print("Close the client socket")
     17     writer.close()
     18     print('sending msg to matrix')
     19     await client.room_send(
     20         room_id=config.room_id,
     21         message_type="m.room.message",
     22         content={
     23             "msgtype": "m.text",
     24             "body": message
     25         }
     26     )
     27     await client.close()
     28 
     29 loop = asyncio.get_event_loop()
     30 coro = asyncio.start_server(handle_echo, '127.0.0.1', 8888, loop=loop)
     31 server = loop.run_until_complete(coro)
     32 
     33 # Serve requests until Ctrl+C is pressed
     34 print('Serving on {}'.format(server.sockets[0].getsockname()))
     35 try:
     36     loop.run_forever()
     37 except KeyboardInterrupt:
     38     pass
     39 
     40 # Close the server
     41 server.close()
     42 loop.run_until_complete(server.wait_closed())
     43 loop.close()