aboutsummaryrefslogtreecommitdiffstats
path: root/cogs/trigger.py
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--cogs/trigger.py84
1 files changed, 4 insertions, 80 deletions
diff --git a/cogs/trigger.py b/cogs/trigger.py
index 02e5573..ce80d43 100644
--- a/cogs/trigger.py
+++ b/cogs/trigger.py
@@ -7,13 +7,13 @@ import os
7import discord 7import discord
8from discord.ext import commands 8from discord.ext import commands
9import random 9import random
10import sqlite3
11import logging 10import logging
12 11
13logger = logging.getLogger(__name__) 12from cogs.utils.database import get_connection, init_database
14 13
14logger = logging.getLogger(__name__)
15 15
16DB_PATH = 'data/triggers.db' 16init_database()
17 17
18_SELECT_KEYWORD_SQL = "SELECT keyword FROM trigger_keywords WHERE trigger_id=?" 18_SELECT_KEYWORD_SQL = "SELECT keyword FROM trigger_keywords WHERE trigger_id=?"
19_SELECT_RESPONSE_SQL = "SELECT response_text FROM trigger_responses WHERE trigger_id=?" 19_SELECT_RESPONSE_SQL = "SELECT response_text FROM trigger_responses WHERE trigger_id=?"
@@ -22,88 +22,12 @@ _TRIGGER_NOT_FOUND_MSG = "Trigger not found."
22_TRIGGER_NAME_OPTION = "the name of the trigger" 22_TRIGGER_NAME_OPTION = "the name of the trigger"
23 23
24 24
25def get_connection():
26 return sqlite3.connect(DB_PATH)
27
28
29class Trigger(commands.Cog): 25class Trigger(commands.Cog):
30 def __init__(self, bot): 26 def __init__(self, bot):
31 self.bot = bot 27 self.bot = bot
32 self.db_check()
33 28
34 trigger_group = discord.SlashCommandGroup("trigger", "trigger commands") 29 trigger_group = discord.SlashCommandGroup("trigger", "trigger commands")
35 30
36 @staticmethod
37 def db_check():
38 if not os.path.exists('data'):
39 os.makedirs('data')
40
41 db_exists = os.path.exists(DB_PATH)
42 if not db_exists:
43 logger.warning("Triggers database not found. Creating new database.")
44
45 try:
46 conn = sqlite3.connect(DB_PATH)
47 c = conn.cursor()
48
49 # Enable foreign key constraints
50 c.execute('PRAGMA foreign_keys = ON')
51
52 # Create triggers table
53 c.execute('''
54 CREATE TABLE IF NOT EXISTS triggers (
55 id INTEGER PRIMARY KEY AUTOINCREMENT,
56 name TEXT NOT NULL UNIQUE,
57 created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
58 last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
59 )''')
60
61 # Create trigger_keywords table with foreign key constraint
62 c.execute('''
63 CREATE TABLE IF NOT EXISTS trigger_keywords (
64 id INTEGER PRIMARY KEY AUTOINCREMENT,
65 trigger_id INTEGER NOT NULL,
66 keyword TEXT NOT NULL,
67 created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
68 FOREIGN KEY (trigger_id) REFERENCES triggers(id) ON DELETE CASCADE,
69 UNIQUE(trigger_id, keyword)
70 )''')
71
72 # Create trigger_responses table with foreign key constraint
73 c.execute('''
74 CREATE TABLE IF NOT EXISTS trigger_responses (
75 id INTEGER PRIMARY KEY AUTOINCREMENT,
76 trigger_id INTEGER NOT NULL,
77 response_text TEXT NOT NULL,
78 created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
79 FOREIGN KEY (trigger_id) REFERENCES triggers(id) ON DELETE CASCADE
80 )''')
81
82 # Create indexes for better query performance
83 c.execute('CREATE INDEX IF NOT EXISTS idx_trigger_keywords_trigger_id ON trigger_keywords(trigger_id)')
84 c.execute('CREATE INDEX IF NOT EXISTS idx_trigger_keywords_keyword ON trigger_keywords(keyword)')
85 c.execute('CREATE INDEX IF NOT EXISTS idx_trigger_responses_trigger_id ON trigger_responses(trigger_id)')
86
87 # Run integrity check
88 integrity_check = c.execute('PRAGMA integrity_check').fetchone()
89 if integrity_check and integrity_check[0] == 'ok':
90 logger.info("Triggers database integrity check passed")
91 else:
92 logger.warning(f"Triggers database integrity check: {integrity_check}")
93
94 conn.commit()
95
96 except sqlite3.Error as e:
97 logger.error(f"Triggers database error: {e}")
98 raise
99
100 finally:
101 if 'conn' in locals():
102 conn.close()
103
104 if not db_exists:
105 logger.info("Triggers database initialized successfully")
106
107 @commands.Cog.listener() 31 @commands.Cog.listener()
108 async def on_message(self, message): 32 async def on_message(self, message):
109 if message.author == self.bot.user: 33 if message.author == self.bot.user:
@@ -130,7 +54,7 @@ class Trigger(commands.Cog):
130 54
131 @staticmethod 55 @staticmethod
132 def get_type(name): 56 def get_type(name):
133 with sqlite3.connect(DB_PATH) as conn: 57 with get_connection() as conn:
134 c = conn.cursor() 58 c = conn.cursor()
135 c.execute("SELECT name FROM triggers") 59 c.execute("SELECT name FROM triggers")
136 return [row[0] for row in c.fetchall()] 60 return [row[0] for row in c.fetchall()]