feat: /increment shows inline keyboard when no argument; add callback button increment

This commit is contained in:
Andre Beging
2025-09-30 10:43:07 +02:00
parent 68a75b8171
commit fba72a679d

75
bot.py
View File

@@ -7,7 +7,13 @@ import sys
from pathlib import Path
from typing import Dict, Any, Optional
from telegram import Update, InlineQueryResultArticle, InputTextMessageContent
from telegram import (
Update,
InlineQueryResultArticle,
InputTextMessageContent,
InlineKeyboardButton,
InlineKeyboardMarkup,
)
from telegram.constants import ParseMode
from telegram.ext import (
ApplicationBuilder,
@@ -17,6 +23,7 @@ from telegram.ext import (
filters,
ChatMemberHandler,
InlineQueryHandler,
CallbackQueryHandler,
)
DATA_DIR = Path(os.environ.get("DATA_DIR", "/data"))
@@ -145,11 +152,27 @@ async def increment_counter(update: Update, context: ContextTypes.DEFAULT_TYPE):
chat_id = update.effective_chat.id
if not context.bot_data['access'](chat_id):
return
counters = context.bot_data['counters']
# If no argument: show inline keyboard with counters
if not context.args:
await update.message.reply_text("Bitte einen Counternamen angeben: /increment <name>")
if not counters:
await update.message.reply_text("Keine Counter vorhanden. Lege einen an mit /add <name>.")
return
buttons = []
row: list = []
for idx, name in enumerate(sorted(counters.keys())):
row.append(InlineKeyboardButton(text=f"{name} ({counters[name]})", callback_data=f"inc:{name}"))
if len(row) == 3:
buttons.append(row)
row = []
if row:
buttons.append(row)
markup = InlineKeyboardMarkup(buttons)
await update.message.reply_text(
"Wähle einen Counter zum Inkrementieren:", reply_markup=markup
)
return
key = norm_key(context.args[0])
counters = context.bot_data['counters']
if key not in counters:
esc = html_escape(key)
await update.message.reply_text(f"Counter <b>{esc}</b> existiert nicht. Lege ihn mit /add {esc} an.", parse_mode=ParseMode.HTML)
@@ -159,6 +182,49 @@ async def increment_counter(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text(f"Counter <b>{html_escape(key)}</b> steht jetzt auf <b>{counters[key]}</b>.", parse_mode=ParseMode.HTML)
async def handle_increment_button(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle callback button presses for incrementing counters."""
query = update.callback_query
if not query:
return
await query.answer()
data = query.data or ""
if not data.startswith("inc:"):
return
name = data.split(":", 1)[1]
counters = context.bot_data['counters']
chat_id = query.message.chat_id if query.message else None
if chat_id is not None and not context.bot_data['access'](chat_id):
return
key = norm_key(name)
if key not in counters:
await query.edit_message_text(f"Counter <b>{html_escape(key)}</b> existiert nicht mehr.", parse_mode=ParseMode.HTML)
return
counters[key] += 1
save_counters(counters)
# Rebuild keyboard to reflect new values
buttons = []
row: list = []
for idx, cname in enumerate(sorted(counters.keys())):
row.append(InlineKeyboardButton(text=f"{cname} ({counters[cname]})", callback_data=f"inc:{cname}"))
if len(row) == 3:
buttons.append(row)
row = []
if row:
buttons.append(row)
markup = InlineKeyboardMarkup(buttons)
try:
await query.edit_message_text(
f"Counter <b>{html_escape(key)}</b> steht jetzt auf <b>{counters[key]}</b>. Wähle weiteren Counter:",
parse_mode=ParseMode.HTML,
reply_markup=markup,
)
except Exception:
# Fallback: send separate message if edit fails
if chat_id is not None:
await context.bot.send_message(chat_id, f"Counter <b>{html_escape(key)}</b> steht jetzt auf <b>{counters[key]}</b>.", parse_mode=ParseMode.HTML)
async def decrement_counter(update: Update, context: ContextTypes.DEFAULT_TYPE):
chat_id = update.effective_chat.id
if not context.bot_data['access'](chat_id):
@@ -388,6 +454,7 @@ def main():
application.add_handler(CommandHandler("add", add_counter))
application.add_handler(CommandHandler("remove", remove_counter))
application.add_handler(CommandHandler("increment", increment_counter))
application.add_handler(CallbackQueryHandler(handle_increment_button, pattern=r"^inc:"))
application.add_handler(CommandHandler("decrement", decrement_counter))
application.add_handler(CommandHandler("list", list_counters))
# Group / membership events
@@ -405,7 +472,7 @@ def main():
application.run_polling(
stop_signals=(signal.SIGINT, signal.SIGTERM),
allowed_updates=["message", "chat_member", "my_chat_member", "inline_query"],
allowed_updates=["message", "chat_member", "my_chat_member", "inline_query", "callback_query"],
)