-
Notifications
You must be signed in to change notification settings - Fork 0
Introduction
Matrix.py is a simple, developer-friendly Python library designed to help you build powerful bots on the Matrix protocol. The library provides a clean, event-driven API built around Python's async/await syntax, with easy command registration and handler management so developers can focus on bot behavior instead of boilerplate setup.
Matrix.py is built on top of the popular Matrix client library matrix-nio.
Before using Matrixpy, you should have:
- Python 3.10 or higher installed.
- A Matrix account to act as the bot's identity.
Matrixpy can be installed easily using pip:
pip install matrix-pythonBefore installing Matrix.py, it's strongly recommended to create a virtual environment. This keeps dependencies isolated and avoids conflicts with other Python projects.
- Create a venv
python -m venv venv- Activate the venv On Linux/macOS:
source venv/bin/activateOn Windows (PowerShell):
venv\Scripts\ActivateIf you want to work with the latest development version or contribute to Matrix.py, clone the repository:
git clone https://github.com/Code-Society-Lab/matrixpy.git
cd matrixpyThen install the package with development dependencies:
pip install -e .[dev]Once installed, you'll need to configure a bot by providing:
- A username (Matrix ID) and password.
- Optionally, a server or homeserver URL if not using the default (matrix.org).
Create a file named config.yaml:
USERNAME: "@yourbot:matrix.org"
PASSWORD: "your_password"Then load it when creating your bot instance:
from matrix import Bot
bot = Bot(config="config.yaml")Note
For full details on available config options and examples, see the Config documentation in the Matrix.py Wiki: Configuration
Matrix.py bots are built around two simple ideas:
- Events: things that happen in a Matrix room
- Commands: messages your bot reacts to on purpose
Matrix is an event-based system: messages, joins, reactions, and more are all delivered as events.
Matrix.py allows you to listen to these events using the @bot.event decorator.
For example, to react whenever a message is sent:
from matrix import Bot, Context
from matrix.bot import MatrixRoom, RoomMessageText
bot = Bot(config="config.yaml")
@bot.event
async def on_message(matrix_room: MatrixRoom, event: RoomMessageText):
print(f"Message received from {event.sender}: {event.body}")Commands are a type of message handler that only trigger when a user sends a message starting with the bot's prefix (default "!"). They simplify building interactive bot features.
from matrix import Context
@bot.command()
async def ping(ctx: Context):
await ctx.send("Pong!")Now, when a user sends !ping the bot will answer Pong!.
Commands can accept arguments, which are automatically parsed from the user's message:
@bot.command()
async def say(ctx: Context, *, text: str):
await ctx.send(text)Warning
Bots do not support encrypted rooms yet.