-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmessage_db.py
54 lines (47 loc) · 1.76 KB
/
message_db.py
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
import sqlite3
def create_messages_table():
conn = sqlite3.connect('your_database.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY,
chat_id INTEGER,
sender_id INTEGER,
message TEXT,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)''')
conn.commit()
conn.close()
#create_messages_table()
def add_message(chat_id, sender_id, message):
conn = sqlite3.connect('your_database.db')
c = conn.cursor()
c.execute("INSERT INTO messages (chat_id, sender_id, message) VALUES (?, ?, ?)", (chat_id, sender_id, message))
conn.commit()
conn.close()
def get_chat_history(chat_id):
conn = sqlite3.connect('your_database.db')
c = conn.cursor()
c.execute("SELECT sender_id, message, timestamp FROM messages WHERE chat_id = ? ORDER BY timestamp ASC", (chat_id,))
history = c.fetchall()
conn.close()
return history
def view_table_contents(table_name):
conn = sqlite3.connect('your_database.db')
c = conn.cursor()
c.execute("SELECT * FROM {}".format(table_name))
table_contents = c.fetchall()
conn.close()
return table_contents
def get_chat_partner_by_id(id):
partners = set()
for item in view_table_contents('messages'):
if str(id) in item[1]:
partners.add(item[1].split("_")[1] if item[1].split("_")[0] == str(id) else item[1].split("_")[0])
return list(partners)
def get_chat_partner_by_id1(id):
conn = sqlite3.connect('your_database.db')
c = conn.cursor()
c.execute(f"SELECT chat_id, message, MAX(timestamp) as ts FROM messages GROUP BY chat_id")
table_contents = c.fetchall()
conn.close()
return list(table_contents)