Removing previous code, adding register and cancelRegister buttons with DM replies

This commit is contained in:
2025-11-29 19:51:53 +01:00
parent 670c0dc556
commit aa3c656537
4 changed files with 42 additions and 120 deletions
+11 -41
View File
@@ -1,4 +1,4 @@
from telegram import Update
from telegram import Bot, InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
import configparser
import json
@@ -6,45 +6,15 @@ import os
import datetime
import shutil
# /liste Handler (nur privat für Admins)
async def liste(update: Update, context: ContextTypes.DEFAULT_TYPE):
if update.effective_user.id not in config['admin']['ids']:
await update.message.reply_text("Epic fail, kein Zugriff für dich")
# Function to send a message with inline buttons
async def newEvent(update: Update, context: ContextTypes.DEFAULT_TYPE):
keyboard = [
[InlineKeyboardButton("Anmelden", callback_data='register')],
[InlineKeyboardButton("Abmelden", callback_data='cancelRegister')]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text("choose below", reply_markup=reply_markup)
return
if event_list:
antwort = "*Aktuelle Anmeldungen:*\n\n"
for i, name in enumerate(event_list, start=1):
antwort += f"{i}. {name}\n"
antwort += f"\n Insgesamt angemeldet: *{len(event_list)}*"
await update.message.reply_text(
antwort, parse_mode="Markdown"
)
else:
await update.message.reply_text("Chill, es is noch gar keiner angemeldet.")
# /reset Handler (nur privat für Admins, mit Archivierung)
async def reset(update: Update, context: ContextTypes.DEFAULT_TYPE):
if update.effective_user.id not in config['admin']['ids']:
await update.message.reply_text("Epic fail, Zugriff verweigert")
return
# Nur archivieren, wenn es überhaupt etwas gibt
if event_list:
timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
backup_file = f"event_list_{timestamp}.json"
try:
shutil.copy(list_file, backup_file)
await update.message.reply_text(
f"Ich hab die Liste mal gespeichert, falls du sie aus Versehen resettet hast, liegt jetz unter:\n`{backup_file}`",
parse_mode="Markdown"
)
except Exception as e:
await update.message.reply_text(f"Fehler beim Sichern: {e}")
else:
await update.message.reply_text("Liste ist leer, nichts zu sichern")
# Liste zurücksetzen (neue, leere Liste)
event_list.clear()
save_list()
await update.message.reply_text("WOOOSH! Und die Liste is wieder leer.")
+25 -52
View File
@@ -1,56 +1,29 @@
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
import configparser
import json
import os
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes, Updater, CallbackQueryHandler, CallbackContext
# Function to handle button clicks (callback queries)
async def button(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.callback_query
user = query.from_user
await query.answer() # Acknowledge the button press
if query.data == 'register':
try:
keyboard = [[InlineKeyboardButton("Abmelden", callback_data='cancelRegister')]]
reply_markup = InlineKeyboardMarkup(keyboard)
await context.bot.send_message(user.id, "Registered", reply_markup=reply_markup)
except Exception as e:
await context.bot.send_message(query.message.chat_id, f"@{user.username} Leider kam es zu einem Fehler: {str(e)}")
if query.data == 'cancelRegister':
try:
await context.bot.send_message(user.id, "Cancelled")
except Exception as e:
await context.bot.send_message(query.message.chat_id, f"@{user.username} Leider kam es zu einem Fehler: {str(e)}")
# /anmeldung Handler
async def anmeldung(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not context.args:
await update.message.reply_text("Bitte Namen angeben: /anmeldung Name")
return
name = " ".join(context.args)
if name in event_list:
await update.message.reply_text(f"{name}, du bist doch schon angemeldet.")
else:
event_list.append(name)
save_list()
await update.message.reply_text(f"{name} will unbedingt auch dabei sein!")
# /abmeldung Handler
async def abmeldung(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not context.args:
await update.message.reply_text("Bitte Namen angeben: /abmeldung Name")
return
name = " ".join(context.args)
if name in event_list:
event_list.remove(name)
save_list()
await update.message.reply_text(f"{name} kann nich mehr oder hat kein Bock auf uns.")
else:
await update.message.reply_text(f"{name}, du warst eh nich auf der Liste.")
# /hilfe Handler
async def hilfe(update: Update, context: ContextTypes.DEFAULT_TYPE):
text = (
"Dude, ich erklär dir mal wie das hier läuft:\n\n"
"In der Gruppe:\n"
"/anmeldung Name - zum Anmelden\n"
"/abmeldung Name - zum Abmelden\n"
"/status - check wie viele Fussel dabei sind\n\n"
)
await update.message.reply_text(text)
# /status Handler (für alle)
async def status(update: Update, context: ContextTypes.DEFAULT_TYPE):
count = len(event_list)
if count == 0:
text = "Is noch keiner eingecheckt..."
elif count == 1:
text = "Es ist aktuell *1 Fussel* dabei!"
else:
text = f"Es sind aktuell *{count} Fussel* dabei!"
await update.message.reply_text(text, parse_mode="Markdown")
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await hilfe(update, context)
+1 -3
View File
@@ -4,6 +4,4 @@ import configparser
import json
import os
async def error(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("nope")
return
+7 -26
View File
@@ -1,6 +1,6 @@
# [ IMPORTS ] #
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes, CallbackQueryHandler, Application
import configparser
import json
import os
@@ -28,35 +28,16 @@ def main():
app = ApplicationBuilder().token(config['telegram']['bot_token']).build()
# Admin commands
app.add_handler(CommandHandler("liste", liste))
app.add_handler(CommandHandler("reset", reset))
app.add_handler(CommandHandler("newEvent", newEvent))
# User commands
app.add_handler(CommandHandler("start", hilfe))
app.add_handler(CommandHandler("hilfe", hilfe))
app.add_handler(CommandHandler("anmeldung", anmeldung))
app.add_handler(CommandHandler("abmeldung", abmeldung))
app.add_handler(CommandHandler("status", status))
app.add_handler(CommandHandler("error", error))
# app.add_handler(CommandHandler("start", start))
# buttons
app.add_handler(CallbackQueryHandler(button))
print("Bot läuft...")
app.run_polling()
if __name__ == "__main__":
main()
######### NEEDS TO BE MOVED #####
# Lade die Liste, falls vorhanden
if os.path.exists(list_file):
with open(config['list']['default'], "r") as f:
event_list = json.load(f)
else:
event_list = []
# Hilfsfunktion zum Speichern
def save_list():
with open(config['list']['default'], "w") as f:
json.dump(event_list, f)