forked from nolan/titlebot-ng-ng
Mayhem mode
This commit is contained in:
@@ -12,6 +12,7 @@ import re
|
||||
import asyncio
|
||||
from nio import AsyncClient, LoginResponse, RoomMessageText, SyncResponse, RoomSendResponse
|
||||
from post import Post
|
||||
import requests
|
||||
|
||||
default_search_terms = ["!suggest", "!Suggest", "!suggestion", "!Suggestion", "SUGGEST", "!sug"]
|
||||
|
||||
@@ -93,6 +94,19 @@ class Room:
|
||||
UNIQUE(sender, timestamp)
|
||||
)
|
||||
''')
|
||||
|
||||
# New: table to log all !mayhem detections (prevents duplicates)
|
||||
c.execute('''
|
||||
CREATE TABLE IF NOT EXISTS mayhem (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
event_id TEXT,
|
||||
sender TEXT,
|
||||
timestamp INTEGER,
|
||||
datetime TEXT,
|
||||
UNIQUE(event_id),
|
||||
UNIQUE(sender, timestamp)
|
||||
)
|
||||
''')
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
@@ -169,13 +183,48 @@ class Room:
|
||||
|
||||
self.posts.append(post)
|
||||
break
|
||||
|
||||
# Remove the !mayhem handling from here entirely
|
||||
fetched += len(response.chunk)
|
||||
print(f"Looked back on {fetched} messages...", end="\r", flush=True)
|
||||
next_batch = getattr(response, "end", None)
|
||||
if not next_batch:
|
||||
break
|
||||
|
||||
# Uses ollama to generate mayhem text
|
||||
def generate_mayhem(self):
|
||||
ollama_model = "llama3.2:1b" #title_config.get("ollama_model", "llama3.2:1b")
|
||||
ollama_url = "http://localhost:11434" #title_config.get("ollama_url", "http://localhost:11434")
|
||||
|
||||
prompt = f"Generate for me the most unhinged, mayhem, insane ramblings that would make a mad man look sane"
|
||||
|
||||
try:
|
||||
response = requests.post(
|
||||
f"{ollama_url}/api/generate",
|
||||
json={
|
||||
"model":ollama_model,
|
||||
"prompt": prompt,
|
||||
"stream": False,
|
||||
"options": {
|
||||
"temperature": 0.8,
|
||||
"top_p": 0.9,
|
||||
}
|
||||
|
||||
},
|
||||
timeout=60
|
||||
)
|
||||
|
||||
if response.status_code==200:
|
||||
result = response.json()
|
||||
return result.get("response", "")
|
||||
else:
|
||||
return " Couldn't do it for some reason."
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
return f"Couldn't connect to ollama: {e}"
|
||||
except Exception as e:
|
||||
return f"Unexpected error: {e}"
|
||||
|
||||
|
||||
def write_to_db(self):
|
||||
conn = sqlite3.connect(self.db_path)
|
||||
c = conn.cursor()
|
||||
@@ -254,13 +303,28 @@ class Room:
|
||||
conn.close()
|
||||
return inserted
|
||||
|
||||
# All this does is wait until someone says the trigger word
|
||||
async def wait_for_gettitles(self, since_ms=None, exact=True):
|
||||
# New: record a !mayhem detection; returns True if newly recorded (not duplicate)
|
||||
def record_mayhem(self, sender, timestamp, event_id=None):
|
||||
"""Record a !mayhem detection; returns True if newly recorded (not duplicate)"""
|
||||
conn = sqlite3.connect(self.db_path)
|
||||
c = conn.cursor()
|
||||
dt_str = datetime.datetime.fromtimestamp(int(timestamp)).isoformat(sep=' ', timespec='seconds')
|
||||
c.execute('''
|
||||
INSERT OR IGNORE INTO mayhem (event_id, sender, timestamp, datetime)
|
||||
VALUES (?, ?, ?, ?)
|
||||
''', (event_id, sender, int(timestamp), dt_str))
|
||||
inserted = c.rowcount == 1
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return inserted
|
||||
|
||||
# Renamed and expanded to handle both !gettitles and !mayhem commands
|
||||
async def wait_for_commands(self, since_ms=None):
|
||||
"""Wait for and handle commands like !gettitles and !mayhem"""
|
||||
# If no since_ms provided, start listening from "now"
|
||||
if since_ms is None:
|
||||
since_ms = int(_time.time() * 1000)
|
||||
|
||||
# ...existing code...
|
||||
while True:
|
||||
sync_response = await self.client.sync(timeout=30000)
|
||||
if not isinstance(sync_response, SyncResponse):
|
||||
@@ -278,16 +342,29 @@ class Room:
|
||||
if event.sender == self.user_id:
|
||||
continue
|
||||
body = event.body.strip()
|
||||
# Tighten trigger to exact match unless overridden
|
||||
if (exact and body == "!gettitles") or (not exact and body.startswith("!gettitles")):
|
||||
# New: log and prevent duplicate detections using DB
|
||||
|
||||
# Handle !gettitles
|
||||
if body == "!gettitles":
|
||||
event_id = getattr(event, "event_id", None)
|
||||
ts_seconds = int(getattr(event, "server_timestamp", 0) // 1000)
|
||||
if not self.record_gettitles(event.sender, ts_seconds, event_id):
|
||||
# Already processed this !gettitles, skip it
|
||||
continue
|
||||
print("!gettitles detected")
|
||||
return
|
||||
return "gettitles"
|
||||
|
||||
# Handle !mayhem
|
||||
elif body.startswith("!mayhem"):
|
||||
event_id = getattr(event, "event_id", None)
|
||||
ts_seconds = int(getattr(event, "server_timestamp", 0) // 1000)
|
||||
if self.record_mayhem(event.sender, ts_seconds, event_id):
|
||||
await self.alert_post("Standby. Ollama is being instructed to generate mayhem. This may take a moment...")
|
||||
await self.alert_post(self.generate_mayhem())
|
||||
|
||||
# Keep the old method name for backward compatibility but mark as deprecated
|
||||
async def wait_for_gettitles(self, since_ms=None, exact=True):
|
||||
"""DEPRECATED: Use wait_for_commands() instead. This method only handles !gettitles."""
|
||||
result = await self.wait_for_commands(since_ms)
|
||||
return result == "gettitles"
|
||||
|
||||
async def alert_post(self, post):
|
||||
content = {
|
||||
|
||||
Reference in New Issue
Block a user