Skip to content

Commit 03ab72b

Browse files
Feat: Make log level configurable via LOG_LEVEL environment variable
- Modifies `matrix_bot.py` to read the `LOG_LEVEL` environment variable (defaulting to INFO) and set the Python logging level accordingly. - Adds `LOG_LEVEL` to `.env.example`. - Updates `README.md` to document the new `LOG_LEVEL` configuration option.
1 parent 38b115a commit 03ab72b

3 files changed

Lines changed: 19 additions & 12 deletions

File tree

.env.example

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,7 @@ ALLOWED_INVITER_USER_ID="@youradminuser:matrix.org" # IMPORTANT: The Matrix User
99
# If not set, defaults to sample.config/alts.json and sample.config/services.json relative to the script
1010
# MATRIX_BOT_ALTS_JSON_PATH="/path/to/your/alts.json"
1111
# MATRIX_BOT_SERVICES_JSON_PATH="/path/to/your/services.json"
12+
13+
# Optional: Set the logging level for the bot.
14+
# Valid values: DEBUG, INFO, WARNING, ERROR, CRITICAL. Defaults to INFO if not set or invalid.
15+
# LOG_LEVEL="INFO"

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ ALLOWED_INVITER_USER_ID="@adminuser:matrix.org" # Full Matrix User ID of the per
4545
- `ALLOWED_INVITER_USER_ID`: Crucial for security. This is the full Matrix ID of the user who has permission to invite the bot into rooms. The bot will ignore invites from anyone else.
4646
- `MATRIX_BOT_ALTS_JSON_PATH` (Optional): Specifies a custom path to the `alts.json` file. If not set, the bot defaults to looking for `sample.config/alts.json` relative to the `matrix_bot.py` script (or `/app/sample.config/alts.json` inside Docker).
4747
- `MATRIX_BOT_SERVICES_JSON_PATH` (Optional): Specifies a custom path to the `services.json` file. If not set, the bot defaults to looking for `sample.config/services.json` relative to the `matrix_bot.py` script (or `/app/sample.config/services.json` inside Docker).
48+
- `LOG_LEVEL` (Optional): Sets the logging level for the bot. Valid values are `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL`. Defaults to `INFO` if not set or if an invalid value is provided. For example, set `LOG_LEVEL="DEBUG"` for more verbose output.
4849

4950
The `alts.json` and `services.json` files define the link substitution rules. By default, the bot expects these to be in the `sample.config/` directory. You can customize their location using the environment variables above. Sample files are provided in `sample.config/`.
5051

matrix_bot.py

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,17 @@
1212
from nio import AsyncClient, LoginError, RoomMessageText, MatrixRoom, RoomMemberEvent
1313

1414
# Configure logging
15+
# Log level will be set based on environment variable LOG_LEVEL
16+
log_level_str = os.environ.get("LOG_LEVEL", "INFO").upper()
17+
log_level = getattr(logging, log_level_str, logging.INFO) # Fallback to INFO if invalid
18+
1519
logging.basicConfig(
16-
level=logging.INFO,
20+
level=log_level,
1721
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
1822
)
1923
logger = logging.getLogger(__name__)
24+
logger.info(f"Logging level set to: {logging.getLevelName(logger.getEffectiveLevel())}")
25+
2026

2127
# Global ALTS and SERVICES dictionaries
2228
ALTS = {}
@@ -220,11 +226,11 @@ async def main():
220226
if not allowed_inviter_user_id:
221227
logger.warning("ALLOWED_INVITER_USER_ID not set. Bot will not accept any invites.")
222228

223-
# Initialize bot_startup_time here, before callbacks that might use it are defined.
224-
# Though it's set again later, this makes its scope clear.
229+
# Initialize bot_startup_time here. It will be set properly before sync_forever.
225230
bot_startup_time = 0
226231

227-
# Define callbacks first
232+
# Define callbacks using decorators, now that 'client' is initialized.
233+
@client.on(RoomMemberEvent)
228234
async def on_room_invite_callback(room: MatrixRoom, event: RoomMemberEvent):
229235
logger.debug("on_room_invite_callback: Entered function.")
230236
if event.membership != "invite" or event.state_key != client.user_id:
@@ -251,13 +257,14 @@ async def on_room_invite_callback(room: MatrixRoom, event: RoomMemberEvent):
251257
except Exception as e:
252258
logger.error(f"Failed to leave (reject) room {room.room_id}: {e}", exc_info=True)
253259

260+
@client.on(RoomMessageText)
254261
async def message_handler_callback(room: MatrixRoom, event: RoomMessageText):
255262
# This callback reads bot_startup_time from the enclosing main() scope
256263
logger.debug(
257264
f"Message received in room {room.room_id} ({room.display_name}) | Sender: {event.sender} | Body: {event.body}"
258265
)
259266

260-
if event.server_timestamp <= bot_startup_time:
267+
if event.server_timestamp <= bot_startup_time: # Uses bot_startup_time from main's scope
261268
logger.debug(f"Ignoring old message from {event.sender} with timestamp {event.server_timestamp} (startup: {bot_startup_time})")
262269
return
263270

@@ -298,16 +305,11 @@ async def message_handler_callback(room: MatrixRoom, event: RoomMessageText):
298305
else:
299306
logger.debug(f"No replies generated for message from {event.sender} in room {room.room_id}.")
300307

301-
# Set the actual startup timestamp before registering callbacks that use it
308+
# Set the actual startup timestamp *before* starting the sync loop that uses it.
302309
bot_startup_time = int(time.time() * 1000)
303310
logger.info(f"Bot startup timestamp set to: {bot_startup_time}")
311+
logger.info("Callbacks are defined using decorators. Starting sync_forever...")
304312

305-
logger.info("Registering event callbacks...")
306-
client.add_event_callback(on_room_invite_callback, RoomMemberEvent)
307-
client.add_event_callback(message_handler_callback, RoomMessageText)
308-
logger.info("Event callbacks registered.")
309-
310-
logger.info("Starting sync with server (full_state=True for initial sync)...")
311313
try:
312314
# full_state=True on the first run of sync_forever will get initial room states.
313315
# nio handles the transition from initial sync to subsequent incremental syncs.

0 commit comments

Comments
 (0)