Nio: A Python Matrix Client Library

0.25.2 · active · verified Sat Apr 11

matrix-nio is a multilayered Python client library for the Matrix communication protocol, designed according to sans I/O principles. It provides a full-featured asyncio layer, leveraging aiohttp for network operations, and supports various Matrix features including end-to-end encryption. The library is actively maintained, with regular releases (current version 0.25.2) and ongoing feature development.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize an `AsyncClient`, log in, register a callback for text messages, and start an endless sync loop to receive events. It uses environment variables for sensitive login details.

import asyncio
import os
from nio import AsyncClient, RoomMessageText, LoginResponse

async def message_callback(room, event):
    """Callback for when a message is received."""
    print(f"Message in {room.display_name} from {room.user_name(event.sender)}: {event.body}")

async def main():
    homeserver = os.environ.get("MATRIX_HOMESERVER", "https://matrix.org")
    user_id = os.environ.get("MATRIX_USER_ID", "@your_username:matrix.org")
    password = os.environ.get("MATRIX_PASSWORD", "your_password")
    device_name = os.environ.get("MATRIX_DEVICE_NAME", "nio-bot")

    if user_id == "@your_username:matrix.org" or password == "your_password":
        print("Please set MATRIX_HOMESERVER, MATRIX_USER_ID, and MATRIX_PASSWORD environment variables.")
        return

    client = AsyncClient(homeserver, user_id)
    client.add_event_callback(message_callback, RoomMessageText)

    print(f"Attempting to login as {user_id}...")
    try:
        response = await client.login(password, device_name=device_name)
        if isinstance(response, LoginResponse):
            print(f"Logged in successfully with device ID: {response.device_id}")
        else:
            print(f"Login failed: {response.message}")
            return

        print("Starting sync loop...")
        await client.sync_forever(timeout=30000)
    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        await client.close()

if __name__ == "__main__":
    asyncio.run(main())

view raw JSON →