all repos — groupgardenbot @ b0ffc4f6ed4b036cbf9176f78db121948a05900b

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