all repos — groupgardenbot @ 6240c1d5461e9f1185ae835be26caa0c059a2702

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

main.py (view raw)

  1import os, logging, time
  2from dotenv import load_dotenv
  3from telegram import Update, User, InlineKeyboardMarkup, InlineKeyboardButton
  4from telegram.ext import PersistenceInput, ApplicationBuilder, CallbackContext, CallbackQueryHandler, CommandHandler, PicklePersistence
  5from Gardening import Plant
  6logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
  7load_dotenv()
  8
  9async def reply(update: Update, context: CallbackContext, text: str = "", markup: str = ""):
 10    return await context.bot.send_message(chat_id=update.effective_chat.id, text=text, reply_markup=markup, parse_mode='Markdown')
 11
 12async def edit(update: Update, context: CallbackContext, text: str = "", markup: str = ""):
 13    return await 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_info(plant: Plant):
 16    return f'''
 17```{plant.get_art()}
 18owner : {plant.owner_name}
 19name  : {plant.name}
 20stage : {plant.parse_plant()}
 21age   : {plant.age_days} days
 22score : {plant.points}
 23bonus : x{plant.generation_bonus - 1:.2f}
 24water : {plant.get_water()}```
 25
 26{plant.get_description()}
 27{f'Last watered by {plant.last_water_name}.' if plant.last_water_user != plant.owner else ""}
 28'''
 29
 30def get_plant(context: CallbackContext, user_id: int):
 31        try:
 32            plant = context.bot_data[user_id]["plant"]
 33        except KeyError:
 34            return None
 35        
 36        plant.update()
 37        return plant
 38
 39def get_plant_markup(user_id: int):
 40    return InlineKeyboardMarkup([
 41        [
 42            InlineKeyboardButton(text="Innaffia 🚰", callback_data=f"water {user_id}"),
 43            InlineKeyboardButton(text="Aggiorna 🌱", callback_data=f"show {user_id}"),
 44        ]
 45    ])
 46
 47async def start_handler(update: Update, context: CallbackContext):
 48    user_id = update.effective_user.id
 49    plant = get_plant(context, user_id)
 50    new = False
 51    
 52    if plant is None:
 53        plant = Plant(update.effective_user)
 54        context.bot_data[user_id] = { "plant" : plant }
 55        new = True
 56
 57    if plant.dead or plant.stage == 5:
 58        plant.start_over(update.effective_user)
 59        new = True
 60    
 61    if new:
 62        show_handler(update, context)
 63        return await reply(update, context, "Hai piantato un nuovo seme! Adesso usa /water o un tasto sopra per innaffiarlo.")
 64    
 65    return await reply(update, context, "La tua pianta non è ancora pronta per andarsene!")
 66
 67def water(context: CallbackContext, user_id: int, who: User):
 68    plant = get_plant(context, user_id)
 69    
 70    if plant is None:
 71        return "Non hai niente da innaffiare! Usa /start per piantare un seme."
 72
 73    if plant.dead:
 74        return "La pianta è morta..."
 75
 76    plant.water(who)
 77    return "Pianta innaffiata."
 78
 79def show(context: CallbackContext, user_id: int):
 80    plant = get_plant(context, user_id)
 81    
 82    if plant is None:
 83        return "Non hai nessuna pianta da mostrare! Usa /start per piantarne una.", ""
 84    
 85    text = get_plant_info(plant)
 86    markup = get_plant_markup(user_id)
 87    return text, markup
 88
 89def rename(context: CallbackContext, user_id: int):
 90    plant = get_plant(context, user_id)
 91    
 92    if plant is None:
 93        return "Non hai ancora piantato niente! Usa /start per piantare un seme."
 94    try:
 95        new_name = " ".join(context.args).strip()
 96        if new_name == "":
 97            raise IndexError
 98    except IndexError:
 99        return "Utilizzo: /rename nuovo nome"
100    
101    plant.name = new_name
102    return f"Fatto! Adesso la tua pianta si chiama {new_name}!"
103
104async def water_handler(update: Update, context: CallbackContext):
105    answer = water(context, update.effective_user.id, update.effective_user)
106    return await reply(update, context, answer)
107
108async def show_handler(update: Update, context: CallbackContext):
109    user_id = update.effective_user.id
110    answer, markup = show(context, user_id)
111    return await reply(update, context, answer, markup)
112    
113async def rename_handler(update: Update, context: CallbackContext):
114    user_id = update.effective_user.id
115    answer = rename(context, user_id)
116    return await reply(update, context, answer)
117
118async def keyboard_handler(update: Update, context: CallbackContext):
119    query = update.callback_query
120    data = query.data
121    user_id = None
122    
123    if data.startswith("water"):
124        user_id = int(data.split(" ")[1])
125        answer = water(context, user_id, update.effective_user)
126        await query.answer(answer)
127    
128    if data.startswith("show"):
129        user_id = int(data.split(" ")[1])
130        await query.answer()
131    
132    if user_id is not None:
133        text, markup = show(context, user_id)
134        return await edit(update, context, text, markup)
135        
136    return await query.answer("Questo tasto non fa nulla.")
137
138if __name__ == "__main__":
139    pers = PersistenceInput(bot_data=True, user_data=False, callback_data=False, chat_data=False)
140    
141    application = ApplicationBuilder()
142    application.token(os.getenv("token"))
143    application.persistence(PicklePersistence(filepath='bot-data.pkl', store_data=pers))
144    application = application.build()
145    
146    application.add_handler(CallbackQueryHandler(callback=keyboard_handler))
147    
148    
149    application.add_handler(CommandHandler('start', start_handler))
150    application.add_handler(CommandHandler('water', water_handler))
151    application.add_handler(CommandHandler('show', show_handler))
152    application.add_handler(CommandHandler('rename', rename_handler))
153    
154    #print(application.bot.name, "is up and running!")
155    application.run_polling()