feat: implement hourly ratelimits for triggers using SHSF db
All checks were successful
Lint and Syntax Check / build (pull_request) Successful in 5s
All checks were successful
Lint and Syntax Check / build (pull_request) Successful in 5s
This commit is contained in:
37
main.py
37
main.py
@@ -10,6 +10,7 @@ OPENCLAW_MODEL = os.getenv("OPENCLAW_MODEL")
|
||||
DATABASE_STORAGE = os.getenv("DATABASE_STORAGE_NAME")
|
||||
AGENT_USERNAME = os.getenv("AGENT_USERNAME")
|
||||
AGENT_PROMPT_FILE = os.getenv("AGENT_PROMPT_FILE")
|
||||
AGENT_HOURLY = int(os.getenv("AGENT_HOURLY", 60))
|
||||
|
||||
eventsToHandle = ["pull_request", "issues", "issue_comment"]
|
||||
actionsToHandle = ["assigned", "created"]
|
||||
@@ -118,7 +119,34 @@ def build_message(event_object, action_str, type_str):
|
||||
return message
|
||||
|
||||
|
||||
def sendToAgent(event_object):
|
||||
def check_ratelimit(db):
|
||||
try:
|
||||
cooldown_key = f"agent_{AGENT_USERNAME}_cooldown"
|
||||
current_data = db.get(DATABASE_STORAGE, cooldown_key)
|
||||
|
||||
import time
|
||||
|
||||
now = int(time.time())
|
||||
one_hour_ago = now - 3600
|
||||
|
||||
if current_data:
|
||||
timestamps = [int(ts) for ts in current_data.split(",") if int(ts) > one_hour_ago]
|
||||
else:
|
||||
timestamps = []
|
||||
|
||||
if len(timestamps) >= AGENT_HOURLY:
|
||||
print(f"Ratelimit hit: {len(timestamps)}/{AGENT_HOURLY} in the last hour.")
|
||||
return False
|
||||
|
||||
timestamps.append(now)
|
||||
db.set(DATABASE_STORAGE, cooldown_key, ",".join(map(str, timestamps)))
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"Failed to check ratelimit: {e}")
|
||||
return True
|
||||
|
||||
|
||||
def sendToAgent(event_object, db):
|
||||
headers = {"x-openclaw-token": OPENCLAW_TOKEN, "Content-Type": "application/json"}
|
||||
|
||||
if event_object.get("type") == "issue_comment":
|
||||
@@ -141,6 +169,9 @@ def sendToAgent(event_object):
|
||||
)
|
||||
return
|
||||
|
||||
if not check_ratelimit(db):
|
||||
return
|
||||
|
||||
message = build_message(event_object, action_str, type_str)
|
||||
|
||||
try:
|
||||
@@ -347,7 +378,7 @@ def main(args):
|
||||
|
||||
# Send to OpenClaw
|
||||
if action == "assigned":
|
||||
sendToAgent(event_object)
|
||||
sendToAgent(event_object, db)
|
||||
else:
|
||||
print(f"Action {action} is not configured to send to agent")
|
||||
|
||||
@@ -378,7 +409,7 @@ def main(args):
|
||||
print(f"Repo: {event_object['repository']}")
|
||||
print(f"By: {event_object['sender']}")
|
||||
|
||||
sendToAgent(event_object)
|
||||
sendToAgent(event_object, db)
|
||||
|
||||
return {
|
||||
"_shsf": "v2",
|
||||
|
||||
Reference in New Issue
Block a user