main.py (view raw)
1import os, logging
2from datetime import datetime
3from dotenv import load_dotenv
4from telegram import Update, User, InlineKeyboardMarkup, InlineKeyboardButton
5from telegram.ext import PersistenceInput, ApplicationBuilder, CallbackContext, CallbackQueryHandler, CommandHandler, PicklePersistence
6from telegram.error import BadRequest
7from Gardening import Plant
8logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
9logger = logging.getLogger(__name__)
10load_dotenv()
11
12async def reply(update: Update, context: CallbackContext, text: str = "", markup: str = ""):
13 return await context.bot.send_message(chat_id=update.effective_chat.id, text=text, reply_markup=markup, parse_mode='Markdown')
14
15async def edit(update: Update, context: CallbackContext, text: str = "", markup: str = ""):
16 try:
17 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')
18 except BadRequest:
19 logger.warning("Message contents were unchanged.")
20
21def get_plant_info(plant: Plant):
22 status = f'''
23```{plant.get_art()}
24owner : {plant.owner_name}
25name : {plant.name}
26stage : {plant.parse_plant()}
27age : {plant.age_days} days
28score : {plant.points}
29bonus : x{plant.generation_bonus - 1:.2f}
30last : {datetime.fromtimestamp(plant.last_water).strftime("%d/%m/%Y %H:%M:%S")}
31water : {plant.get_water()}
32```
33
34{plant.get_description()}
35'''
36 if plant.last_water_user != plant.owner:
37 status += f'Last watered by {plant.last_water_name}.'
38 return status
39
40def get_plant(context: CallbackContext, user_id: int):
41 try:
42 plant = context.bot_data[user_id]["plant"]
43 except KeyError:
44 return None
45
46 plant.update()
47 return plant
48
49def get_plant_markup(user_id: int, plant):
50
51 buttons = []
52 if not plant.dead:
53 buttons += [
54 [
55 InlineKeyboardButton(text="Innaffia π°", callback_data=f"water {user_id}"),
56 InlineKeyboardButton(text="Aggiorna π±", callback_data=f"show {user_id}"),
57 ]
58 ]
59
60 if plant.dead or plant.stage == 5:
61 buttons += [ [ InlineKeyboardButton(text="Ricomincia π°", callback_data=f"start {user_id}") ] ]
62
63 return InlineKeyboardMarkup(buttons)
64
65def new_plant(context: CallbackContext, who: User):
66 plant = Plant(who)
67 context.bot_data[who.id] = { "plant": plant }
68 return plant
69
70def start(context: CallbackContext, user_id: int, who: User):
71
72 plant = get_plant(context, user_id)
73 new_text = "Hai piantato un nuovo seme!"
74
75 if plant is not None:
76 if not (plant.dead or plant.stage == 5):
77 return "La tua pianta non Γ¨ ancora pronta per andarsene!", False
78
79 plant.start_over(who)
80 return new_text, True
81
82 new_plant(context, who)
83 return new_text, True
84
85async def start_handler(update: Update, context: CallbackContext):
86 user_id = update.effective_user.id
87 plant = get_plant(context, user_id)
88
89 response, new = start(context, update.effective_user.id, update.effective_user)
90
91 await reply(update, context, response)
92
93 if new:
94 text, markup = show(context, user_id)
95 await reply(update, context, text, markup)
96
97def water(context: CallbackContext, user_id: int, who: User):
98 plant = get_plant(context, user_id)
99
100 if plant is None:
101 return "Non hai niente da innaffiare! Usa /start per piantare un seme."
102
103 if plant.dead:
104 return "La pianta Γ¨ morta..."
105
106 plant.water(who)
107 return "Pianta innaffiata."
108
109def show(context: CallbackContext, user_id: int):
110 plant = get_plant(context, user_id)
111
112 if plant is None:
113 return "Non hai nessuna pianta da mostrare! Usa /start per piantarne una.", ""
114
115 text = get_plant_info(plant)
116 markup = get_plant_markup(user_id, plant)
117 return text, markup
118
119def rename(context: CallbackContext, user_id: int):
120 plant = get_plant(context, user_id)
121
122 if plant is None:
123 return "Non hai ancora piantato niente! Usa /start per piantare un seme."
124 try:
125 new_name = " ".join(context.args).strip()
126 if new_name == "":
127 raise IndexError
128 except IndexError:
129 return "Utilizzo: /rename nuovo nome"
130
131 plant.name = new_name
132 return f"Fatto! Adesso la tua pianta si chiama {new_name}!"
133
134async def water_handler(update: Update, context: CallbackContext):
135 answer = water(context, update.effective_user.id, update.effective_user)
136 return await reply(update, context, answer)
137
138async def show_handler(update: Update, context: CallbackContext):
139 user_id = update.effective_user.id
140 answer, markup = show(context, user_id)
141 return await reply(update, context, answer, markup)
142
143async def rename_handler(update: Update, context: CallbackContext):
144 user_id = update.effective_user.id
145 answer = rename(context, user_id)
146 return await reply(update, context, answer)
147
148async def keyboard_handler(update: Update, context: CallbackContext):
149 query = update.callback_query
150 data = query.data
151 user_id = None
152
153 if data.startswith("start"):
154 user_id = int(data.split(" ")[1])
155 if user_id != update.effective_user.id:
156 return await query.answer("Non puoi usare questo comando.")
157 text, _ = show(context, user_id)
158 await edit(update, context, text, None)
159 answer = start(context, user_id, update.effective_user)
160 await query.answer(answer)
161 text, markup = show(context, user_id)
162 return await reply(update, context, text, markup)
163
164 if data.startswith("water"):
165 user_id = int(data.split(" ")[1])
166 answer = water(context, user_id, update.effective_user)
167 await query.answer(answer)
168 text, markup = show(context, user_id)
169 return await edit(update, context, text, markup)
170
171 if data.startswith("show"):
172 user_id = int(data.split(" ")[1])
173 await query.answer()
174 text, markup = show(context, user_id)
175 return await edit(update, context, text, markup)
176
177 return await query.answer("Questo tasto non fa nulla.")
178
179async def kill_handler(update: Update, context: CallbackContext):
180 user_id = update.effective_user.id
181 plant = get_plant(context, user_id)
182 plant.dead = True
183 return await reply(update, context, "πππ", "")
184
185async def bloom_handler(update: Update, context: CallbackContext):
186 user_id = update.effective_user.id
187 plant = get_plant(context, user_id)
188 plant.points = 9999999
189 plant.dead = False
190 return await reply(update, context, "πΈπΈπΈ", "")
191
192if __name__ == "__main__":
193 pers = PersistenceInput(bot_data=True, user_data=False, callback_data=False, chat_data=False)
194
195 application = ApplicationBuilder()
196 application.token(os.getenv("token"))
197 application.persistence(PicklePersistence(filepath='bot-data.pkl', store_data=pers))
198 application = application.build()
199
200 application.add_handler(CallbackQueryHandler(callback=keyboard_handler))
201
202 application.add_handler(CommandHandler('start', start_handler))
203 application.add_handler(CommandHandler('water', water_handler))
204 application.add_handler(CommandHandler('show', show_handler))
205 application.add_handler(CommandHandler('rename', rename_handler))
206
207 if os.getenv("cheats") == "True":
208 application.add_handler(CommandHandler('kill', kill_handler))
209 application.add_handler(CommandHandler('bloom', bloom_handler))
210
211 #print(application.bot.name, "is up and running!")
212 application.run_polling()