Implemented better mariadb Connection handling

This commit is contained in:
jmueller
2023-12-18 15:27:54 +01:00
parent bee606c4bb
commit 5f0a86cced

464
main.py
View File

@@ -16,24 +16,28 @@ else:
if os.path.exists(".env"): if os.path.exists(".env"):
load_dotenv() load_dotenv()
class DBConnection:
def __init__(self):
self.user = config["db_user"]
self.password = config["db_password"]
self.host = config["db_host"]
self.database = config["db_name"]
def connect_db(): def __enter__(self):
try: self.conn = mariadb.connect(user=self.user, password=self.password,
conn = mariadb.connect( host=self.host, database=self.database)
user=config["db_user"], self.cursor = self.conn.cursor()
password=config["db_password"], return self.cursor
host=config["db_host"],
port=3306,
database=config["db_name"]
)
return conn
except mariadb.Error as e:
print(f"Error connecting to MariaDB Platform: {e}")
sys.exit(1)
def recruit_update(member, recruit, cur, conn): def __exit__(self, exc_type, exc_val, exc_tb):
cur.execute("INSERT INTO recruits (discord_id, nickname, recruit) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE nickname=?, recruit=?;", (member.id, member.display_name, recruit, member.display_name, recruit)) self.conn.commit()
conn.commit() self.cursor.close()
self.conn.close()
def recruit_update(member, recruit):
with DBConnection() as cur:
cur.execute("INSERT INTO recruits (discord_id, nickname, recruit) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE nickname=?, recruit=?;", (member.id, member.display_name, recruit, member.display_name, recruit))
intents = discord.Intents.default() intents = discord.Intents.default()
@@ -59,15 +63,13 @@ async def on_ready():
bot.add_view(report_buttons()) bot.add_view(report_buttons())
print(f"{bot.user} is ready and online!") print(f"{bot.user} is ready and online!")
conn = connect_db()
cur = conn.cursor()
# create Slash Command group with bot.create_group # create Slash Command group with bot.create_group
settings = bot.create_group("set", "Einstellungen") settings = bot.create_group("set", "Einstellungen")
def get_count_recruits(real = 0): def get_count_recruits(real = 0):
cur.execute("SELECT count(*) FROM recruits WHERE recruit=1") with DBConnection() as cur:
count = cur.fetchone()[0] cur.execute("SELECT count(*) FROM recruits WHERE recruit=1")
count = cur.fetchone()[0]
if real == 0: if real == 0:
if count > 25: if count > 25:
count = count / 2 count = count / 2
@@ -75,9 +77,10 @@ def get_count_recruits(real = 0):
def build_option_list(part=1): def build_option_list(part=1):
cur.execute("SELECT discord_id, nickname, recruit FROM recruits WHERE recruit=1") with DBConnection() as cur:
cur.execute("SELECT discord_id, nickname, recruit FROM recruits WHERE recruit=1")
records = cur.fetchall()
options = [] options = []
records = cur.fetchall()
count = get_count_recruits(1) count = get_count_recruits(1)
counter = 0 counter = 0
if count <= 25: if count <= 25:
@@ -102,13 +105,13 @@ def build_option_list(part=1):
def insert_yes_vote(recruit_id, voter_id): def insert_yes_vote(recruit_id, voter_id):
cur.execute("SELECT discord_id_recruit, discord_id_voter FROM yes_votes WHERE discord_id_recruit = ? AND discord_id_voter = ?", (recruit_id, voter_id)) with DBConnection() as cur:
result = cur.fetchone() cur.execute("SELECT discord_id_recruit, discord_id_voter FROM yes_votes WHERE discord_id_recruit = ? AND discord_id_voter = ?", (recruit_id, voter_id))
if result is None: result = cur.fetchone()
cur.execute("INSERT INTO yes_votes(discord_id_recruit, discord_id_voter) VALUES (?, ?)", (recruit_id, voter_id)) if result is None:
conn.commit() cur.execute("INSERT INTO yes_votes(discord_id_recruit, discord_id_voter) VALUES (?, ?)", (recruit_id, voter_id))
cur.execute("SELECT nickname FROM recruits WHERE discord_id = ?", (recruit_id, )) cur.execute("SELECT nickname FROM recruits WHERE discord_id = ?", (recruit_id, ))
return cur.fetchone()[0] return cur.fetchone()[0]
async def send_yes_confirm(select, interaction): async def send_yes_confirm(select, interaction):
message = "Du hast für folgende Rekruten mit **Ja** abgestimmt:\n\n" message = "Du hast für folgende Rekruten mit **Ja** abgestimmt:\n\n"
@@ -128,9 +131,9 @@ class yes_question_cause_overlap(discord.ui.View):
vote_ids = [] vote_ids = []
@discord.ui.button(label="Nein-Stimmen löschen und mit Ja stimmen", style=discord.ButtonStyle.primary) @discord.ui.button(label="Nein-Stimmen löschen und mit Ja stimmen", style=discord.ButtonStyle.primary)
async def yes(self, button, interaction): async def yes(self, button, interaction):
for vote_id in self.vote_ids: with DBConnection() as cur:
cur.execute("DELETE FROM no_votes WHERE id = ?", (vote_id, )) for vote_id in self.vote_ids:
conn.commit() cur.execute("DELETE FROM no_votes WHERE id = ?", (vote_id, ))
await self.message.delete() await self.message.delete()
await send_yes_confirm(self.select, interaction) await send_yes_confirm(self.select, interaction)
@discord.ui.button(label="Abbrechen", style=discord.ButtonStyle.secondary) @discord.ui.button(label="Abbrechen", style=discord.ButtonStyle.secondary)
@@ -155,10 +158,11 @@ async def process_yes_vote(select, interaction):
) )
yes_question_cause_overlap_inst = yes_question_cause_overlap() yes_question_cause_overlap_inst = yes_question_cause_overlap()
for yes_vote in select.values: for yes_vote in select.values:
cur.execute( with DBConnection() as cur:
"SELECT recruits.nickname, no_votes.reason, no_votes.id FROM recruits, no_votes WHERE no_votes.discord_id_recruit = recruits.discord_id AND no_votes.discord_id_voter = ? AND no_votes.discord_id_recruit = ?", cur.execute(
(interaction.user.id, yes_vote)) "SELECT recruits.nickname, no_votes.reason, no_votes.id FROM recruits, no_votes WHERE no_votes.discord_id_recruit = recruits.discord_id AND no_votes.discord_id_voter = ? AND no_votes.discord_id_recruit = ?",
result = cur.fetchall() (interaction.user.id, yes_vote))
result = cur.fetchall()
if result: if result:
found = True found = True
overlap_embed.add_field(name=result[0][0], value=result[0][1]) overlap_embed.add_field(name=result[0][0], value=result[0][1])
@@ -223,14 +227,15 @@ async def send_yes_message(channel):
message = await channel.send(embed=create_yes_embed(), view=Yes_select_inst25) message = await channel.send(embed=create_yes_embed(), view=Yes_select_inst25)
else: else:
message = await channel.send(embed=create_yes_embed(), view=Yes_select_inst50) message = await channel.send(embed=create_yes_embed(), view=Yes_select_inst50)
cur.execute("UPDATE settings SET VALUE = ? WHERE name = 'message_voting_yes'", (message.id, )) with DBConnection() as cur:
cur.execute("UPDATE settings SET VALUE = ? WHERE name = 'message_voting_yes'", (message.id, ))
async def edit_yes_message(): async def edit_yes_message():
cur.execute("SELECT value FROM settings WHERE name='channel_voting'") with DBConnection() as cur:
channel = bot.get_channel(int(cur.fetchone()[0])) cur.execute("SELECT value FROM settings WHERE name='channel_voting'")
cur.execute("SELECT value FROM settings WHERE name='message_voting_yes'") channel = bot.get_channel(int(cur.fetchone()[0]))
message = await channel.fetch_message(int(cur.fetchone()[0])) cur.execute("SELECT value FROM settings WHERE name='message_voting_yes'")
conn.commit() message = await channel.fetch_message(int(cur.fetchone()[0]))
if get_count_recruits(1) <= 25: if get_count_recruits(1) <= 25:
global Yes_select_inst25 global Yes_select_inst25
optiontuple = build_option_list() optiontuple = build_option_list()
@@ -249,10 +254,10 @@ async def edit_yes_message():
def insert_no_vote(recruit_id, voter_id, reason): def insert_no_vote(recruit_id, voter_id, reason):
cur.execute("INSERT INTO no_votes(discord_id_recruit, discord_id_voter, reason) VALUES (?, ?, ?)", (recruit_id, voter_id, reason)) with DBConnection() as cur:
conn.commit() cur.execute("INSERT INTO no_votes(discord_id_recruit, discord_id_voter, reason) VALUES (?, ?, ?)", (recruit_id, voter_id, reason))
cur.execute("SELECT nickname FROM recruits WHERE discord_id = ?", (recruit_id, )) cur.execute("SELECT nickname FROM recruits WHERE discord_id = ?", (recruit_id, ))
return cur.fetchone()[0] return cur.fetchone()[0]
class No_reason(discord.ui.Modal): class No_reason(discord.ui.Modal):
@@ -276,8 +281,9 @@ class No_reason(discord.ui.Modal):
await interaction.response.send_message(embeds=[embed], ephemeral=True) await interaction.response.send_message(embeds=[embed], ephemeral=True)
async def reason(discord_id, interaction): async def reason(discord_id, interaction):
cur.execute("SELECT nickname FROM recruits WHERE discord_id = ?", (discord_id,)) with DBConnection() as cur:
nickname = cur.fetchone()[0] cur.execute("SELECT nickname FROM recruits WHERE discord_id = ?", (discord_id,))
nickname = cur.fetchone()[0]
no_reason_instance = No_reason(title="Begründung für " + nickname) no_reason_instance = No_reason(title="Begründung für " + nickname)
no_reason_instance.recruit_id = discord_id no_reason_instance.recruit_id = discord_id
no_reason_instance.recruit_name = nickname no_reason_instance.recruit_name = nickname
@@ -289,8 +295,8 @@ class no_question(discord.ui.View):
vote_id = "" vote_id = ""
@discord.ui.button(label="Ja", style=discord.ButtonStyle.green,) @discord.ui.button(label="Ja", style=discord.ButtonStyle.green,)
async def yes(self, button, interaction): async def yes(self, button, interaction):
cur.execute("DELETE FROM no_votes WHERE id = ?", (self.vote_id, )) with DBConnection() as cur:
conn.commit() cur.execute("DELETE FROM no_votes WHERE id = ?", (self.vote_id, ))
await self.message.delete() await self.message.delete()
await reason(self.discord_id, interaction) await reason(self.discord_id, interaction)
@discord.ui.button(label="Nein", style=discord.ButtonStyle.grey) @discord.ui.button(label="Nein", style=discord.ButtonStyle.grey)
@@ -311,8 +317,8 @@ class no_clicked_but_yes_vote_question(discord.ui.View):
vote_id = "" vote_id = ""
@discord.ui.button(label="Ja", style=discord.ButtonStyle.green,) @discord.ui.button(label="Ja", style=discord.ButtonStyle.green,)
async def yes(self, button, interaction): async def yes(self, button, interaction):
cur.execute("DELETE FROM yes_votes WHERE id = ?", (self.vote_id, )) with DBConnection() as cur:
conn.commit() cur.execute("DELETE FROM yes_votes WHERE id = ?", (self.vote_id, ))
await self.message.delete() await self.message.delete()
await reason(self.discord_id, interaction) await reason(self.discord_id, interaction)
@discord.ui.button(label="Nein", style=discord.ButtonStyle.grey) @discord.ui.button(label="Nein", style=discord.ButtonStyle.grey)
@@ -326,14 +332,15 @@ class no_clicked_but_yes_vote_question(discord.ui.View):
await interaction.response.send_message(embed=embed, ephemeral=True) await interaction.response.send_message(embed=embed, ephemeral=True)
async def process_no_vote(interaction, select): async def process_no_vote(interaction, select):
cur.execute( with DBConnection() as cur:
"SELECT no_votes.reason, recruits.nickname, no_votes.id FROM recruits, no_votes WHERE recruits.discord_id = no_votes.discord_id_recruit AND no_votes.discord_id_voter = ? AND no_votes.discord_id_recruit = ?", cur.execute(
(interaction.user.id, select.values[0])) "SELECT no_votes.reason, recruits.nickname, no_votes.id FROM recruits, no_votes WHERE recruits.discord_id = no_votes.discord_id_recruit AND no_votes.discord_id_voter = ? AND no_votes.discord_id_recruit = ?",
no_vote = cur.fetchall() (interaction.user.id, select.values[0]))
cur.execute( no_vote = cur.fetchall()
"SELECT recruits.nickname, yes_votes.id FROM recruits, yes_votes WHERE yes_votes.discord_id_voter = ? AND yes_votes.discord_id_recruit = ? AND recruits.discord_id = yes_votes.discord_id_recruit", cur.execute(
(interaction.user.id, select.values[0])) "SELECT recruits.nickname, yes_votes.id FROM recruits, yes_votes WHERE yes_votes.discord_id_voter = ? AND yes_votes.discord_id_recruit = ? AND recruits.discord_id = yes_votes.discord_id_recruit",
yes_vote = cur.fetchall() (interaction.user.id, select.values[0]))
yes_vote = cur.fetchall()
if yes_vote: if yes_vote:
yes_question_inst = no_clicked_but_yes_vote_question() yes_question_inst = no_clicked_but_yes_vote_question()
yes_question_inst.discord_id = select.values[0] # Discord-ID des Rekruten yes_question_inst.discord_id = select.values[0] # Discord-ID des Rekruten
@@ -411,18 +418,20 @@ def create_no_embed():
async def send_no_message(channel): async def send_no_message(channel):
if get_count_recruits(1) <= 25: if get_count_recruits(1) <= 25:
message = await channel.send(embed=create_no_embed(), view=no_select_inst25) message = await channel.send(embed=create_no_embed(), view=no_select_inst25)
cur.execute("UPDATE settings SET VALUE = ? WHERE name = 'message_voting_no'", (message.id, )) with DBConnection() as cur:
cur.execute("UPDATE settings SET VALUE = ? WHERE name = 'message_voting_no'", (message.id, ))
else: else:
message = await channel.send(embed=create_no_embed(), view=no_select_inst50) message = await channel.send(embed=create_no_embed(), view=no_select_inst50)
cur.execute("UPDATE settings SET VALUE = ? WHERE name = 'message_voting_no'", (message.id, )) with DBConnection() as cur:
cur.execute("UPDATE settings SET VALUE = ? WHERE name = 'message_voting_no'", (message.id, ))
async def edit_no_message(): async def edit_no_message():
cur.execute("SELECT value FROM settings WHERE name='channel_voting'") with DBConnection() as cur:
channel = bot.get_channel(int(cur.fetchone()[0])) cur.execute("SELECT value FROM settings WHERE name='channel_voting'")
cur.execute("SELECT value FROM settings WHERE name='message_voting_no'") channel = bot.get_channel(int(cur.fetchone()[0]))
message = await channel.fetch_message(int(cur.fetchone()[0])) cur.execute("SELECT value FROM settings WHERE name='message_voting_no'")
conn.commit() message = await channel.fetch_message(int(cur.fetchone()[0]))
if get_count_recruits(1) <= 25: if get_count_recruits(1) <= 25:
global no_select_inst25 global no_select_inst25
no_select_inst25.children[0].options = build_option_list()[0] no_select_inst25.children[0].options = build_option_list()[0]
@@ -443,10 +452,11 @@ class delete_and_view_votes_message(discord.ui.View):
description="Hier sind deine Ja- und Nein-Stimmen aufgelistet:", description="Hier sind deine Ja- und Nein-Stimmen aufgelistet:",
color=discord.Colour.blurple(), color=discord.Colour.blurple(),
) )
cur.execute("SELECT recruits.nickname FROM recruits, yes_votes WHERE recruits.discord_id = yes_votes.discord_id_recruit AND recruits.recruit = 1 AND yes_votes.discord_id_voter = ?", (interaction.user.id, )) with DBConnection() as cur:
yes_votes = cur.fetchall() cur.execute("SELECT recruits.nickname FROM recruits, yes_votes WHERE recruits.discord_id = yes_votes.discord_id_recruit AND recruits.recruit = 1 AND yes_votes.discord_id_voter = ?", (interaction.user.id, ))
cur.execute("SELECT recruits.nickname, no_votes.reason FROM recruits, no_votes WHERE recruits.discord_id = no_votes.discord_id_recruit AND recruits.recruit = 1 AND no_votes.discord_id_voter = ?", (interaction.user.id, )) yes_votes = cur.fetchall()
no_votes = cur.fetchall() cur.execute("SELECT recruits.nickname, no_votes.reason FROM recruits, no_votes WHERE recruits.discord_id = no_votes.discord_id_recruit AND recruits.recruit = 1 AND no_votes.discord_id_voter = ?", (interaction.user.id, ))
no_votes = cur.fetchall()
if yes_votes: if yes_votes:
yes_message = "" yes_message = ""
for vote in yes_votes: for vote in yes_votes:
@@ -468,10 +478,11 @@ class delete_and_view_votes_message(discord.ui.View):
@discord.ui.button(label="Stimme auswählen und löschen", custom_id="delete-votes", style=discord.ButtonStyle.secondary) @discord.ui.button(label="Stimme auswählen und löschen", custom_id="delete-votes", style=discord.ButtonStyle.secondary)
async def delete_votes(self, button, interaction): async def delete_votes(self, button, interaction):
cur.execute("SELECT count(yes_votes.id) FROM recruits, yes_votes WHERE recruits.discord_id = yes_votes.discord_id_recruit AND recruits.recruit = 1 AND yes_votes.discord_id_voter = ?", (interaction.user.id,)) with DBConnection() as cur:
yes_votes = cur.fetchone()[0] cur.execute("SELECT count(yes_votes.id) FROM recruits, yes_votes WHERE recruits.discord_id = yes_votes.discord_id_recruit AND recruits.recruit = 1 AND yes_votes.discord_id_voter = ?", (interaction.user.id,))
cur.execute("SELECT count(no_votes.id) FROM recruits, no_votes WHERE recruits.discord_id = no_votes.discord_id_recruit AND recruits.recruit = 1 AND no_votes.discord_id_voter = ?", (interaction.user.id,)) yes_votes = cur.fetchone()[0]
no_votes = cur.fetchone()[0] cur.execute("SELECT count(no_votes.id) FROM recruits, no_votes WHERE recruits.discord_id = no_votes.discord_id_recruit AND recruits.recruit = 1 AND no_votes.discord_id_voter = ?", (interaction.user.id,))
no_votes = cur.fetchone()[0]
count = yes_votes + no_votes count = yes_votes + no_votes
if count == 0: if count == 0:
embed = discord.Embed( embed = discord.Embed(
@@ -502,63 +513,65 @@ class delete_and_view_votes_message(discord.ui.View):
await interaction.response.send_message(embed=embed, view=delete_recruit_vote_inst, ephemeral=True) await interaction.response.send_message(embed=embed, view=delete_recruit_vote_inst, ephemeral=True)
def getvotes(voterid, part = 1): def getvotes(voterid, part = 1):
cur.execute("SELECT count(*) FROM yes_votes WHERE discord_id_voter = ?", (voterid, )) with DBConnection() as cur:
yes_vote_count = cur.fetchone()[0] cur.execute("SELECT count(*) FROM yes_votes WHERE discord_id_voter = ?", (voterid, ))
cur.execute("SELECT count(*) FROM no_votes WHERE discord_id_voter = ?", (voterid,)) yes_vote_count = cur.fetchone()[0]
no_vote_count = cur.fetchone()[0] cur.execute("SELECT count(*) FROM no_votes WHERE discord_id_voter = ?", (voterid,))
count = yes_vote_count + no_vote_count no_vote_count = cur.fetchone()[0]
cur.execute( count = yes_vote_count + no_vote_count
"SELECT recruits.discord_id, recruits.nickname FROM recruits, yes_votes WHERE recruits.discord_id = yes_votes.discord_id_recruit AND yes_votes.discord_id_voter = ? AND recruit = 1",
(voterid, ))
yes_votes = cur.fetchall()
option = []
new_option = []
if count <= 25:
for vote in yes_votes:
option.append(discord.SelectOption(value=str(vote[0]), label="Ja: " + str(vote[1])))
cur.execute( cur.execute(
"SELECT recruits.discord_id, recruits.nickname FROM recruits, no_votes WHERE recruits.discord_id = no_votes.discord_id_recruit AND no_votes.discord_id_voter = ? AND recruit = 1", "SELECT recruits.discord_id, recruits.nickname FROM recruits, yes_votes WHERE recruits.discord_id = yes_votes.discord_id_recruit AND yes_votes.discord_id_voter = ? AND recruit = 1",
(voterid, )) (voterid, ))
no_votes = cur.fetchall() yes_votes = cur.fetchall()
for vote in no_votes: option = []
option.append(discord.SelectOption(value=str(vote[0]), label="Nein: " + str(vote[1]))) new_option = []
return option if count <= 25:
else: for vote in yes_votes:
for vote in yes_votes: option.append(discord.SelectOption(value=str(vote[0]), label="Ja: " + str(vote[1])))
option.append(discord.SelectOption(value=str(vote[0]), label="Ja: " + str(vote[1]))) cur.execute(
cur.execute( "SELECT recruits.discord_id, recruits.nickname FROM recruits, no_votes WHERE recruits.discord_id = no_votes.discord_id_recruit AND no_votes.discord_id_voter = ? AND recruit = 1",
"SELECT recruits.discord_id, recruits.nickname FROM recruits, no_votes WHERE recruits.discord_id = no_votes.discord_id_recruit AND no_votes.discord_id_voter = ? AND recruit = 1", (voterid, ))
(voterid, )) no_votes = cur.fetchall()
no_votes = cur.fetchall() for vote in no_votes:
for vote in no_votes: option.append(discord.SelectOption(value=str(vote[0]), label="Nein: " + str(vote[1])))
option.append(discord.SelectOption(value=str(vote[0]), label="Nein: " + str(vote[1]))) return option
if part == 1:
count = 0
for option_single in option:
if count >= 25:
break
else:
new_option.append(option_single)
count = count + 1
return new_option
else: else:
count = 0 for vote in yes_votes:
for option_single in option: option.append(discord.SelectOption(value=str(vote[0]), label="Ja: " + str(vote[1])))
if count < 25: cur.execute(
count = count + 1 "SELECT recruits.discord_id, recruits.nickname FROM recruits, no_votes WHERE recruits.discord_id = no_votes.discord_id_recruit AND no_votes.discord_id_voter = ? AND recruit = 1",
continue (voterid, ))
else: no_votes = cur.fetchall()
new_option.append(option_single) for vote in no_votes:
count = count + 1 option.append(discord.SelectOption(value=str(vote[0]), label="Nein: " + str(vote[1])))
return new_option if part == 1:
count = 0
for option_single in option:
if count >= 25:
break
else:
new_option.append(option_single)
count = count + 1
return new_option
else:
count = 0
for option_single in option:
if count < 25:
count = count + 1
continue
else:
new_option.append(option_single)
count = count + 1
return new_option
async def process_deletion_request(select, interaction): async def process_deletion_request(select, interaction):
confirm_deletion_of_vote_inst = confirm_deletion_of_vote() confirm_deletion_of_vote_inst = confirm_deletion_of_vote()
confirm_deletion_of_vote.votes = select.values confirm_deletion_of_vote.votes = select.values
description = "Du möchtest deine Stimme für folgenden Rekruten löschen:\n" description = "Du möchtest deine Stimme für folgenden Rekruten löschen:\n"
for choice in select.values: for choice in select.values:
cur.execute("SELECT nickname FROM recruits WHERE discord_id = ?", (choice,)) with DBConnection() as cur:
nickname = cur.fetchone()[0] cur.execute("SELECT nickname FROM recruits WHERE discord_id = ?", (choice,))
nickname = cur.fetchone()[0]
description = description + nickname + "\n" description = description + nickname + "\n"
embed = discord.Embed( embed = discord.Embed(
title="Stimme löschen", title="Stimme löschen",
@@ -610,10 +623,10 @@ class confirm_deletion_of_vote(discord.ui.View): # Create a class called MyView
votes = [] votes = []
@discord.ui.button(label="Stimme löschen", style=discord.ButtonStyle.danger) @discord.ui.button(label="Stimme löschen", style=discord.ButtonStyle.danger)
async def ja(self, button, interaction): async def ja(self, button, interaction):
for vote in self.votes: with DBConnection() as cur:
cur.execute("DELETE FROM yes_votes WHERE discord_id_voter = ? AND discord_id_recruit = ?", (interaction.user.id, vote)) for vote in self.votes:
cur.execute("DELETE FROM no_votes WHERE discord_id_voter = ? AND discord_id_recruit = ?", (interaction.user.id, vote)) cur.execute("DELETE FROM yes_votes WHERE discord_id_voter = ? AND discord_id_recruit = ?", (interaction.user.id, vote))
conn.commit() cur.execute("DELETE FROM no_votes WHERE discord_id_voter = ? AND discord_id_recruit = ?", (interaction.user.id, vote))
embed = discord.Embed( embed = discord.Embed(
title="Löschvorgang abgeschlossen", title="Löschvorgang abgeschlossen",
description="Deine Stimmen wurden gelöscht. \nSollte das ein Fehler sein, stimme einfach erneut ab.", description="Deine Stimmen wurden gelöscht. \nSollte das ein Fehler sein, stimme einfach erneut ab.",
@@ -644,44 +657,46 @@ async def send_delete_message(channel):
color=discord.Colour.dark_red(), color=discord.Colour.dark_red(),
) )
message = await channel.send(embed=embed, view=delete_and_view_votes_message()) message = await channel.send(embed=embed, view=delete_and_view_votes_message())
cur.execute("UPDATE settings SET VALUE = ? WHERE name = 'message_delete_vote'", (message.id, )) with DBConnection() as cur:
cur.execute("UPDATE settings SET VALUE = ? WHERE name = 'message_delete_vote'", (message.id, ))
async def process_detailed_report(select, interaction): async def process_detailed_report(select, interaction):
cur.execute("SELECT nickname FROM recruits WHERE discord_id = ?", (select.values[0],)) with DBConnection() as cur:
nick = cur.fetchone()[0] cur.execute("SELECT nickname FROM recruits WHERE discord_id = ?", (select.values[0],))
embed = discord.Embed( nick = cur.fetchone()[0]
title="Abstimmungen für " + nick, embed = discord.Embed(
color=discord.Colour.blurple(), # Pycord provides a class with default colors you can choose from title="Abstimmungen für " + nick,
) color=discord.Colour.blurple(), # Pycord provides a class with default colors you can choose from
cur.execute("SELECT discord_id_voter FROM yes_votes WHERE discord_id_recruit = ?", (select.values[0],)) )
yes_votes = cur.fetchall() cur.execute("SELECT discord_id_voter FROM yes_votes WHERE discord_id_recruit = ?", (select.values[0],))
yes_vote = "" yes_votes = cur.fetchall()
cur.execute("SELECT value FROM settings WHERE name = ?", ("guild",)) yes_vote = ""
guild_id = cur.fetchone()[0] cur.execute("SELECT value FROM settings WHERE name = ?", ("guild",))
guild = bot.get_guild(guild_id) guild_id = cur.fetchone()[0]
for vote in yes_votes: guild = bot.get_guild(guild_id)
yes_vote = yes_vote + guild.get_member(vote[0]).display_name + "\n" for vote in yes_votes:
cur.execute("SELECT count(*) FROM yes_votes WHERE discord_id_recruit = ?", (select.values[0],)) yes_vote = yes_vote + guild.get_member(vote[0]).display_name + "\n"
count_yes_votes = cur.fetchone()[0] cur.execute("SELECT count(*) FROM yes_votes WHERE discord_id_recruit = ?", (select.values[0],))
embed.add_field(name="Ja-Stimmen (" + str(count_yes_votes) + "):", value=yes_vote) count_yes_votes = cur.fetchone()[0]
cur.execute("SELECT discord_id_voter, reason FROM no_votes WHERE discord_id_recruit = ?", (select.values[0],)) embed.add_field(name="Ja-Stimmen (" + str(count_yes_votes) + "):", value=yes_vote)
no_votes = cur.fetchall() cur.execute("SELECT discord_id_voter, reason FROM no_votes WHERE discord_id_recruit = ?", (select.values[0],))
no_vote_text = "" no_votes = cur.fetchall()
for vote in no_votes: no_vote_text = ""
no_vote_text = no_vote_text + "**" + guild.get_member(vote[0]).display_name + "**: " + vote[1] + "\n" for vote in no_votes:
cur.execute("SELECT count(*) FROM no_votes WHERE discord_id_recruit = ?", (select.values[0],)) no_vote_text = no_vote_text + "**" + guild.get_member(vote[0]).display_name + "**: " + vote[1] + "\n"
count_no_votes = cur.fetchone()[0] cur.execute("SELECT count(*) FROM no_votes WHERE discord_id_recruit = ?", (select.values[0],))
count_no_votes = cur.fetchone()[0]
embed.add_field(name="Nein-Stimmen (" + str(count_no_votes) + "):", value=no_vote_text) embed.add_field(name="Nein-Stimmen (" + str(count_no_votes) + "):", value=no_vote_text)
await interaction.response.send_message(embed=embed, ephemeral=True) await interaction.response.send_message(embed=embed, ephemeral=True)
@settings.command(description="Sendet die Nachricht zum Abstimmen in den aktuellen Channel.") @settings.command(description="Sendet die Nachricht zum Abstimmen in den aktuellen Channel.")
@default_permissions(manage_roles=True) @default_permissions(manage_roles=True)
async def message_voting(ctx): async def message_voting(ctx):
cur.execute("UPDATE settings SET VALUE = ? WHERE name = 'channel_voting'", (ctx.channel_id, )) with DBConnection() as cur:
cur.execute("UPDATE settings SET VALUE = ? WHERE name = 'channel_voting'", (ctx.channel_id, ))
await send_yes_message(ctx.channel) await send_yes_message(ctx.channel)
await send_no_message(ctx.channel) await send_no_message(ctx.channel)
await send_delete_message(ctx.channel) await send_delete_message(ctx.channel)
conn.commit()
await ctx.respond(f"Done.", ephemeral=True) await ctx.respond(f"Done.", ephemeral=True)
class report_select_menu25(discord.ui.View): class report_select_menu25(discord.ui.View):
@@ -732,22 +747,23 @@ async def process_generate_report(select, interaction):
description = "```\n" description = "```\n"
guild = interaction.guild guild = interaction.guild
for recruit in select.values: for recruit in select.values:
cur.execute( with DBConnection() as cur:
"SELECT recruits.nickname FROM recruits WHERE recruits.discord_id = ?", cur.execute(
(recruit,)) "SELECT recruits.nickname FROM recruits WHERE recruits.discord_id = ?",
data = cur.fetchone() (recruit,))
cur.execute("SELECT count(*) FROM yes_votes WHERE discord_id_recruit = ?", (recruit, )) data = cur.fetchone()
yes_count = cur.fetchone()[0] cur.execute("SELECT count(*) FROM yes_votes WHERE discord_id_recruit = ?", (recruit, ))
cur.execute("SELECT count(*) FROM no_votes WHERE discord_id_recruit = ?", (recruit, )) yes_count = cur.fetchone()[0]
no_count = cur.fetchone()[0] cur.execute("SELECT count(*) FROM no_votes WHERE discord_id_recruit = ?", (recruit, ))
description = description + "**" + str(data[0]) + ":** " + str(yes_count) + " Ja | " + str(no_count) + " Nein -> \n" no_count = cur.fetchone()[0]
if no_count != 0: description = description + "**" + str(data[0]) + ":** " + str(yes_count) + " Ja | " + str(no_count) + " Nein -> \n"
cur.execute("SELECT discord_id_voter, reason FROM no_votes WHERE discord_id_recruit = ?", (recruit,)) if no_count != 0:
no_votes = cur.fetchall() cur.execute("SELECT discord_id_voter, reason FROM no_votes WHERE discord_id_recruit = ?", (recruit,))
for vote in no_votes: no_votes = cur.fetchall()
nick = guild.get_member(vote[0]).display_name for vote in no_votes:
description = description + "Begründung von " + nick + ": " + vote[1] + "\n" nick = guild.get_member(vote[0]).display_name
description = description + "\n" description = description + "Begründung von " + nick + ": " + vote[1] + "\n"
description = description + "\n"
description = description + "```" description = description + "```"
embed.description = description embed.description = description
await interaction.followup.send(embed=embed, ephemeral=True) await interaction.followup.send(embed=embed, ephemeral=True)
@@ -841,37 +857,38 @@ def create_report_embed():
title="Aktuelle Stimmen", title="Aktuelle Stimmen",
color=discord.Colour.blurple(), # Pycord provides a class with default colors you can choose from color=discord.Colour.blurple(), # Pycord provides a class with default colors you can choose from
) )
cur.execute("SELECT recruits.nickname, recruits.discord_id FROM recruits WHERE recruits.recruit = 1") with DBConnection() as cur:
recruits = cur.fetchall() cur.execute("SELECT recruits.nickname, recruits.discord_id FROM recruits WHERE recruits.recruit = 1")
description = "" recruits = cur.fetchall()
cur.execute("SELECT value FROM settings WHERE name = ?", ("guild", )) description = ""
guild_id = cur.fetchone()[0] cur.execute("SELECT value FROM settings WHERE name = ?", ("guild", ))
guild = bot.get_guild(guild_id) guild_id = cur.fetchone()[0]
for recruit in recruits: guild = bot.get_guild(guild_id)
cur.execute("SELECT count(*) FROM yes_votes WHERE discord_id_recruit = ?", (recruit[1], )) for recruit in recruits:
yes_count = cur.fetchone()[0] cur.execute("SELECT count(*) FROM yes_votes WHERE discord_id_recruit = ?", (recruit[1], ))
cur.execute("SELECT count(*) FROM no_votes WHERE discord_id_recruit = ?", (recruit[1], )) yes_count = cur.fetchone()[0]
no_count = cur.fetchone()[0] cur.execute("SELECT count(*) FROM no_votes WHERE discord_id_recruit = ?", (recruit[1], ))
if no_count != 0: no_count = cur.fetchone()[0]
cur.execute("SELECT reason, discord_id_voter FROM no_votes WHERE discord_id_recruit = ?", (recruit[1], )) if no_count != 0:
no_votes = cur.fetchall() cur.execute("SELECT reason, discord_id_voter FROM no_votes WHERE discord_id_recruit = ?", (recruit[1], ))
description = description + "**" + recruit[0] + ":** " + str(yes_count) + " Ja, " + str(no_count) + " Nein.\n" no_votes = cur.fetchall()
for no_vote in no_votes: description = description + "**" + recruit[0] + ":** " + str(yes_count) + " Ja, " + str(no_count) + " Nein.\n"
description = description + "Begründung von " + guild.get_member(no_vote[1]).display_name + ": " + no_vote[0] + "\n" for no_vote in no_votes:
description = description + "\n\n" description = description + "Begründung von " + guild.get_member(no_vote[1]).display_name + ": " + no_vote[0] + "\n"
else: description = description + "\n\n"
description = description + "**" + recruit[0] + ":** " + str(yes_count) + " Ja, " + str(no_count) + " Nein.\n" else:
description = description + "**" + recruit[0] + ":** " + str(yes_count) + " Ja, " + str(no_count) + " Nein.\n"
embed.description = description embed.description = description
return embed return embed
@settings.command(description="Sendet den Report in den aktuellen Kanal.") @settings.command(description="Sendet den Report in den aktuellen Kanal.")
@default_permissions(manage_roles=True) @default_permissions(manage_roles=True)
async def message_report(ctx): async def message_report(ctx):
cur.execute("UPDATE settings SET VALUE = ? WHERE name = 'channel_report'", (ctx.channel_id, ))
channel = ctx.channel channel = ctx.channel
message = await channel.send(embed=create_report_embed(), view=report_buttons()) with DBConnection() as cur:
cur.execute("UPDATE settings SET VALUE = ? WHERE name = 'message_report'", (message.id, )) cur.execute("UPDATE settings SET VALUE = ? WHERE name = 'channel_report'", (ctx.channel_id, ))
conn.commit() message = await channel.send(embed=create_report_embed(), view=report_buttons())
cur.execute("UPDATE settings SET VALUE = ? WHERE name = 'message_report'", (message.id, ))
await ctx.respond(f"Done.", ephemeral=True) await ctx.respond(f"Done.", ephemeral=True)
@settings.command(description="Setzt die ID der Rekruten-Rolle") @settings.command(description="Setzt die ID der Rekruten-Rolle")
@@ -880,15 +897,15 @@ async def role_recruit(
ctx, ctx,
rolearg: discord.Option(discord.SlashCommandOptionType.role) rolearg: discord.Option(discord.SlashCommandOptionType.role)
): ):
cur.execute("UPDATE settings SET VALUE = ? WHERE name = 'role_recruit'", (rolearg.id, )) with DBConnection() as cur:
conn.commit() cur.execute("UPDATE settings SET VALUE = ? WHERE name = 'role_recruit'", (rolearg.id, ))
await ctx.respond(f"Done.", ephemeral=True) await ctx.respond(f"Done.", ephemeral=True)
@settings.command(description="Setzt den Discord-Server") @settings.command(description="Setzt den Discord-Server")
@default_permissions(manage_roles=True) @default_permissions(manage_roles=True)
async def guild(ctx): async def guild(ctx):
cur.execute("UPDATE settings SET VALUE = ? WHERE name = 'guild'", (ctx.guild_id, )) with DBConnection() as cur:
conn.commit() cur.execute("UPDATE settings SET VALUE = ? WHERE name = 'guild'", (ctx.guild_id, ))
await ctx.respond(f"Done.", ephemeral=True) await ctx.respond(f"Done.", ephemeral=True)
def check_roles(member, recruit_id): def check_roles(member, recruit_id):
@@ -897,40 +914,42 @@ def check_roles(member, recruit_id):
return "Yes" return "Yes"
async def process_refresh(): async def process_refresh():
cur.execute("SELECT value FROM settings WHERE name='guild'") with DBConnection() as cur:
guild_id = cur.fetchone() cur.execute("SELECT value FROM settings WHERE name='guild'")
guild_id = guild_id[0] guild_id = cur.fetchone()
cur.execute("SELECT value FROM settings WHERE name='role_recruit'") guild_id = guild_id[0]
recruit_id = cur.fetchone()[0] cur.execute("SELECT value FROM settings WHERE name='role_recruit'")
recruit_id = cur.fetchone()[0]
guild = bot.get_guild(guild_id) guild = bot.get_guild(guild_id)
for role in guild.roles: for role in guild.roles:
if role.id == recruit_id: if role.id == recruit_id:
for member in role.members: for member in role.members:
recruit_update(member, 1, cur, conn) recruit_update(member, 1)
for member in guild.members: for member in guild.members:
result = check_roles(member, recruit_id) result = check_roles(member, recruit_id)
if result == "Yes": if result == "Yes":
pass pass
else: else:
cur.execute("UPDATE recruits SET recruit = ?, nickname = ? WHERE discord_id = ?", with DBConnection() as cur:
cur.execute("UPDATE recruits SET recruit = ?, nickname = ? WHERE discord_id = ?",
(0, member.display_name, member.id)) (0, member.display_name, member.id))
conn.commit() with DBConnection() as cur:
cur.execute("SELECT discord_id FROM recruits WHERE recruit = 1") cur.execute("SELECT discord_id FROM recruits WHERE recruit = 1")
recruits = cur.fetchall() recruits = cur.fetchall()
for recruit in recruits: for recruit in recruits:
member = guild.get_member(recruit[0]) member = guild.get_member(recruit[0])
if member is None: if member is None:
cur.execute("UPDATE recruits SET recruit = 0 WHERE discord_id = ?", (recruit[0],)) cur.execute("UPDATE recruits SET recruit = 0 WHERE discord_id = ?", (recruit[0],))
conn.commit()
await edit_yes_message() await edit_yes_message()
await edit_no_message() await edit_no_message()
await edit_report_message() await edit_report_message()
async def edit_report_message(): async def edit_report_message():
cur.execute("SELECT value FROM settings WHERE name='channel_report'") with DBConnection() as cur:
channel = bot.get_channel(int(cur.fetchone()[0])) cur.execute("SELECT value FROM settings WHERE name='channel_report'")
cur.execute("SELECT value FROM settings WHERE name='message_report'") channel = bot.get_channel(int(cur.fetchone()[0]))
message = await channel.fetch_message(int(cur.fetchone()[0])) cur.execute("SELECT value FROM settings WHERE name='message_report'")
message = await channel.fetch_message(int(cur.fetchone()[0]))
await message.edit(embed=create_report_embed(), view=report_buttons()) await message.edit(embed=create_report_embed(), view=report_buttons())
@settings.command(description="Aktualisiert die internen Daten.") @settings.command(description="Aktualisiert die internen Daten.")
@@ -943,13 +962,14 @@ async def refresh(ctx):
@bot.event @bot.event
async def on_member_update(previous, after): async def on_member_update(previous, after):
cur.execute("SELECT value FROM settings WHERE name='role_recruit'") with DBConnection() as cur:
recruit_id = cur.fetchone() cur.execute("SELECT value FROM settings WHERE name='role_recruit'")
recruit_id = cur.fetchone()
recruit_id = recruit_id[0] recruit_id = recruit_id[0]
found = False found = False
for role in after.roles: for role in after.roles:
if role.id == recruit_id: if role.id == recruit_id:
recruit_update(after, 1, cur, conn) recruit_update(after, 1)
found = True found = True
break break
if found: if found:
@@ -958,7 +978,7 @@ async def on_member_update(previous, after):
else: else:
for role in previous.roles: for role in previous.roles:
if role.id == recruit_id: if role.id == recruit_id:
recruit_update(after, 0, cur, conn) recruit_update(after, 0)
break break
await edit_yes_message() await edit_yes_message()
await edit_no_message() await edit_no_message()