Files
ngb-counter/main.py

66 lines
2.3 KiB
Python

import discord
import os # default module
from dotenv import load_dotenv
import json
load_dotenv() # load all the variables from the env file
bot = discord.Bot()
with open('storage.json') as user_file:
storage = json.loads(user_file.read())
@bot.event
async def on_ready():
bot.add_view(CounterView())
print(f"{bot.user} is ready and online!")
def create_embed(counter):
embed = discord.Embed(
title="Schimpfwortkasse",
color=discord.Colour.blurple(),
)
embed.add_field(name="Aktueller Stand:", value=str(counter) + ".00 Euro")
return embed
async def getmsg(ctx, msgID: int): # yes, you can do msg: discord.Message
msg = await ctx.fetch_message(msgID) # you now have the message object from the id
class CounterView(discord.ui.View): # Create a class called MyView that subclasses 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):
storage["counter"] = storage["counter"] + 1
with open('storage.json', 'w') as f:
json.dump(storage, f)
channel = bot.get_channel(int(storage["channel_id"]))
message = channel.fetch_message(int(storage["message_id"]))
await message.edit(embed=create_embed(storage["counter"]), view=CounterView())
await interaction.response.send_message("Fertig", ephemeral=True)
@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
storage["channel_id"] = channel.id
message = await channel.send(embed=create_embed(storage["counter"]), view=CounterView())
storage["message_id"] = message.id
with open('storage.json', 'w') as f:
json.dump(storage, f)
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):
storage["counter"] = 0
with open('storage.json', 'w') as f:
json.dump(storage, f)
await ctx.respond(content="Done", ephemeral=True)
bot.run(os.getenv('TOKEN')) # run the bot with the token