Files
fembot/commands/create_meet.py
T
2026-05-24 23:00:37 +02:00

262 lines
9.1 KiB
Python

import os
import re
import discord
import traceback
import time
from geopy.geocoders import Nominatim
from geopy.exc import GeocoderTimedOut
from discord.ext import commands, tasks
from discord import app_commands
from datetime import datetime
from dotenv import load_dotenv
load_dotenv()
class ConfirmInteractiveMenu(discord.ui.View):
def __init__(self):
super().__init__(timeout=60.0)
@discord.ui.button(label="Register Meetup!", style=discord.ButtonStyle.success)
async def primary_button_callback(self, interaction: discord.Interaction, button: discord.ui.Button):
for child in self.children:
child.disabled = True
await interaction.response.edit_message(view=self)
await interaction.followup.send(f"## Meetup Registered Successfully!", ephemeral=True)
def validate_postal_code(country_code: str, postal_code: str) -> bool:
country_code = country_code.upper().strip()
postal_code = postal_code.strip()
patterns = {
"DE": r"^\d{4,5}$", # Pure digits (4-5)
"AT": r"^\d{4,5}$", # Pure digits (4-5)
"CH": r"^\d{4,5}$", # Pure digits (4-5)
"US": r"^\d{5}(-\d{4})?$", # 5-digit or ZIP+4
"UK": r"^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$" # Case-insensitive alphanumeric
}
if country_code not in patterns:
return False
if country_code == "UK":
postal_code = postal_code.upper()
return bool(re.match(patterns[country_code], postal_code))
def get_state_from_postal_code(country_code: str, postal_code: str) -> str:
geolocator = Nominatim(user_agent="discord_bot_local_femboy_meetup")
query = {
"postalcode": postal_code,
"country": country_code
}
result = {
"state": "Error: State not found :c",
"settlement": "Error: settlement not found :c"
}
try:
location = geolocator.geocode(query, addressdetails=True, timeout=10)
if location and "address" in location.raw:
address = location.raw["address"]
state_keys = ["state", "province", "state_district", "region"]
for key in state_keys:
if key in address:
result["state"] = address[key]
break
settlement_keys = ["village", "hamlet", "suburb", "town", "city", "municipality"]
for key in settlement_keys:
if key in address:
result["settlement"] = address[key]
break
return result
except GeocoderTimedOut:
return "Error: Request timed out :c"
class CreateMeetupForm(discord.ui.Modal, title="Create a local meetup"):
def __init__(self, chosen_country: str):
super().__init__()
self.chosen_country = chosen_country
form_postal_code = discord.ui.TextInput(
label="Enter the local postal code",
style=discord.TextStyle.short,
placeholder="",
required=True,
max_length=10
)
form_date = discord.ui.TextInput(
label="Enter the date (Format: YYYY-MM-DD)",
style=discord.TextStyle.short,
placeholder="YYYY-MM-DD",
required=True,
max_length=10
)
form_start_time = discord.ui.TextInput(
label="Enter the start time (Format: HH:MM [UTC]",
style=discord.TextStyle.short,
placeholder="HH:MM",
required=True,
max_length=5
)
form_end_time = discord.ui.TextInput(
label="Enter the end time (Format: HH:MM [UTC])",
style=discord.TextStyle.short,
placeholder="HH:MM",
required=True,
max_length=5
)
form_location = discord.ui.TextInput(
label="Enter the location or specific",
style=discord.TextStyle.paragraph,
placeholder="",
required=True,
max_length=200
)
async def on_submit(self, interaction: discord.Interaction):
try:
try:
valid_date = datetime.strptime(self.form_date.value, "%Y-%m-%d").date()
formatted_date = valid_date.strftime("%B %d, %Y")
except ValueError:
await interaction.response.send_message(
"❌ **Validation Error:** Invalid date format. Please use **YYYY-MM-DD**.",
ephemeral=True
)
return
if datetime.now().date() > valid_date:
await interaction.response.send_message(
"❌ **Validation Error:** The date cannot be in the past!",
ephemeral=True
)
return
try:
valid_start = datetime.strptime(self.form_start_time.value, "%H:%M").time()
valid_end = datetime.strptime(self.form_end_time.value, "%H:%M").time()
formatted_start = valid_start.strftime("%H:%M")
formatted_end = valid_end.strftime("%H:%M")
except ValueError:
await interaction.response.send_message(
"❌ **Validation Error:** Invalid time format. Please use **HH:MM** in 24-hour format.",
ephemeral=True
)
return
if valid_start >= valid_end:
await interaction.response.send_message(
"❌ **Validation Error:** The start time must be earlier than the end time!",
ephemeral=True
)
return
if not validate_postal_code(self.chosen_country, self.form_postal_code.value):
await interaction.response.send_message(
"❌ **Validation Error:** Please use a valid postal code for the local country",
ephemeral=True
)
return
result = get_state_from_postal_code(self.chosen_country, self.form_postal_code.value)
self.state = result["state"]
self.settlement = result["settlement"]
await interaction.response.send_message(
content=(
"## Event Register Preview\n"
f"**Country:** {self.chosen_country}\n"
f"**State:** {self.state}\n"
f"**City:** {self.form_postal_code.value} {self.settlement}\n"
"> \n"
f"**Date:** {valid_date}\n"
f"**Time:** {formatted_start} - {formatted_end}\n"
f"**Organizer:** {interaction.user.mention}\n"
f"**Location:** {self.form_location.value}\n"
"-# bla bla bla bla"
),
ephemeral=True, view=ConfirmInteractiveMenu()
)
except Exception as e:
print("CRITICAL ERROR IN SUBMIT:")
traceback.print_exc()
await interaction.response.send_message("An internal error occurred :c", ephemeral=True)
class CountrySelect(discord.ui.Select):
def __init__(self):
options = [
discord.SelectOption(label="Deutschland", value="de", emoji="🇩🇪"),
discord.SelectOption(label="Österreich", value="at", emoji="🇦🇹"),
discord.SelectOption(label="Switzerland", value="ch", emoji="🇨🇭"),
discord.SelectOption(label="United Kingdom", value="uk", emoji="🇬🇧"),
discord.SelectOption(label="United States", value="us", emoji="🇺🇸"),
]
super().__init__(placeholder="Select your country...", min_values=1, max_values=1, options=options)
async def callback(self, interaction: discord.Interaction):
await interaction.response.send_modal(CreateMeetupForm(chosen_country=self.values[0]))
await interaction.delete_original_response()
class CountryDropdownView(discord.ui.View):
def __init__(self):
super().__init__(timeout=60)
self.add_item(CountrySelect())
class MainInteractiveMenu(discord.ui.View):
def __init__(self):
super().__init__()
@discord.ui.button(label="Register a Meetup", style=discord.ButtonStyle.success)
async def primary_button_callback(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message(
content="Please select your country below to continue:",
view=CountryDropdownView(),
ephemeral=True
)
class CreateMeetup(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
async def cog_load(self):
self.startup.start()
def cog_unload(self):
self.startup.cancel()
@tasks.loop(count=1)
async def startup(self):
await self.bot.wait_until_ready()
channel = await self.bot.fetch_channel(os.getenv('CREATE_MEETUP_CHANNEL_ID'))
await channel.purge(limit=None, bulk=True)
await channel.send("""
# Create a local meetup
bla bla bla
bla bla bla
-# bla bla bla
""", view=MainInteractiveMenu())
async def setup(bot: commands.Bot):
await bot.add_cog(CreateMeetup(bot))