all repos — groupgardenbot @ 0e04eaf6a49e512e4821d45558b1166c9404708c

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 get_plant_markup(user_id: int):
 23    return InlineKeyboardMarkup([
 24        [
 25            InlineKeyboardButton(text="Innaffia 🚰", callback_data=f"water {user_id}"),
 26            InlineKeyboardButton(text="Mostra 🌱", callback_data=f"show {user_id}"),
 27        ]
 28    ])
 29
 30def start_handler(update: Update, context: CallbackContext):
 31    user_id = update.effective_user.id
 32    plant = get_plant(context, user_id)
 33    new = False
 34    
 35    if plant is None:
 36        plant = Plant(user_id)
 37        context.bot_data[update.effective_user.id] = { "plant" : Plant(user_id) }
 38        new = True
 39
 40    if plant.dead or plant.stage == 5:
 41        plant.start_over()
 42        new = True
 43    
 44    if new:
 45        show_handler(update, context)
 46        return reply(update, context, "Hai piantato un nuovo seme! Adesso usa /water per innaffiarlo.")
 47    
 48    return reply(update, context, "La tua pianta non è ancora pronta per andarsene!")
 49
 50def water(context: CallbackContext, user_id: int):
 51    plant = get_plant(context, user_id)
 52    
 53    if plant is None:
 54        return "Non hai niente da innaffiare! Usa /start per piantare un seme."
 55
 56    if plant.dead:
 57        return "La pianta è morta..."
 58    
 59    plant.water()
 60    return "Pianta innaffiata."
 61
 62def show(context: CallbackContext, user_id: int):
 63    plant = get_plant(context, user_id)
 64    
 65    if plant is None:
 66        return "Non hai nessuna pianta da mostrare! Usa /start per piantarne una.", ""
 67
 68    markup = get_plant_markup(user_id)
 69    return get_plant_info(plant), markup
 70
 71def rename(context: CallbackContext, user_id: int):
 72    plant = get_plant(context, user_id)
 73    
 74    if plant is None:
 75        return "Non hai ancora piantato niente! Usa /start per piantare un seme."
 76    try:
 77        new_name = " ".join(context.args).strip()
 78        if new_name == "":
 79            raise IndexError
 80    except IndexError:
 81        return "Utilizzo: /rename <nuovo nome>"
 82    
 83    plant.name = new_name
 84    return f"Fatto! Adesso la tua pianta si chiama {new_name}!"
 85
 86def water_handler(update: Update, context: CallbackContext):
 87    answer = water(context, update.effective_user.id)
 88    return reply(update, context, answer)
 89
 90def show_handler(update: Update, context: CallbackContext):
 91    user_id = update.effective_user.id
 92    answer, markup = show(context, user_id)
 93    reply(update, context, answer, markup)
 94    
 95def rename_handler(update: Update, context: CallbackContext):
 96    user_id = update.effective_user.id
 97    answer = rename(context, user_id)
 98    reply(update, context, answer)
 99
100def keyboard_handler(update: Update, context: CallbackContext):
101    query = update.callback_query
102    data = query.data
103    
104    if data.startswith("water"):
105        user_id = int(data.split(" ")[1])
106        answer = water(context, user_id)
107        if user_id != update.effective_user.id:
108            reply(update, context, f"{update.effective_user.full_name} ha innaffiato la pianta di qualcuno!")
109        return query.answer(answer)
110    
111    if data.startswith("show"):
112        user_id = int(data.split(" ")[1])
113        answer, markup = show(context, user_id)
114        reply(update, context, answer, markup)
115        
116    return query.answer("Questo tasto non fa nulla.")
117
118def main():
119    updater = Updater(token=os.getenv("token"),
120                      persistence=PicklePersistence(filename='bot-data.pkl',
121                                                    store_user_data=False,
122                                                    store_bot_data=True,
123                                                    store_callback_data=False,
124                                                    store_chat_data=False
125                                                    ))
126    dispatcher = updater.dispatcher
127    
128    # commands
129    dispatcher.add_handler(CommandHandler('start', start_handler))
130    dispatcher.add_handler(CommandHandler('water', water_handler))
131    dispatcher.add_handler(CommandHandler('show', show_handler))
132    dispatcher.add_handler(CommandHandler('rename', rename_handler))
133    dispatcher.add_handler(CallbackQueryHandler(callback=keyboard_handler))
134    
135    updater.start_polling()
136    print(updater.bot.name, "is up and running!")
137    updater.idle()
138
139if __name__ == "__main__":
140    main()