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
+10 -40
View File
@@ -1,4 +1,4 @@
from telegram import Update from telegram import Bot, InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
import configparser import configparser
import json import json
@@ -6,45 +6,15 @@ import os
import datetime import datetime
import shutil import shutil
# /liste Handler (nur privat für Admins) # Function to send a message with inline buttons
async def liste(update: Update, context: ContextTypes.DEFAULT_TYPE): async def newEvent(update: Update, context: ContextTypes.DEFAULT_TYPE):
if update.effective_user.id not in config['admin']['ids']: keyboard = [
await update.message.reply_text("Epic fail, kein Zugriff für dich") [InlineKeyboardButton("Anmelden", callback_data='register')],
return [InlineKeyboardButton("Abmelden", callback_data='cancelRegister')]
]
if event_list: reply_markup = InlineKeyboardMarkup(keyboard)
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) await update.message.reply_text("choose below", reply_markup=reply_markup)
async def reset(update: Update, context: ContextTypes.DEFAULT_TYPE): return
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.")
+24 -51
View File
@@ -1,56 +1,29 @@
from telegram import Update from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes, Updater, CallbackQueryHandler, CallbackContext
import configparser
import json
import os
# /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 # Function to handle button clicks (callback queries)
async def abmeldung(update: Update, context: ContextTypes.DEFAULT_TYPE): async def button(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not context.args: query = update.callback_query
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 user = query.from_user
async def hilfe(update: Update, context: ContextTypes.DEFAULT_TYPE):
text = ( await query.answer() # Acknowledge the button press
"Dude, ich erklär dir mal wie das hier läuft:\n\n"
"In der Gruppe:\n" if query.data == 'register':
"/anmeldung Name - zum Anmelden\n" try:
"/abmeldung Name - zum Abmelden\n" keyboard = [[InlineKeyboardButton("Abmelden", callback_data='cancelRegister')]]
"/status - check wie viele Fussel dabei sind\n\n" reply_markup = InlineKeyboardMarkup(keyboard)
) await context.bot.send_message(user.id, "Registered", reply_markup=reply_markup)
await update.message.reply_text(text) 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)}")
return
# /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 json
import os 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 ] # # [ IMPORTS ] #
from telegram import Update from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes, CallbackQueryHandler, Application
import configparser import configparser
import json import json
import os import os
@@ -28,35 +28,16 @@ def main():
app = ApplicationBuilder().token(config['telegram']['bot_token']).build() app = ApplicationBuilder().token(config['telegram']['bot_token']).build()
# Admin commands # Admin commands
app.add_handler(CommandHandler("liste", liste)) app.add_handler(CommandHandler("newEvent", newEvent))
app.add_handler(CommandHandler("reset", reset))
# User commands # User commands
app.add_handler(CommandHandler("start", hilfe)) # app.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("hilfe", hilfe))
app.add_handler(CommandHandler("anmeldung", anmeldung)) # buttons
app.add_handler(CommandHandler("abmeldung", abmeldung)) app.add_handler(CallbackQueryHandler(button))
app.add_handler(CommandHandler("status", status))
app.add_handler(CommandHandler("error", error))
print("Bot läuft...") print("Bot läuft...")
app.run_polling() app.run_polling()
if __name__ == "__main__": if __name__ == "__main__":
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)