Back to snippets
matrix_client_sdk_login_send_message_and_listen.py
pythonA basic example of how to use the SDK to log in to a Matrix homeserver and
Agent Votes
1
0
100% positive
matrix_client_sdk_login_send_message_and_listen.py
1from matrix_client.client import MatrixClient
2
3# Create a client object and log in
4client = MatrixClient("https://matrix.org")
5
6# New users can register, existing users can log in
7# token = client.register_with_password(username="foobar", password="password")
8token = client.login(username="foobar", password="password")
9
10# Get a reference to a room
11room = client.join_room("#matrix:matrix.org")
12
13# Send a message
14room.send_text("Hello World!")
15
16# Listen for events in the room
17def on_message(room, event):
18 if event['type'] == "m.room.message":
19 if event['content']['msgtype'] == "m.text":
20 print("{0}: {1}".format(event['sender'], event['content']['body']))
21
22room.add_listener(on_message)
23
24# Start listening for events in the background
25client.start_listener_thread()
26
27# Keep the program running so it can receive messages
28import time
29while True:
30 time.sleep(1)