Skip to content

Commit a38e91c

Browse files
authored
Update bot.py
added new conditions 1. if irrigation_app is not None and irrigation_app != 'NA' 2. if (phic is not None and phit is not None and phic >= phit and irrigation_need != 'NA' 3. if row get_irrigation_data is none
1 parent 4fb7157 commit a38e91c

File tree

1 file changed

+94
-18
lines changed
  • WWCS/irrigation/telegramBot

1 file changed

+94
-18
lines changed

WWCS/irrigation/telegramBot/bot.py

Lines changed: 94 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -109,20 +109,21 @@ async def get_irrigation_data(chat_id=None):
109109
s.irrigation,
110110
i.date,
111111
i.irrigationNeed,
112+
i.irrigationApp,
112113
h.telegramID,
113114
JSON_UNQUOTE(JSON_EXTRACT(s.fieldproperties, '$.type')) AS type,
114115
JSON_UNQUOTE(JSON_EXTRACT(s.fieldproperties, '$.measurement_device')) AS device,
115116
JSON_UNQUOTE(JSON_EXTRACT(s.fieldproperties, '$.Crop')) AS crop,
116117
JSON_EXTRACT(s.fieldproperties, '$.area') AS area,
117118
JSON_EXTRACT(s.fieldproperties, '$.IE') AS ie,
118-
JSON_EXTRACT(s.fieldproperties, '$.WA') AS wa
119+
JSON_EXTRACT(s.fieldproperties, '$.WA') AS wa,
120+
i.PHIc as phic,
121+
i.PHIt as phit
119122
FROM SitesHumans.Sites s
120123
JOIN SitesHumans.Humans h ON JSON_UNQUOTE(JSON_EXTRACT(s.fieldproperties, '$.humanID')) = h.humanID
121124
JOIN WWCServices.Irrigation i ON i.siteID = s.siteID
122125
WHERE
123126
s.irrigation = 1
124-
AND i.PHIc < i.PHIt
125-
AND i.irrigationApp = 0
126127
AND i.date = DATE_SUB(CURDATE(), INTERVAL 1 DAY)
127128
"""
128129

@@ -154,11 +155,42 @@ async def get_irrigation_data(chat_id=None):
154155
# The user is not in the system at all
155156
await send_message_safe(
156157
chat_id,
157-
_("❌ Your Telegram ID was not found in our system. Please check if you registered correctly or contact support.")
158+
_("❌ I am sorry, your telegramID is not in our system. Please contact support.")
158159
)
159160
return False
160-
return row
161161

162+
irrigation_app = row['irrigationApp'] if 'irrigationApp' in row else 0
163+
phic = float(row['phic']) if row['phic'] is not None and row['phic'] != 'NA' else None
164+
phit = float(row['phit']) if row['phit'] is not None and row['phit'] != 'NA' else None
165+
irrigation_need = row['irrigationNeed']
166+
167+
print(
168+
f"[DEBUG] irrigation_app: {irrigation_app}, phic: {phic}, phit: {phit}, irrigation_need: {irrigation_need}")
169+
170+
# 1. Check: if irrigation is already applied
171+
if irrigation_app is not None and irrigation_app != 'NA':
172+
try:
173+
if float(irrigation_app) > 0:
174+
await send_message_safe(
175+
chat_id,
176+
_("❌ I am sorry, you have already registered your irrigation. Please contact support.")
177+
)
178+
return False # here bot exits
179+
except (ValueError, TypeError):
180+
pass
181+
182+
if (phic is not None and phit is not None and phic >= phit and irrigation_need != 'NA' and
183+
f"no_irrigation_msg_{chat_id}" not in user_states):
184+
await send_message_safe(
185+
chat_id,
186+
_("🌤 Your plot does not require irrigation today. If you want to irrigate nevertheless, press 'Start irrigation'. Otherwise simply come back tomorrow.")
187+
)
188+
user_states[f"no_irrigation_msg_{chat_id}"] = True # Помечаем как отправленное
189+
190+
# IMPORTANT: DO NOT return, continue working!
191+
# The message is just informative, the bot continues to work
192+
pass
193+
return row
162194
except Exception as e:
163195
print(f"Database error for chat_id {chat_id}: {str(e)}")
164196
await send_message_safe(
@@ -228,23 +260,35 @@ async def send_message_safe(chat_id, text, reply_markup=None):
228260
async def check_irrigation(chat_id):
229261
try:
230262
row = await get_irrigation_data(chat_id)
263+
print(f"[DEBUG] check_irrigation: row = {row}, type = {type(row)}")
264+
265+
if row is False:
266+
return # The error has already been processed in get_irrigation_data
267+
268+
269+
if isinstance(row, bool):
270+
if row is True:
271+
# If True is returned, it means "no irrigation required"
272+
return True # Just finishing
273+
else:
274+
return False # Error
231275

232276
# Handling a special case where irrigation is not required
233277
if row is None:
234278
await send_message_safe(
235279
chat_id,
236-
_("🌤 Your plot does not require irrigation today. If you want to irrigate nevertheless, press ‘Start irrigation’. Otherwise simply come back tomorrow.")
280+
_("🌤 I am sorry, I have a technical problem and cannot provide you with a recommendation. Please contact support. Otherwise simply come back tomorrow.")
237281
)
238282
return True
239283

240-
# Error handling (when False is returned)
241-
if row is False:
242-
return False
243-
284+
# # Error handling (when False is returned)
285+
# if row is False:
286+
# return False
244287

245288
if not row or 'type' not in row or 'device' not in row:
246289
print(f"[ERROR] Invalid row data for chat_id: {chat_id}")
247-
await send_message_safe(chat_id, "❌ Your data was not found in the system. Please check if you have registered correctly and filled in all required fields. If the problem persists, please contact support.")
290+
await send_message_safe(chat_id,
291+
"❌ Your data was not found in the system. Please check if you have registered correctly and filled in all required fields. If the problem persists, please contact support.")
248292
return False
249293

250294
print(f"[DEBUG] Processing irrigation for: {row['firstName']} (type: {row['type']}, device: {row['device']})")
@@ -253,7 +297,8 @@ async def check_irrigation(chat_id):
253297

254298
if 'irrigationNeed' not in row or 'area' not in row or 'wa' not in row or 'ie' not in row:
255299
print(f"[ERROR] Missing required fields in row data for chat_id: {chat_id}")
256-
await send_message_safe(chat_id, "❌ Configuration error: required data is missing. Please check your profile and fill in all required fields or contact support.")
300+
await send_message_safe(chat_id,
301+
"❌ Configuration error: required data is missing. Please check your profile and fill in all required fields or contact support.")
257302
return False
258303

259304
m3_needed = (float(row['irrigationNeed']) * 10 * float(row['area']) * float(row['wa'])) / float(row['ie'])
@@ -389,7 +434,7 @@ async def calculate_irrigation(chat_id, water_level, irrigation_need, area, ie,
389434
async def start(message):
390435
try:
391436
markup = create_reply_keyboard()
392-
await send_message_safe(message.chat.id, reply_markup=markup)
437+
await send_message_safe(message.chat.id, "Select action:", reply_markup=markup)
393438
await check_irrigation(message.chat.id)
394439
except Exception as e:
395440
print(f"[ERROR] in start command: {str(e)}")
@@ -400,15 +445,21 @@ async def start(message):
400445
async def handle_recommendation(message):
401446
chat_id = message.chat.id
402447
try:
403-
if chat_id in user_irrigation_data:
404-
print(f"[DEBUG] Clearing previous irrigation data for {chat_id}")
405-
del user_irrigation_data[chat_id]
406-
448+
# if chat_id in user_irrigation_data:
449+
# print(f"[DEBUG] Clearing previous irrigation data for {chat_id}")
450+
# del user_irrigation_data[chat_id]
451+
407452
row = await get_irrigation_data(chat_id)
453+
454+
if row is False:
455+
print("[DEBUG] Row is False, returning")
456+
return
457+
408458
if row is None:
409459
await send_message_safe(chat_id, _("❌ Your data was not found in the system"))
410460
return
411461

462+
412463
if row['type'] == "treatment" and row['device'] == "thomson_profile":
413464
user_states[chat_id] = "waiting_for_water_level"
414465
await send_message_safe(chat_id,
@@ -428,6 +479,10 @@ async def handle_recommendation(message):
428479
user_states[chat_id] = "waiting_for_water_level_control"
429480
return
430481

482+
elif row['type'] == "treatment" and row['device'] == "total_meter":
483+
await send_message_safe(chat_id, _("For your plot and device type you need to press 'Irrigation finished and enter m³ used water in total'"))
484+
return
485+
431486
else:
432487
await send_recommendation(
433488
chat_id,
@@ -557,7 +612,7 @@ async def handle_water_level(message):
557612
water_level = float("".join(filter(lambda x: x.isdigit() or x == '.', message.text)))
558613

559614
# We check that the water level is within the acceptable range.
560-
if water_level < 1 or water_level > 25:
615+
if water_level < 0 or water_level > 25:
561616
await send_message_safe(
562617
chat_id,
563618
_("⚠️ Incorrect water level! Acceptable values from 1 to 25 cm.\n"
@@ -613,10 +668,31 @@ async def handle_send_data(message):
613668
notification_manager.remove_all_jobs(chat_id)
614669

615670
row = await get_irrigation_data(chat_id)
671+
672+
if row is False:
673+
print("[DEBUG] Row is False, returning")
674+
return
675+
616676
if row is None:
617677
await send_message_safe(chat_id, _("❌ Your data was not found in the system"))
618678
return
619679

680+
irrigation_app = row['irrigationApp'] if 'irrigationApp' in row else 0
681+
print(f"[DEBUG] irrigation_app value: {irrigation_app}, type: {type(irrigation_app)}")
682+
try:
683+
irrigation_app_float = float(irrigation_app)
684+
if irrigation_app_float > 0:
685+
await send_message_safe(
686+
chat_id,
687+
_("❌ I am sorry, you have already registered your irrigation. Please contact support.")
688+
)
689+
print(f"[DEBUG] Irrigation already registered: {irrigation_app_float}, stopping bot")
690+
return # Завершаем работу бота
691+
except (ValueError, TypeError):
692+
print(f"[DEBUG] Could not convert irrigation_app to float: {irrigation_app}")
693+
694+
695+
620696
if row['type'] == "treatment" and row['device'] == "total_meter":
621697
print("[SAVE_DATA_TOTAL_METER] Requesting actual water usage")
622698
await send_message_safe(chat_id, _("Please enter the volume that you irrigated today (in m³):"))

0 commit comments

Comments
 (0)