all repos — groupgardenbot @ b610caa5ffb191c30ec7269d74b7d3d856e0e282

An extension of the game "botany", originally designed for unix-based systems, to the Telegram Bot API.

main.py (view raw)

  1import os, logging
  2logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
  3from telegram.error import BadRequest
  4from telegram import Update, User, InlineKeyboardMarkup, InlineKeyboardButton
  5from telegram.ext import Updater, CallbackContext, CallbackQueryHandler, CommandHandler, MessageHandler, PicklePersistence
  6from dotenv import load_dotenv
  7load_dotenv()
  8from Gardening import Plant, get_plant_info
  9
 10def reply(update: Update, context: CallbackContext, text: str = "", markup: str = ""):
 11    return context.bot.send_message(chat_id=update.effective_chat.id, text=text, reply_markup=markup, parse_mode='Markdown')
 12
 13def get_plant(context: CallbackContext, user_id: int):
 14        try:
 15            plant = context.bot_data[user_id]["plant"]
 16        except KeyError:
 17            return None
 18        
 19        plant.update()
 20        return plant
 21
 22def start_handler(update: Update, context: CallbackContext):
 23    
 24    plant = get_plant(context, update.effective_user.id)
 25    new = False
 26    
 27    if plant is None:
 28        context.bot_data[update.effective_user.id] = { "plant" : Plant(update.effective_user.id) }
 29        new = True
 30
 31    if plant.dead or plant.stage == 5:
 32        plant.start_over()
 33        new = True
 34    
 35    if new:
 36        return reply(update, context, "Hai piantato un nuovo seme! Adesso usa /water per innaffiarlo.")
 37    
 38    return reply(update, context, "La tua pianta non è ancora pronta per andarsene!")
 39
 40def water(context: CallbackContext, user_id: int):
 41    plant = get_plant(context, user_id)
 42    
 43    if plant is None:
 44        return "Non hai nessuna pianta da innaffiare! Usa /start per piantarne una."
 45
 46    if plant.dead:
 47        return "La pianta è morta..."
 48    
 49    plant.water()
 50    return "Pianta innaffiata."
 51
 52def show(context: CallbackContext, user_id: int):
 53    plant = get_plant(context, user_id)
 54    
 55    if plant is None:
 56        return "Non hai nessuna pianta da mostrare! Usa /start per piantarne una."
 57
 58    return get_plant_info(plant)
 59
 60def water_handler(update: Update, context: CallbackContext):
 61    answer = water(context, update.effective_user.id)
 62    return reply(update, context, answer)
 63
 64def show_handler(update: Update, context: CallbackContext):
 65    user_id = update.effective_user.id
 66    answer = show(context, user_id)
 67    
 68    markup = InlineKeyboardMarkup([[InlineKeyboardButton(text="Innaffia 🚰", callback_data=f"water {user_id}")]])
 69    reply(update, context, answer, markup)
 70
 71def keyboard_handler(update: Update, context: CallbackContext):
 72    query = update.callback_query
 73    data = query.data
 74    
 75    if data.startswith("water"):
 76        user_id = int(data.split(" ")[1])
 77        answer = water(context, user_id)
 78        if user_id != update.effective_user.id:
 79            reply(update, context, f"{update.effective_user.full_name} ha innaffiato la pianta di qualcuno!")
 80        return query.answer(answer)
 81    
 82    return query.answer("Questo tasto non fa nulla.")
 83
 84def main():
 85    
 86    updater = Updater(token=os.getenv("token"),
 87                      persistence=PicklePersistence(filename='bot-data.pkl',
 88                                                    store_user_data=False,
 89                                                    store_bot_data=True,
 90                                                    store_callback_data=False,
 91                                                    store_chat_data=False
 92                                                    ))
 93    
 94    dispatcher = updater.dispatcher
 95    
 96    
 97    # commands
 98    dispatcher.add_handler(CommandHandler('start', start_handler))
 99    dispatcher.add_handler(CommandHandler('water', water_handler))
100    dispatcher.add_handler(CommandHandler('show', show_handler))
101    
102    dispatcher.add_handler(CallbackQueryHandler(callback=keyboard_handler))
103    
104    updater.start_polling()
105    print(os.getenv("bot_name"))
106    updater.idle()
107
108if __name__ == "__main__":
109    main()