From d0064aea463fec914fa231bcb399a9c5887a3587 Mon Sep 17 00:00:00 2001 From: Jeremiah K <17190268+jeremiah-k@users.noreply.github.com> Date: Fri, 4 Oct 2024 21:34:25 -0500 Subject: [PATCH 1/6] update matrix-nio to 0.25.2 --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 1c83a44..267e331 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,7 @@ meshtastic Pillow==9.5.0 py-staticmaps==0.4.0 -matrix-nio==0.20.2 +matrix-nio==0.25.2 matplotlib==3.9.0 requests==2.31.0 markdown==3.4.3 From d16e83bea639469f368e3ea378e0cbee9a94ff5f Mon Sep 17 00:00:00 2001 From: Jeremiah K <17190268+jeremiah-k@users.noreply.github.com> Date: Fri, 4 Oct 2024 21:44:44 -0500 Subject: [PATCH 2/6] Remove login call since we're using an access token --- main.py | 21 +++++++++++---------- matrix_utils.py | 4 ++++ 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/main.py b/main.py index 58f3a15..9349eb6 100644 --- a/main.py +++ b/main.py @@ -1,10 +1,7 @@ -""" -This script connects a Meshtastic mesh network to Matrix chat rooms by relaying messages between them. -It uses Meshtastic-python and Matrix nio client library to interface with the radio and the Matrix server respectively. -""" import asyncio import signal import sys +import logging # Add this line from typing import List from nio import RoomMessageText, RoomMessageNotice @@ -34,6 +31,9 @@ matrix_rooms: List[dict] = relay_config["matrix_rooms"] matrix_access_token = relay_config["matrix"]["access_token"] +# Set the logging level for 'nio' to ERROR to suppress warnings +logging.getLogger('nio').setLevel(logging.ERROR) # Add this line + async def main(): """ Main asynchronous function to set up and run the relay. @@ -53,12 +53,13 @@ async def main(): # Connect to Matrix matrix_client = await connect_matrix() - matrix_logger.info("Connecting to Matrix...") - try: - await matrix_client.login(matrix_access_token) - except Exception as e: - matrix_logger.error(f"Error connecting to Matrix server: {e}") - return + # Remove the login call since we're using an access token + # matrix_logger.info("Connecting to Matrix...") + # try: + # await matrix_client.login(matrix_access_token) + # except Exception as e: + # matrix_logger.error(f"Error connecting to Matrix server: {e}") + # return # Join the rooms specified in the config.yaml for room in matrix_rooms: diff --git a/matrix_utils.py b/matrix_utils.py index 61cddd3..7d05e99 100644 --- a/matrix_utils.py +++ b/matrix_utils.py @@ -54,6 +54,10 @@ async def connect_matrix(): matrix_homeserver, bot_user_id, config=config, ssl=ssl_context ) matrix_client.access_token = matrix_access_token + matrix_client.user_id = bot_user_id # Add this line + matrix_client.logged_in = True # Add this line + + # Fetch the bot's display name response = await matrix_client.get_displayname(bot_user_id) bot_user_name = response.displayname return matrix_client From 26fcfa75a457a2224134e0ea2bd2efbe8596de01 Mon Sep 17 00:00:00 2001 From: Jeremiah K <17190268+jeremiah-k@users.noreply.github.com> Date: Fri, 4 Oct 2024 21:55:30 -0500 Subject: [PATCH 3/6] Updates for latest matrix-nio --- main.py | 4 ++++ matrix_utils.py | 11 +++++++---- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/main.py b/main.py index 9349eb6..1dc8053 100644 --- a/main.py +++ b/main.py @@ -1,3 +1,7 @@ +""" +This script connects a Meshtastic mesh network to Matrix chat rooms by relaying messages between them. +It uses Meshtastic-python and Matrix nio client library to interface with the radio and the Matrix server respectively. +""" import asyncio import signal import sys diff --git a/matrix_utils.py b/matrix_utils.py index 7d05e99..cc4adf9 100644 --- a/matrix_utils.py +++ b/matrix_utils.py @@ -51,11 +51,14 @@ async def connect_matrix(): # Initialize the Matrix client with custom SSL context config = AsyncClientConfig(encryption_enabled=False) matrix_client = AsyncClient( - matrix_homeserver, bot_user_id, config=config, ssl=ssl_context + homeserver=matrix_homeserver, + user=bot_user_id, # Pass bot_user_id as 'user' + config=config, + ssl=ssl_context, + access_token=matrix_access_token, # Pass access_token here ) - matrix_client.access_token = matrix_access_token - matrix_client.user_id = bot_user_id # Add this line - matrix_client.logged_in = True # Add this line + + # No need to set matrix_client.user_id or matrix_client.logged_in # Fetch the bot's display name response = await matrix_client.get_displayname(bot_user_id) From a294afb1d01f2665f14dbb74637ba51d09fdf00f Mon Sep 17 00:00:00 2001 From: Jeremiah K <17190268+jeremiah-k@users.noreply.github.com> Date: Fri, 4 Oct 2024 22:02:16 -0500 Subject: [PATCH 4/6] authenticate using the login method with the access token --- main.py | 11 +++-------- matrix_utils.py | 19 ++++++++++++++----- 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/main.py b/main.py index 1dc8053..9f217d5 100644 --- a/main.py +++ b/main.py @@ -56,14 +56,9 @@ async def main(): # Connect to Matrix matrix_client = await connect_matrix() - - # Remove the login call since we're using an access token - # matrix_logger.info("Connecting to Matrix...") - # try: - # await matrix_client.login(matrix_access_token) - # except Exception as e: - # matrix_logger.error(f"Error connecting to Matrix server: {e}") - # return + if matrix_client is None: + logger.error("Failed to connect to Matrix. Exiting.") + return # Join the rooms specified in the config.yaml for room in matrix_rooms: diff --git a/matrix_utils.py b/matrix_utils.py index cc4adf9..056b59f 100644 --- a/matrix_utils.py +++ b/matrix_utils.py @@ -12,6 +12,8 @@ RoomMessageText, RoomMessageNotice, UploadResponse, + LoginResponse, + LoginError, ) from config import relay_config from log_utils import get_logger @@ -52,20 +54,27 @@ async def connect_matrix(): config = AsyncClientConfig(encryption_enabled=False) matrix_client = AsyncClient( homeserver=matrix_homeserver, - user=bot_user_id, # Pass bot_user_id as 'user' + user=bot_user_id, config=config, ssl=ssl_context, - access_token=matrix_access_token, # Pass access_token here ) - # No need to set matrix_client.user_id or matrix_client.logged_in + # Log in using the access token + login_response = await matrix_client.login(token=matrix_access_token) + if isinstance(login_response, LoginError): + logger.error(f"Failed to login: {login_response.message}") + return None + + # Now we are logged in # Fetch the bot's display name response = await matrix_client.get_displayname(bot_user_id) - bot_user_name = response.displayname + if hasattr(response, 'displayname'): + bot_user_name = response.displayname + else: + bot_user_name = bot_user_id # Fallback if display name is not set return matrix_client - async def join_matrix_room(matrix_client, room_id_or_alias: str) -> None: """Join a Matrix room by its ID or alias.""" try: From 04a1566de600a7c22cb9a986fe1832b1ed08c0b6 Mon Sep 17 00:00:00 2001 From: Jeremiah K <17190268+jeremiah-k@users.noreply.github.com> Date: Fri, 4 Oct 2024 22:08:28 -0500 Subject: [PATCH 5/6] Initialize without device_id --- main.py | 1 - matrix_utils.py | 16 ++++++---------- 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/main.py b/main.py index 9f217d5..bf34654 100644 --- a/main.py +++ b/main.py @@ -33,7 +33,6 @@ # Extract Matrix configuration matrix_rooms: List[dict] = relay_config["matrix_rooms"] -matrix_access_token = relay_config["matrix"]["access_token"] # Set the logging level for 'nio' to ERROR to suppress warnings logging.getLogger('nio').setLevel(logging.ERROR) # Add this line diff --git a/matrix_utils.py b/matrix_utils.py index 056b59f..e12f479 100644 --- a/matrix_utils.py +++ b/matrix_utils.py @@ -2,9 +2,8 @@ import time import re import certifi -import io import ssl -from typing import List, Union +from typing import List from nio import ( AsyncClient, AsyncClientConfig, @@ -12,8 +11,6 @@ RoomMessageText, RoomMessageNotice, UploadResponse, - LoginResponse, - LoginError, ) from config import relay_config from log_utils import get_logger @@ -59,13 +56,11 @@ async def connect_matrix(): ssl=ssl_context, ) - # Log in using the access token - login_response = await matrix_client.login(token=matrix_access_token) - if isinstance(login_response, LoginError): - logger.error(f"Failed to login: {login_response.message}") - return None + # Set the access_token and user_id + matrix_client.access_token = matrix_access_token + matrix_client.user_id = bot_user_id - # Now we are logged in + # Now we can proceed without the device_id # Fetch the bot's display name response = await matrix_client.get_displayname(bot_user_id) @@ -73,6 +68,7 @@ async def connect_matrix(): bot_user_name = response.displayname else: bot_user_name = bot_user_id # Fallback if display name is not set + return matrix_client async def join_matrix_room(matrix_client, room_id_or_alias: str) -> None: From 635a490ad5b45ea1ce1b88919cdca99307aebf55 Mon Sep 17 00:00:00 2001 From: Jeremiah K <17190268+jeremiah-k@users.noreply.github.com> Date: Fri, 4 Oct 2024 22:12:36 -0500 Subject: [PATCH 6/6] Attempt to retrieve the device_id using whoami() --- matrix_utils.py | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/matrix_utils.py b/matrix_utils.py index e12f479..6c41a12 100644 --- a/matrix_utils.py +++ b/matrix_utils.py @@ -3,7 +3,7 @@ import re import certifi import ssl -from typing import List +from typing import List, Union from nio import ( AsyncClient, AsyncClientConfig, @@ -11,6 +11,8 @@ RoomMessageText, RoomMessageNotice, UploadResponse, + WhoamiResponse, + WhoamiError, ) from config import relay_config from log_utils import get_logger @@ -60,7 +62,17 @@ async def connect_matrix(): matrix_client.access_token = matrix_access_token matrix_client.user_id = bot_user_id - # Now we can proceed without the device_id + # Attempt to retrieve the device_id using whoami() + whoami_response = await matrix_client.whoami() + if isinstance(whoami_response, WhoamiError): + logger.error(f"Failed to retrieve device_id: {whoami_response.message}") + matrix_client.device_id = None + else: + matrix_client.device_id = whoami_response.device_id + if matrix_client.device_id: + logger.info(f"Retrieved device_id: {matrix_client.device_id}") + else: + logger.warning("device_id not returned by whoami()") # Fetch the bot's display name response = await matrix_client.get_displayname(bot_user_id)