Nio: A Python Matrix Client Library
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
- breaking Python 3.7 support was dropped in matrix-nio version 0.21.0. Users on older Python versions must upgrade to Python 3.8 or newer.
- breaking The `logbook` library was replaced with Python's standard `logging` module in version 0.21.0. Custom logging configurations using `logbook` will break and need to be adapted to `logging`.
- gotcha End-to-end encryption (E2EE) requires the `python-olm` package, which in turn needs the `libolm` C library (version 3.x) to be installed on your system. This C library is not installed automatically by `pip`.
- breaking As of version 0.25.1, `matrix-nio` uses authenticated media access (Authorization header) and requires the homeserver to be compliant with Matrix v1.11. This was introduced to restore support for matrix.org, which disabled unauthenticated media access.
Install
-
pip install matrix-nio -
pip install "matrix-nio[e2e]"
Imports
- AsyncClient
from nio import AsyncClient
- RoomMessageText
from nio import RoomMessageText
- LoginResponse
from nio import LoginResponse
Quickstart
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())