I'm happy to help you create a script that uses matrix-commander to listen to encrypted messages from a specific Matrix room. First, make sure you've installed matrix-commander and the required dependencies. You can do this by following the installation instructions in the matrix-commander GitHub repository: https://github.com/8go/matrix-commander
Here's an example script that listens to messages from a specific Matrix room:
import sys
import os
from matrix_client.client import MatrixClient
# Callback function for handling messages
def on_message(room, event):
if event['type'] == "m.room.message" and event['content']['msgtype'] == "m.text":
print(f"{room.display_name}[{room.room_id}]: {event['content']['body']}")
# Read access token, user ID, and device ID from environment variables
matrix_user = os.environ["MATRIX_USER"]
matrix_password = os.environ["MATRIX_PASSWORD"]
matrix_server = os.environ["MATRIX_SERVER"]
matrix_room_id = os.environ["MATRIX_ROOM_ID"]
# Create a Matrix client and connect
client = MatrixClient(matrix_server)
try:
token = open("token.txt", "r").read().strip()
matrix_user = open("userid.txt", "r").read().strip()
matrix_device_id = open("deviceid.txt", "r").read().strip()
client.load_config(matrix_user, token, matrix_device_id)
except FileNotFoundError:
# If the token is not found, log in with the username and password
client.login_with_password(matrix_user, matrix_password)
# Join the target room and add message callback
room = client.join_room(matrix_room_id)
room.add_listener(on_message)
# Start listening for messages
client.start_listener_thread()
# Allow the script to run indefinitely
try:
while True:
pass
except KeyboardInterrupt:
client.stop_listener_thread()
sys.exit(0)
Before running the script, make sure you have exported the following environment variables:
MATRIX_USER: Your Matrix username (e.g., "@example:matrix.org")
MATRIX_PASSWORD: Your Matrix password
MATRIX_SERVER: The Matrix server URL (e.g., "https://matrix.org")
MATRIX_ROOM_ID: The Matrix room ID where you want to listen to encrypted messages
You can export these variables in shell by using export:
export MATRIX_USER="@example:matrix.org"
export MATRIX_PASSWORD="yourpassword"
export MATRIX_SERVER="https://matrix.org"
export MATRIX_ROOM_ID="!yourroomidgoeshere:matrix.org"
Once you've set up your environment variables, run the script using Python 3:
python3 listen_encrypted_messages.py
Now your script will print the received messages from the specified Matrix room. Keep in mind that matrix-commander should be set up properly for encryption before running the script. Make sure your target room has encryption enabled, and matrix-commander has the required dependencies for end-to-end encryption.