-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmessage_db.py
More file actions
79 lines (71 loc) · 2.6 KB
/
message_db.py
File metadata and controls
79 lines (71 loc) · 2.6 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
import sqlite3
from datetime import datetime, timedelta
_db_connection = None
def init_db():
"""Initialize the database and create tables if they don't exist."""
global _db_connection
try:
_db_connection = sqlite3.connect('messages.db')
c = _db_connection.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS messages
(id TEXT PRIMARY KEY,
content TEXT,
author TEXT,
timestamp DATETIME,
channel_id TEXT)''')
_db_connection.commit()
except Exception as e:
print(f"Error initializing database: {e}")
if _db_connection:
_db_connection.close()
_db_connection = None
def close_db_connection():
"""Close the database connection if it exists."""
global _db_connection
try:
if _db_connection:
_db_connection.commit()
_db_connection.close()
_db_connection = None
print("Database connection closed successfully")
except Exception as e:
print(f"Error closing database: {e}")
def store_message(message):
"""Store a Discord message in the database."""
conn = sqlite3.connect('messages.db')
c = conn.cursor()
try:
c.execute('INSERT OR IGNORE INTO messages VALUES (?,?,?,?,?)',
(str(message.id),
message.content,
str(message.author),
message.created_at,
str(message.channel.id)))
conn.commit()
except sqlite3.IntegrityError:
print(f"Message {message.id} already exists")
except Exception as e:
print(f"Error storing message: {e}")
finally:
conn.close()
def get_daily_messages(channel_ids=None):
"""Get messages from the last 24 hours."""
conn = sqlite3.connect('messages.db')
c = conn.cursor()
twenty_four_hours_ago = datetime.utcnow() - timedelta(hours=24)
try:
if channel_ids:
channels_str = ','.join(f"'{ch}'" for ch in channel_ids)
query = f'''SELECT content, author, timestamp, channel_id
FROM messages
WHERE timestamp >= ? AND channel_id IN ({channels_str})'''
c.execute(query, (twenty_four_hours_ago,))
else:
c.execute('''SELECT content, author, timestamp, channel_id
FROM messages
WHERE timestamp >= ?''',
(twenty_four_hours_ago,))
results = c.fetchall()
return results
finally:
conn.close()