Files
bot.py
google_apps_script.gs
README.md
requirements.txt
Code
4 431
bot.py
import asyncio
import hmac
import json
import logging
import os
import re
import secrets
from datetime import datetime, timezone
from pathlib import Path
import discord
from aiohttp import web
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
logger = logging.getLogger("application_bot")
DATA_PATH = Path("data.json")
TOKEN = os.getenv("DISCORD_TOKEN")
WEBHOOK_SECRET = os.getenv("WEBHOOK_SECRET", "")
def load_store():
try:
data = json.loads(DATA_PATH.read_text(encoding="utf-8"))
if isinstance(data, dict):
data.setdefault("guilds", {})
data.setdefault("applications", {})
return data
except FileNotFoundError:
pass
except (json.JSONDecodeError, OSError):
logger.exception("Kunde inte läsa data.json; startar med tom konfiguration")
return {"guilds": {}, "applications": {}}
store = load_store()
def save_store():
temporary_path = DATA_PATH.with_suffix(".tmp")
temporary_path.write_text(json.dumps(store, ensure_ascii=False, indent=2), encoding="utf-8")
temporary_path.replace(DATA_PATH)
def guild_settings(guild_id):
settings = store["guilds"].setdefault(
str(guild_id),
{"channel_id": None, "staff_role_id": None, "title": "Ny ansökan", "color": "38BDF8", "footer": "Ansökningsgranskning"},
)
settings.setdefault("forms", {})
return settings
def staff_can_review(interaction, settings):
member = interaction.user
if not isinstance(member, discord.Member):
return False
if member.guild_permissions.manage_guild:
return True
role_id = settings.get("staff_role_id")
if role_id:
return any(role.id == int(role_id) for role in member.roles)
return member.guild_permissions.manage_messages
def make_embed_color(hex_color):
return discord.Color(int(hex_color, 16))
class ApplicationReviewView(discord.ui.View):
def __init__(self, application_id):
super().__init__(timeout=None)
self.application_id = application_id
for item in self.children:
if item.label == "Godkänn":
item.custom_id = f"application:approve:{application_id}"
elif item.label == "Neka":
item.custom_id = f"application:reject:{application_id}"
@discord.ui.button(label="Godkänn", style=discord.ButtonStyle.success)
async def approve_button(self, interaction: discord.Interaction, button: discord.ui.Button):
await self.decide(interaction, approved=True)
@discord.ui.button(label="Neka", style=discord.ButtonStyle.danger)
async def reject_button(self, interaction: discord.Interaction, button: discord.ui.Button):
await self.decide(interaction, approved=False)
async def decide(self, interaction, approved):
application = store["applications"].get(self.application_id)
if application is None:
await interaction.response.send_message("Ansökan hittades inte.", ephemeral=True)
return
if interaction.guild_id != int(application["guild_id"]):
await interaction.response.send_message("Du kan inte granska den här ansökan här.", ephemeral=True)
return
settings = guild_settings(interaction.guild_id)
if not staff_can_review(interaction, settings):
await interaction.response.send_message("Du har inte behörighet att granska ansökningar.", ephemeral=True)
return
if application["status"] != "pending":
await interaction.response.send_message("Ansökan har redan granskats.", ephemeral=True)
return
status = "Godkänd" if approved else "Nekad"
application["status"] = "approved" if approved else "rejected"
application["reviewed_by"] = interaction.user.id
application["reviewed_at"] = datetime.now(timezone.utc).isoformat()
save_store()
self.disable_all_items()
embeds = list(interaction.message.embeds)
if embeds:
embed = embeds[0]
embed.color = discord.Color.green() if approved else discord.Color.red()
for index, field in enumerate(embed.fields):
if field.name == "Status":
embed.set_field_at(index, name="Status", value=f"{status} av {interaction.user.mention}", inline=False)
break
await interaction.response.edit_message(embeds=embeds, view=self)
class AppearanceModal(discord.ui.Modal, title="Ändra utseende"):
def __init__(self, guild_id, form_name, settings):
super().__init__()
self.guild_id = guild_id
self.form_name = form_name
self.title_input = discord.ui.TextInput(
label="Titel på ansöknings-embed", default=settings["title"], max_length=200
)
self.color_input = discord.ui.TextInput(
label="Färg i hex (t.ex. 38BDF8)", default=settings["color"], max_length=7
)
self.footer_input = discord.ui.TextInput(
label="Fottext", default=settings["footer"], max_length=200
)
self.add_item(self.title_input)
self.add_item(self.color_input)
self.add_item(self.footer_input)
async def on_submit(self, interaction):
color = self.color_input.value.strip().removeprefix("#")
if not re.fullmatch(r"[0-9a-fA-F]{6}", color):
await interaction.response.send_message("Färgen måste vara sex hexadecimala tecken, till exempel `38BDF8`.", ephemeral=True)
return
settings = guild_settings(self.guild_id)
appearance = settings["forms"].setdefault(self.form_name, {
"title": settings["title"],
"color": settings["color"],
"footer": settings["footer"],
})
appearance["title"] = self.title_input.value.strip() or "Ny ansökan"
appearance["color"] = color.upper()
appearance["footer"] = self.footer_input.value.strip()
save_store()
await interaction.response.send_message(f"Utseendet för **{self.form_name}** har sparats.", ephemeral=True)
class AppearanceFormSelect(discord.ui.Select):
def __init__(self, guild_id, form_names):
self.guild_id = guild_id
options = [discord.SelectOption(label=name[:100], value=name) for name in form_names[:25]]
super().__init__(placeholder="Välj vilket formulär du vill ändra", min_values=1, max_values=1, options=options)
async def callback(self, interaction):
form_name = self.values[0]
settings = guild_settings(self.guild_id)
appearance = settings["forms"].get(form_name, settings)
await interaction.response.send_modal(AppearanceModal(self.guild_id, form_name, appearance))
class AppearanceFormView(discord.ui.View):
def __init__(self, guild_id, form_names):
super().__init__(timeout=180)
self.add_item(AppearanceFormSelect(guild_id, form_names))
class ApplicationBot(commands.Bot):
def __init__(self):
super().__init__(command_prefix="!", intents=discord.Intents.default())
self.http_runner = None
async def setup_hook(self):
for application_id, application in store["applications"].items():
if application.get("status") == "pending" and application.get("message_id"):
self.add_view(ApplicationReviewView(application_id), message_id=int(application["message_id"]))
await self.tree.sync()
web_app = web.Application(client_max_size=2 * 1024 * 1024)
web_app.router.add_post("/google-form", receive_application)
self.http_runner = web.AppRunner(web_app)
await self.http_runner.setup()
site = web.TCPSite(self.http_runner, "0.0.0.0", int(os.getenv("SERVER_PORT", "8080")))
await site.start()
logger.info("Formulär-endpointen är startad")
async def close(self):