Bugfix + wip nested menu

main
Alex 5 months ago
parent 510c2039a8
commit a7ab11e3bb

@ -1,12 +1,22 @@
import os
import logging
import telegram
from telegram import Update
from telegram.ext import ApplicationBuilder, ContextTypes, CallbackContext, CommandHandler, MessageHandler, filters
import telegram.error
import asyncio
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, CallbackQueryHandler, MessageHandler, filters, ContextTypes
import os
logging.basicConfig(filename='osiris_telegram.log', level=logging.DEBUG, format='%(asctime)s %(message)s')
# Telegram bot token
TELEGRAM_BOT_TOKEN = '6984289827:AAHNUM4F_U6233oa75nX5jXyQY6vC0NlZvw'
# File to store subscriber chat IDs
SUBSCRIBERS_FILE = 'telegramm_subscribers.txt'
PASSWORD = '29102021'
# Dictionary to store timers
timers = {}
####
# Nested Menu Bäume
####
@ -44,6 +54,7 @@ minecraft_menu = [
{"text": "The 1.12.2 Pack (SanderPack)", "callback_data": "minecraft_sanderpack"},
{"text": "GT New Horizons 2.6.0 (SanderHorizons)", "callback_data": "minecraft_sanderhorizon"},
{"text": "RLCraft 2.9.3 (SanderHardcore)", "callback_data": "minecraft_sanderhardcore"},
{"text": "HarvestMoon (SanderMoon)", "callback_data": "minecraft_sandermoon"},
{"text": "<- Zurück", "callback_data": "minecraft_back"}
# Add neue Minecraft Commands here
]
@ -52,6 +63,7 @@ minecraft_menu = [
mc_vanilla_menu = [
[
{"text": "Start", "callback_data": "mc_vanilla_start"},
{"text": "Stop", "callback_data": "mc_vanilla_stop"},
{"text": "<- Zurück", "callback_data": "mc_vanilla_back"}
]
]
@ -59,6 +71,7 @@ mc_vanilla_menu = [
mc_sanderpack_menu = [
[
{"text": "Start", "callback_data": "mc_sanderpack_start"},
{"text": "Stop", "callback_data": "mc_sanderpack_stop"},
{"text": "<- Zurück", "callback_data": "mc_sanderpack_back"}
]
]
@ -66,20 +79,31 @@ mc_sanderpack_menu = [
mc_sanderhorizon_menu = [
[
{"text": "Start", "callback_data": "mc_sanderhorizon_start"},
{"text": "Stop", "callback_data": "mc_sanderhorizon_stop"},
{"text": "<- Zurück", "callback_data": "mc_sanderhorizon_back"}
]
]
mc_sanderhardcore_menu = [
[
{"text": "Start", "callback_data": "mc_sanderhardcore_start"},
{"text": "Start", "callback_data": "mc_sanderhardcore_start"},
{"text": "Stop", "callback_data": "mc_sanderhardcore_stop"},
{"text": "<- Zurück", "callback_data": "mc_sanderhardcore_back"}
]
]
mc_sandermoon_menu = [
[
{"text": "Start", "callback_data": "mc_sandermoon_start"},
{"text": "Stop", "callback_data": "mc_sandermoon_stop"},
{"text": "<- Zurück", "callback_data": "mc_sandermoon_back"}
]
]
ragnarok_online_menu = [
[
{"text": "Start", "callback_data": "ro_start"},
{"text": "Stop", "callback_data": "ro_stop"},
{"text": "<- Zurück", "callback_data": "ro_back"}
]
]
@ -87,13 +111,110 @@ ragnarok_online_menu = [
wow_menu = [
[
{"text": "Start", "callback_data": "wow_start"},
{"text": "Stop", "callback_data": "wow_stop"},
{"text": "<- Zurück", "callback_data": "wow_back"}
]
]
####
# Timer Functions
####
async def start_timer(context: ContextTypes.DEFAULT_TYPE, chat_id: int):
if chat_id in timers:
timers[chat_id].cancel()
timers[chat_id] = context.application.create_task(timer(context, chat_id))
async def timer(context: ContextTypes.DEFAULT_TYPE, chat_id: int):
await asyncio.sleep(60)
await send_main_menu(context, chat_id)
####
# User functions
####
def is_registered(user_id):
if not os.path.exists(SUBSCRIBERS_FILE):
return False
with open(SUBSCRIBERS_FILE, 'r') as file:
return str(user_id) in file.read().splitlines()
# Utility function to register a user
def register_user(user_id):
with open(SUBSCRIBERS_FILE, 'a') as file:
file.write(f"{user_id}\n")
# Password verification handler
async def verify_password(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
user_id = update.message.chat_id
if not is_registered(user_id):
if update.message.text == PASSWORD:
register_user(user_id)
await update.message.reply_text('Password accepted. Sie sind jetzt registriert.')
await send_main_menu(context, user_id)
await start_timer(context, user_id)
else:
await update.message.reply_text('Incorrect password. Bitte erneut eingeben.')
####
# Utils
####
# Function to send the main menu
async def send_main_menu(context: ContextTypes.DEFAULT_TYPE, chat_id: int):
keyboard = [
[InlineKeyboardButton("Option 1", callback_data='1')],
[InlineKeyboardButton("Option 2", callback_data='2')],
]
reply_markup = InlineKeyboardMarkup(keyboard)
await context.bot.send_message(chat_id=chat_id, text='Bitte wählen:', reply_markup=reply_markup)
# Broadcast message function
async def broadcast_message(application: Application, message: str):
subscribers = read_subscribers()
for chat_id in subscribers:
try:
await application.bot.send_message(chat_id=chat_id, text=message)
except Exception as e:
logging.error(f"Failed to send message to {chat_id}: {e}")
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text('Use /start to test this bot.')
def read_subscribers():
if not os.path.exists(SUBSCRIBERS_FILE):
return []
with open(SUBSCRIBERS_FILE, 'r') as file:
return [int(line.strip()) for line in file]
def save_subscriber(chat_id):
"""Save a new subscriber chat ID to the file."""
with open(SUBSCRIBERS_FILE, 'a') as file:
file.write(f"{chat_id}\n")
####
# Initialize Bot
####
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
user_id = update.message.chat_id if update.message else update.callback_query.message.chat_id
if is_registered(user_id):
keyboard = [
[InlineKeyboardButton("Option 1", callback_data='1')],
[InlineKeyboardButton("Option 2", callback_data='2')],
]
reply_markup = InlineKeyboardMarkup(keyboard)
if update.message:
await update.message.reply_text('Bitte wählen:', reply_markup=reply_markup)
elif update.callback_query:
await update.callback_query.message.reply_text('Bitte wählen:', reply_markup=reply_markup)
else:
await update.message.reply_text('Bitte das Zugriffspassword eingeben.')
####
# Command-Verarbeitung
####
"""
def handle_callback(update: Update, context: CallbackContext) -> None:
query = update.callback_query
data = query.data
@ -104,50 +225,92 @@ def handle_callback(update: Update, context: CallbackContext) -> None:
query.edit_message_text("Wähle eine Tool Funktion:", reply_markup=telegram.InlineKeyboardMarkup(tools_menu))
case "game_servers":
query.edit_message_text("Wähle einen Gameserver Typ:", reply_markup=telegram.InlineKeyboardMarkup(gameserver_menu))
# Tools
case "game_servers":
query.edit_message_text("Wähle einen Gameserver Typ:", reply_markup=telegram.InlineKeyboardMarkup(gameserver_menu))
case "nuc_satus":
pass
case "nuc_shutdown":
pass
case "nuc_back":
query.edit_message_text("Wähle ein Themengebiet aus:", reply_markup=telegram.InlineKeyboardMarkup(main_menu))
# TODO: Weiter bauen
# Game Servers
case "gameservers_status":
pass
case "gameservers_minecraft":
pass
case "gameservers_ragnarok_online":
pass
case "gameservers_wow":
pass
case "gameservers_back":
query.edit_message_text("Wähle ein Themengebiet aus:", reply_markup=telegram.InlineKeyboardMarkup(main_menu))
# Minecraft
case "minecraft_back":
query.edit_message_text("Wähle ein Game aus:", reply_markup=telegram.InlineKeyboardMarkup(gameserver_menu))
# Ragnarok Online
case "ro_back":
query.edit_message_text("Wähle ein Game aus:", reply_markup=telegram.InlineKeyboardMarkup(gameserver_menu))
# World of Warcraft
case "wow_back":
query.edit_message_text("Wähle ein Game aus:", reply_markup=telegram.InlineKeyboardMarkup(gameserver_menu))
# Default Case
case _:
print()
####
# Initialize Bot
####
# Telegram bot token
TELEGRAM_BOT_TOKEN = '6984289827:AAHNUM4F_U6233oa75nX5jXyQY6vC0NlZvw'
# File to store subscriber chat IDs
SUBSCRIBERS_FILE = 'telegramm_subscribers.txt'
async def start_bot(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
chat_id = update.message.chat_id
save_subscriber(chat_id)
await context.bot.send_message(chat_id=update.effective_chat.id, text="Sie wurden angemeldet für Nachrichten vom nuc_morroc.")
"""
async def handle_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
query = update.callback_query
await query.answer()
await start_timer(context, query.message.chat_id)
data = query.data
match data:
case "tools":
query.message.reply_text("Wähle eine Tool Funktion:", reply_markup=InlineKeyboardMarkup(tools_menu))
def load_subscribers():
"""Load subscriber chat IDs from the file."""
if os.path.exists(SUBSCRIBERS_FILE):
with open(SUBSCRIBERS_FILE, 'r') as file:
return [line.strip() for line in file.readlines()]
return []
match query.data_: == '1': #todo cases einbauen +finalisieren
# Nested menu for Option 1
gameserver_menu = [
[InlineKeyboardButton("Game 1", callback_data='game1')],
[InlineKeyboardButton("Game 2", callback_data='game2')],
[InlineKeyboardButton("Back", callback_data='start')],
]
await query.message.reply_text(text="Wähle ein Game aus:", reply_markup=InlineKeyboardMarkup(gameserver_menu))
elif query.data == '2':
# Nested menu for Option 2
other_menu = [
[InlineKeyboardButton("Service 1", callback_data='service1')],
[InlineKeyboardButton("Service 2", callback_data='service2')],
[InlineKeyboardButton("Back", callback_data='start')],
]
await query.message.reply_text(text="Wähle einen Service aus:", reply_markup=InlineKeyboardMarkup(other_menu))
elif query.data == 'start':
await start(update, context)
elif query.data.startswith('game'):
await query.message.reply_text(f"You selected {query.data}")
elif query.data.startswith('service'):
await query.message.reply_text(f"You selected {query.data}")
def save_subscriber(chat_id):
"""Save a new subscriber chat ID to the file."""
with open(SUBSCRIBERS_FILE, 'a') as file:
file.write(f"{chat_id}\n")
async def on_startup(application: Application):
# Broadcast message on startup
await broadcast_message(application, "Nuc-Morroc hier. Bin jetzt wach :)")
if __name__ == '__main__':
logging.info("Starte Telegram-Bot")
telegramm_app = ApplicationBuilder().token(TELEGRAM_BOT_TOKEN).build()
start_handler = CommandHandler('start', start_bot)
telegramm_app.add_handler(start_handler)
application = Application.builder().token(TELEGRAM_BOT_TOKEN).build()
application.add_handler(CommandHandler("start", start))
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, verify_password))
application.add_handler(CallbackQueryHandler(handle_callback))
application.add_handler(CommandHandler("help", help_command))
# Set up the startup handler
application.post_init(on_startup)
telegramm_app.run_polling()
application.run_polling()
Loading…
Cancel
Save