main.py (view raw)
1import os, logging, time
2from dotenv import load_dotenv
3from telegram import Update, User, InlineKeyboardMarkup, InlineKeyboardButton
4from telegram.ext import Updater, 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
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_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}
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
47def 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 reply(update, context, "Hai piantato un nuovo seme! Adesso usa /water o un tasto sopra per innaffiarlo.")
64
65 return 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
104def water_handler(update: Update, context: CallbackContext):
105 answer = water(context, update.effective_user.id, update.effective_user)
106 return reply(update, context, answer)
107
108def show_handler(update: Update, context: CallbackContext):
109 user_id = update.effective_user.id
110 answer, markup = show(context, user_id)
111 reply(update, context, answer, markup)
112
113def rename_handler(update: Update, context: CallbackContext):
114 user_id = update.effective_user.id
115 answer = rename(context, user_id)
116 reply(update, context, answer)
117
118def 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 query.answer(answer)
127
128 if data.startswith("show"):
129 user_id = int(data.split(" ")[1])
130 query.answer()
131
132 if user_id is not None:
133 text, markup = show(context, user_id)
134 return edit(update, context, text, markup)
135
136 return query.answer("Questo tasto non fa nulla.")
137
138if __name__ == "__main__":
139 updater = Updater(token=os.getenv("token"),
140 persistence=PicklePersistence(filename='bot-data.pkl',
141 store_user_data=False,
142 store_bot_data=True,
143 store_callback_data=False,
144 store_chat_data=False
145 ))
146 dispatcher = updater.dispatcher
147
148 dispatcher.add_handler(CommandHandler('start', start_handler))
149 dispatcher.add_handler(CommandHandler('water', water_handler))
150 dispatcher.add_handler(CommandHandler('show', show_handler))
151 dispatcher.add_handler(CommandHandler('rename', rename_handler))
152 dispatcher.add_handler(CallbackQueryHandler(callback=keyboard_handler))
153
154 updater.start_polling()
155 print(updater.bot.name, "is up and running!")
156 updater.idle()