Skip to content

Commit

Permalink
feat(matrix_handler): ✨ Ignore back-to-back messages to avoid send mu…
Browse files Browse the repository at this point in the history
…ltiple messages to customer
  • Loading branch information
egalvis39 committed Mar 4, 2024
1 parent 86ad721 commit 889348e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
4 changes: 4 additions & 0 deletions menuflow/example-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ menuflow:
start: 1
end: 3

# It defines how much time have to wait before receive a message in a room,
# it's to avoid send too much messages to the customer
message_rate_limit: 1 #seconds


server:
# The IP and port to listen to.
Expand Down
13 changes: 13 additions & 0 deletions menuflow/matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import asyncio
from copy import deepcopy
from datetime import datetime
from typing import Dict, Optional

from mautrix.client import Client as MatrixClient
Expand Down Expand Up @@ -36,6 +37,7 @@ def __init__(
self.flow = Flow(flow_utils=flow_utils, flow_mxid=self.mxid)
self.LOCKED_ROOMS = set()
self.LAST_JOIN_EVENT: Dict[RoomID, int] = {}
self.LAST_MESSAGE_RECEIVE: Dict[RoomID, datetime] = {}
Base.init_cls(
config=self.config,
session=self.api.session,
Expand Down Expand Up @@ -190,6 +192,17 @@ async def handle_message(self, message: MessageEvent) -> None:
)
return

current_message_time = datetime.fromtimestamp(message.timestamp / 1000)
last_message_time = self.LAST_MESSAGE_RECEIVE.get(message.room_id)
if (
last_message_time
and (current_message_time - last_message_time).seconds
< self.config["menuflow.message_rate_limit"]
):
self.log.warning(f"Message in {message.room_id} ignored due to rate limit")
return

self.LAST_MESSAGE_RECEIVE[message.room_id] = current_message_time
room: Room = await Room.get_by_room_id(room_id=message.room_id, bot_mxid=self.mxid)
room.config = self.config = self.config
room.matrix_client = self
Expand Down

0 comments on commit 889348e

Please sign in to comment.