import discord import os # default module from dotenv import load_dotenv import json import mariadb if os.path.exists(".env"): load_dotenv() intents = discord.Intents.default() intents.members = True bot = discord.Bot(intents = intents) configfile = "config.json" if os.path.exists(configfile): with open('config.json') as user_file: config = json.loads(user_file.read()) else: config = {"db_user": os.environ["db_user"], "db_password": os.environ["db_password"], "db_host": os.environ["db_host"], "db_name": os.environ["db_name"]} 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 __enter__(self): self.conn = mariadb.connect(user=self.user, password=self.password, host=self.host, database=self.database) self.cursor = self.conn.cursor() return self.cursor def __exit__(self, exc_type, exc_val, exc_tb): self.conn.commit() self.cursor.close() self.conn.close() @bot.event async def on_ready(): bot.add_view(CounterView()) print(f"{bot.user} is ready and online!") def create_embed(guild): embed = discord.Embed( title="Schimpfwortkasse", color=discord.Colour.magenta(), ) with DBConnection() as cur: cur.execute("SELECT user_id, count FROM member") members = cur.fetchall() cur.execute("SELECT sum(count) as Totalcount from member") count_member = cur.fetchone()[0] if count_member is None: count_member = 0 cur.execute("SELECT value FROM settings WHERE name='pre-count'") precount = cur.fetchone()[0] if precount is None: precount = 0 total = precount + count_member embed.add_field(name="Aktueller Stand:", value=str(total) + ".00 Euro") description = "" if precount != 0: description = description + "**Vorheriger Stand:** " + str(precount) + " Euro\n" for member in members: if hasattr(guild.get_member(member[0]), "display_name"): name = guild.get_member(member[0]).display_name else: name = guild.get_member(member[0]).global_name description = description + "**" + name + "**: " + str(member[1]) + " Euro \n" embed.add_field(name="Bestenliste:", value=description) return embed class CounterView(discord.ui.View): def __init__(self): super().__init__(timeout=None) # timeout of the view must be set to None @discord.ui.button(label="+1", custom_id="count_plus_one", style=discord.ButtonStyle.primary) async def button_callback(self, button, interaction): with DBConnection() as cur: cur.execute("INSERT INTO member (user_id, count) VALUES (?, 1) ON DUPLICATE KEY UPDATE count=count + 1", (interaction.user.id, )) await updatemessage(interaction.guild) await interaction.response.send_message("Ab ins Sparschwein damit!", ephemeral=True) async def updatemessage(guild): with DBConnection() as cur: cur.execute("SELECT value from settings WHERE name='message_id'") message_id = cur.fetchone()[0] cur.execute("SELECT value from settings WHERE name='channel_id'") channelid = cur.fetchone()[0] channel = await guild.fetch_channel(int(channelid)) message = await channel.fetch_message(int(message_id)) await message.edit(embed=create_embed(guild), view=CounterView()) @bot.slash_command(name="set_channel", description="Setze den Channel, in dem der Zähler erstellt wird.") async def set_channel(ctx): channel = ctx.channel message = await channel.send(embed=create_embed(ctx.guild), view=CounterView()) with DBConnection() as cur: cur.execute("UPDATE settings SET VALUE = ? WHERE name = 'channel_id'", (ctx.channel_id,)) cur.execute("UPDATE settings SET VALUE = ? WHERE name = 'message_id'", (message.id,)) await ctx.respond(content="Done", ephemeral=True) @bot.slash_command(name="update", description="Aktualisiere die Nachricht") async def set_channel(ctx): await updatemessage(ctx.guild) await ctx.respond(content="Done", ephemeral=True) @bot.slash_command(name="reset_counter", description="Setze den Zähler auf Null.") async def reset_counter(ctx): await ctx.respond(content="Dies kann nur durch Lord gemacht werden. Er muss die Daten in der Datenbank löschen. Sprech ihn bitte an.", ephemeral=True) bot.run(os.getenv('TOKEN')) # run the bot with the token