all repos — groupgardenbot @ dd587ca3c8ea6677ed6671c9aa264c494d3d681e

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

main.py (view raw)

  1import os, logging
  2from dotenv import load_dotenv
  3from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton
  4from telegram.ext import Updater, CallbackContext, CallbackQueryHandler, CommandHandler, PicklePersistence
  5from Gardening import Plant, get_plant_info
  6logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
  7load_dotenv()
  8
  9def reply(update: Update, context: CallbackContext, text: str = "", markup: str = ""):
 10    return context.bot.send_message(chat_id=update.effective_chat.id, text=text, reply_markup=markup, parse_mode='Markdown')
 11
 12def edit(update: Update, context: CallbackContext, text: str = "", markup: str = ""):
 13    context.bot.editMessageText(chat_id=update.effective_chat.id, message_id=update.effective_message.message_id, text=text, reply_markup=markup, parse_mode='Markdown')
 14
 15def get_plant(context: CallbackContext, user_id: int):
 16        try:
 17            plant = context.bot_data[user_id]["plant"]
 18        except KeyError:
 19            return None
 20        
 21        plant.update()
 22        return plant
 23
 24def get_plant_markup(user_id: int):
 25    return InlineKeyboardMarkup([
 26        [
 27            InlineKeyboardButton(text="Innaffia 🚰", callback_data=f"water {user_id}"),
 28            InlineKeyboardButton(text="Aggiorna 🌱", callback_data=f"show {user_id}"),
 29        ]
 30    ])
 31
 32def start_handler(update: Update, context: CallbackContext):
 33    user_id = update.effective_user.id
 34    plant = get_plant(context, user_id)
 35    new = False
 36    
 37    if plant is None:
 38        plant = Plant(user_id)
 39        context.bot_data[update.effective_user.id] = { "plant" : plant }
 40        new = True
 41
 42    if plant.dead or plant.stage == 5:
 43        plant.start_over()
 44        new = True
 45    
 46    if new:
 47        show_handler(update, context)
 48        return reply(update, context, "Hai piantato un nuovo seme! Adesso usa /water per innaffiarlo.")
 49    
 50    return reply(update, context, "La tua pianta non è ancora pronta per andarsene!")
 51
 52def water(context: CallbackContext, user_id: int):
 53    plant = get_plant(context, user_id)
 54    
 55    if plant is None:
 56        return "Non hai niente da innaffiare! Usa /start per piantare un seme."
 57
 58    if plant.dead:
 59        return "La pianta è morta..."
 60    
 61    plant.water()
 62    return "Pianta innaffiata."
 63
 64def show(context: CallbackContext, user_id: int):
 65    plant = get_plant(context, user_id)
 66    
 67    if plant is None:
 68        return "Non hai nessuna pianta da mostrare! Usa /start per piantarne una.", ""
 69    
 70    text = get_plant_info(plant)
 71    markup = get_plant_markup(user_id)
 72    return text, markup
 73
 74def rename(context: CallbackContext, user_id: int):
 75    plant = get_plant(context, user_id)
 76    
 77    if plant is None:
 78        return "Non hai ancora piantato niente! Usa /start per piantare un seme."
 79    try:
 80        new_name = " ".join(context.args).strip()
 81        if new_name == "":
 82            raise IndexError
 83    except IndexError:
 84        return "Utilizzo: /rename <nuovo nome>"
 85    
 86    plant.name = new_name
 87    return f"Fatto! Adesso la tua pianta si chiama {new_name}!"
 88
 89def water_handler(update: Update, context: CallbackContext):
 90    answer = water(context, update.effective_user.id)
 91    return reply(update, context, answer)
 92
 93def show_handler(update: Update, context: CallbackContext):
 94    user_id = update.effective_user.id
 95    answer, markup = show(context, user_id)
 96    reply(update, context, answer, markup)
 97    
 98def rename_handler(update: Update, context: CallbackContext):
 99    user_id = update.effective_user.id
100    answer = rename(context, user_id)
101    reply(update, context, answer)
102
103def keyboard_handler(update: Update, context: CallbackContext):
104    query = update.callback_query
105    data = query.data
106    user_id = None
107    
108    if data.startswith("water"):
109        user_id = int(data.split(" ")[1])
110        answer = water(context, user_id)
111        query.answer(answer)
112    
113    if data.startswith("show"):
114        user_id = int(data.split(" ")[1])
115        query.answer()
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
123if __name__ == "__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()