Hello Code Review community !
I'm making a bot with discord.py that listens to every message sent in a server and stores it in a database that could be retrieved by admin/mod later.
Here's the structure of the database currently
guild_id = guild.id
statements = [
f"""
CREATE TABLE guild{guild_id}_members (
id BIGSERIAL PRIMARY KEY NOT NULL,
user_id bigint UNIQUE NOT NULL
);
""",
f"""
CREATE TABLE guild{guild_id}_messages (
id BIGSERIAL PRIMARY KEY NOT NULL,
member_id INTEGER NOT NULL,
at_time TIMESTAMP NOT NULL,
message VARCHAR(2000) NOT NULL,
CONSTRAINT fk_memberid
FOREIGN KEY(member_id)
REFERENCES guild{guild_id}_members(id)
ON UPDATE CASCADE
ON DELETE CASCADE
);
"""
]
sql_queries(self.conn, statements)
(sql_queries basically is just a function for executing each statement one after the other then commit)
Then i use on_message event from discord.py that executes this part of the code:
@commands.Cog.listener()
async def on_message(self, message):
if message.content == '': #or message.author.id == self.logbot.user.id:
return
guild_id = message.guild.id
author_id = message.author.id
at_time = message.created_at
statement = f"""
INSERT INTO guild{guild_id}_members (user_id)
VALUES ('{author_id}')
ON CONFLICT DO NOTHING;
"""
sql_query(self.conn, statement)
statement = f"""
SELECT id FROM guild{guild_id}_members
WHERE user_id = '{author_id}';
"""
member_id = int(sql_select(self.conn, statement)[0])
print(f'{member_id}')
statement = f"""
INSERT INTO guild{guild_id}_messages (member_id, at_time, message)
VALUES ('{member_id}', '{at_time}', '{message.content}')
"""
sql_query(self.conn, statement)
To explain further, first i create a user identity in my guild{guild_id}_members (with unique constraint) then i select the id through a select query to use it to insert the message with the id i just got from the select query.
I know it's optimizable but i don't know how.
Thank you for reading me. :)
EDIT : Here's my sql_query and my sql_select functions : Sql query :
def sql_query(conn, statement):
cur = conn.cursor()
cur.execute(str(statement))
conn.commit()
Sql Select :
def sql_select(conn, statement):
cur = conn.cursor()
cur.execute(str(statement))
return cur.fetchone()
commands.Cog.listener
come from? \$\endgroup\$commands.Cog.listener
come from? It comes from discord.py library >And can you show your source for sql_query sql query is basically 3 lines, it just executes the query then commit with the cursor \$\endgroup\$