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