mirror of
https://github.com/alterware/aw-bot.git
synced 2025-10-26 14:15:54 +00:00
feat: DB for patterns
This commit is contained in:
@@ -3,6 +3,9 @@ from typing import Literal
|
||||
import discord
|
||||
from discord import app_commands
|
||||
|
||||
from database import add_pattern
|
||||
|
||||
from bot.config import update_patterns
|
||||
from bot.utils import compile_stats, fetch_game_stats, perform_search
|
||||
|
||||
GUILD_ID = 1110531063161299074
|
||||
@@ -25,6 +28,22 @@ async def setup(bot):
|
||||
|
||||
bot.tree.on_error = on_tree_error
|
||||
|
||||
@bot.tree.command(
|
||||
name="add_pattern",
|
||||
description="Add a new message pattern to the database.",
|
||||
guild=discord.Object(id=GUILD_ID),
|
||||
)
|
||||
@app_commands.checks.has_permissions(administrator=True)
|
||||
async def add_pattern_cmd(
|
||||
interaction: discord.Interaction, regex: str, response: str
|
||||
):
|
||||
"""Slash command to add a new message pattern to the database."""
|
||||
add_pattern(regex, response)
|
||||
update_patterns(regex, response)
|
||||
await interaction.response.send_message(
|
||||
f"Pattern added!\n**Regex:** `{regex}`\n**Response:** `{response}`"
|
||||
)
|
||||
|
||||
@bot.tree.command(
|
||||
name="search",
|
||||
description="Search for servers by hostname or IP.",
|
||||
|
||||
@@ -1,7 +1,43 @@
|
||||
import json
|
||||
import os
|
||||
from database import get_patterns, add_pattern
|
||||
|
||||
try:
|
||||
with open("patterns.json", "r") as f:
|
||||
message_patterns = json.load(f)
|
||||
except FileNotFoundError:
|
||||
message_patterns = [] # Fallback to an empty list if the file doesn't exist
|
||||
PATTERNS_FILE = "patterns.json"
|
||||
|
||||
BOT_DATA_DIR = os.getenv("BOT_DATA_DIR", "/bot-data")
|
||||
MIGRATION_FLAG = os.path.join(BOT_DATA_DIR, "migration_done.flag")
|
||||
|
||||
|
||||
def migrate_patterns():
|
||||
"""Migrate patterns.json to the database if not already done."""
|
||||
if os.path.exists(MIGRATION_FLAG):
|
||||
print("Not performing migration: already done")
|
||||
return
|
||||
|
||||
if not os.path.exists(PATTERNS_FILE):
|
||||
return
|
||||
|
||||
try:
|
||||
with open(PATTERNS_FILE, "r") as f:
|
||||
patterns = json.load(f)
|
||||
except (json.JSONDecodeError, FileNotFoundError):
|
||||
patterns = []
|
||||
|
||||
for pattern in patterns:
|
||||
add_pattern(pattern["regex"], pattern["response"])
|
||||
|
||||
with open(MIGRATION_FLAG, "w") as f:
|
||||
f.write("done")
|
||||
|
||||
print("Migration completed: patterns.json -> Database")
|
||||
|
||||
|
||||
migrate_patterns()
|
||||
|
||||
message_patterns = get_patterns()
|
||||
|
||||
|
||||
def update_patterns(regex: str, response: str):
|
||||
"""update patterns in memory."""
|
||||
message_patterns.append({"regex": regex, "response": response})
|
||||
print(f"Pattern added in memory: {regex}")
|
||||
|
||||
Reference in New Issue
Block a user