-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
245 lines (206 loc) · 8.31 KB
/
database.py
File metadata and controls
245 lines (206 loc) · 8.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import sqlite3
import json
from datetime import datetime
from typing import List, Dict, Optional
import os
class DatabaseManager:
"""Manages SQLite database operations for Nebula bot."""
def __init__(self, db_path: str = "nebula.db"):
"""Initialize database connection."""
self.db_path = db_path
self.init_database()
def get_connection(self):
"""Get a database connection."""
return sqlite3.connect(self.db_path)
def init_database(self):
"""Initialize database tables."""
conn = self.get_connection()
cursor = conn.cursor()
# Conversation history table
cursor.execute('''
CREATE TABLE IF NOT EXISTS conversation_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT NOT NULL,
channel_id TEXT NOT NULL,
user_id TEXT NOT NULL,
display_name TEXT NOT NULL,
role TEXT NOT NULL,
content TEXT NOT NULL,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
token_count INTEGER DEFAULT 0
)
''')
# User profiles table
cursor.execute('''
CREATE TABLE IF NOT EXISTS user_profiles (
user_id TEXT PRIMARY KEY,
display_name TEXT NOT NULL,
guild_id TEXT NOT NULL,
first_seen DATETIME DEFAULT CURRENT_TIMESTAMP,
last_seen DATETIME DEFAULT CURRENT_TIMESTAMP,
message_count INTEGER DEFAULT 0
)
''')
# Server settings table
cursor.execute('''
CREATE TABLE IF NOT EXISTS server_settings (
guild_id TEXT PRIMARY KEY,
settings JSON,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
''')
# Admin actions log table
cursor.execute('''
CREATE TABLE IF NOT EXISTS admin_actions_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id TEXT NOT NULL,
admin_id TEXT NOT NULL,
admin_name TEXT NOT NULL,
action_type TEXT NOT NULL,
target_id TEXT,
target_name TEXT,
details TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
''')
conn.commit()
conn.close()
print("Database initialized successfully")
def add_message(self, guild_id: str, channel_id: str, user_id: str,
display_name: str, role: str, content: str, token_count: int = 0):
"""Add a message to conversation history."""
conn = self.get_connection()
cursor = conn.cursor()
cursor.execute('''
INSERT INTO conversation_history
(guild_id, channel_id, user_id, display_name, role, content, token_count)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (guild_id, channel_id, user_id, display_name, role, content, token_count))
conn.commit()
conn.close()
def get_conversation_history(self, guild_id: str, channel_id: str,
limit: int = 50) -> List[Dict]:
"""Retrieve recent conversation history."""
conn = self.get_connection()
cursor = conn.cursor()
cursor.execute('''
SELECT display_name, role, content, timestamp, token_count
FROM conversation_history
WHERE guild_id = ? AND channel_id = ?
ORDER BY timestamp DESC
LIMIT ?
''', (guild_id, channel_id, limit))
messages = []
for row in cursor.fetchall():
messages.append({
'display_name': row[0],
'role': row[1],
'content': row[2],
'timestamp': row[3],
'token_count': row[4]
})
conn.close()
return list(reversed(messages)) # Return in chronological order
def get_total_tokens(self, guild_id: str, channel_id: str) -> int:
"""Get total token count for a conversation."""
conn = self.get_connection()
cursor = conn.cursor()
cursor.execute('''
SELECT SUM(token_count)
FROM conversation_history
WHERE guild_id = ? AND channel_id = ?
''', (guild_id, channel_id))
result = cursor.fetchone()[0]
conn.close()
return result if result else 0
def reset_conversation(self, guild_id: str, channel_id: str):
"""Reset conversation history for a channel."""
conn = self.get_connection()
cursor = conn.cursor()
cursor.execute('''
DELETE FROM conversation_history
WHERE guild_id = ? AND channel_id = ?
''', (guild_id, channel_id))
conn.commit()
conn.close()
print(f"Conversation history reset for guild {guild_id}, channel {channel_id}")
def update_user_profile(self, user_id: str, display_name: str, guild_id: str):
"""Update or create user profile."""
conn = self.get_connection()
cursor = conn.cursor()
cursor.execute('''
INSERT INTO user_profiles (user_id, display_name, guild_id, message_count)
VALUES (?, ?, ?, 1)
ON CONFLICT(user_id) DO UPDATE SET
display_name = excluded.display_name,
last_seen = CURRENT_TIMESTAMP,
message_count = message_count + 1
''', (user_id, display_name, guild_id))
conn.commit()
conn.close()
def get_user_activity(self, user_id: str, guild_id: str) -> Optional[Dict]:
"""Get user activity information."""
conn = self.get_connection()
cursor = conn.cursor()
# Get user profile
cursor.execute('''
SELECT display_name, first_seen, last_seen, message_count
FROM user_profiles
WHERE user_id = ? AND guild_id = ?
''', (user_id, guild_id))
profile = cursor.fetchone()
if not profile:
conn.close()
return None
# Get recent message count
cursor.execute('''
SELECT COUNT(*)
FROM conversation_history
WHERE user_id = ? AND guild_id = ?
AND timestamp > datetime('now', '-7 days')
''', (user_id, guild_id))
recent_messages = cursor.fetchone()[0]
conn.close()
return {
'display_name': profile[0],
'first_seen': profile[1],
'last_seen': profile[2],
'total_messages': profile[3],
'messages_last_7_days': recent_messages
}
def log_admin_action(self, guild_id: str, admin_id: str, admin_name: str,
action_type: str, target_id: str = None,
target_name: str = None, details: str = None):
"""Log an admin action."""
conn = self.get_connection()
cursor = conn.cursor()
cursor.execute('''
INSERT INTO admin_actions_log
(guild_id, admin_id, admin_name, action_type, target_id, target_name, details)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (guild_id, admin_id, admin_name, action_type, target_id, target_name, details))
conn.commit()
conn.close()
def get_admin_logs(self, guild_id: str, limit: int = 50) -> List[Dict]:
"""Retrieve admin action logs."""
conn = self.get_connection()
cursor = conn.cursor()
cursor.execute('''
SELECT admin_name, action_type, target_name, details, timestamp
FROM admin_actions_log
WHERE guild_id = ?
ORDER BY timestamp DESC
LIMIT ?
''', (guild_id, limit))
logs = []
for row in cursor.fetchall():
logs.append({
'admin_name': row[0],
'action_type': row[1],
'target_name': row[2],
'details': row[3],
'timestamp': row[4]
})
conn.close()
return logs