ThreeT2105 commited on
Commit
cf2cde5
·
verified ·
1 Parent(s): 4ff3015

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -0
app.py CHANGED
@@ -94,6 +94,70 @@ def notify_telegram(error_type, detail=""):
94
  f"📝 Chi tiết: {detail[:600]}"
95
  )
96
  threading.Thread(target=_send_telegram, args=(text,), daemon=True).start()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  # ==========================================
98
 
99
  current_detected_disease_context = "Chưa thực hiện quét mẫu bệnh phẩm."
@@ -676,6 +740,7 @@ def submit_user_followup(selected_option, followup_text, role="user"):
676
 
677
  if updated:
678
  save_expert_tickets(tickets)
 
679
 
680
  status_label, _ = get_ticket_status_display(target_ticket)
681
  updated_option_str = f"#{ticket_id} - {target_ticket['plant']} - {target_ticket['time']} - [{status_label}]"
@@ -729,6 +794,7 @@ def submit_expert_request(user_question, selected_plant, input_image):
729
  }
730
  tickets.append(new_ticket)
731
  save_expert_tickets(tickets)
 
732
  h_info, c_info = format_ticket_detail(new_ticket)
733
  return "📩 Đã gửi câu hỏi đến Hộp thư chờ Chuyên gia! Chuyên gia sẽ sớm xem xét và trả lời.", h_info + "<br><hr style='border: 1px solid #d4deda; margin: 12px 0;'><br>" + c_info, saved_img_path
734
 
 
94
  f"📝 Chi tiết: {detail[:600]}"
95
  )
96
  threading.Thread(target=_send_telegram, args=(text,), daemon=True).start()
97
+
98
+ # ============ BOT TELEGRAM THỨ 2: BÁO CHUYÊN GIA KHI CÓ CÂU HỎI TỪ NHÀ NÔNG ============
99
+ EXPERT_BOT_TOKEN = os.environ.get("EXPERT_BOT_TOKEN")
100
+ EXPERT_CHAT_ID = os.environ.get("EXPERT_CHAT_ID")
101
+
102
+ def _send_expert_telegram(text, image_path=None):
103
+ """Gửi tin cho chuyên gia; có ảnh lá thì gửi kèm ảnh, lỗi ảnh thì gửi chữ."""
104
+ base = f"https://api.telegram.org/bot{EXPERT_BOT_TOKEN}"
105
+ try:
106
+ if image_path and os.path.exists(image_path):
107
+ try:
108
+ with open(image_path, "rb") as f:
109
+ r = requests.post(
110
+ f"{base}/sendPhoto",
111
+ data={"chat_id": EXPERT_CHAT_ID, "caption": text[:1000]},
112
+ files={"photo": f},
113
+ timeout=20,
114
+ )
115
+ if r.ok:
116
+ return
117
+ print(f"⚠️ Telegram chuyên gia (gửi ảnh) trả lỗi: {r.status_code} {r.text[:200]}")
118
+ except Exception as e:
119
+ print(f"⚠️ Telegram chuyên gia (gửi ảnh) thất bại: {e}")
120
+ r = requests.post(
121
+ f"{base}/sendMessage",
122
+ json={"chat_id": EXPERT_CHAT_ID, "text": text},
123
+ timeout=10,
124
+ )
125
+ if not r.ok:
126
+ print(f"⚠️ Telegram chuyên gia trả lỗi: {r.status_code} {r.text[:200]}")
127
+ except Exception as e:
128
+ print(f"⚠️ Gửi Telegram chuyên gia thất bại: {e}")
129
+
130
+ def _dispatch_expert_telegram(text, image_path=None):
131
+ if not EXPERT_BOT_TOKEN or not EXPERT_CHAT_ID:
132
+ return
133
+ threading.Thread(target=_send_expert_telegram, args=(text, image_path), daemon=True).start()
134
+
135
+ def notify_expert_new_question(ticket):
136
+ """Nhà nông vừa gửi câu hỏi MỚI vào hộp thư chờ chuyên gia."""
137
+ context_text = str(ticket.get("context", ""))[:300]
138
+ text = (
139
+ f"📩 CÂU HỎI MỚI TỪ NHÀ NÔNG\n"
140
+ f"📌 Mã yêu cầu: #{ticket.get('id')}\n"
141
+ f"⏱️ {ticket.get('time')}\n"
142
+ f"🌱 Loại cây: {ticket.get('plant')}\n"
143
+ f"💬 Câu hỏi: {ticket.get('user_query')}\n"
144
+ f"🔬 Kết quả quét gần nhất: {context_text}\n\n"
145
+ f"👉 Đăng nhập hệ thống bằng tài khoản chuyên gia, vào 'Xem Lại Lịch Sử Bệnh Án' để trả lời."
146
+ )
147
+ _dispatch_expert_telegram(text, ticket.get("image_path"))
148
+
149
+ def notify_expert_followup(ticket, followup_text):
150
+ """Nhà nông hỏi THÊM trong một yêu cầu đã có."""
151
+ text = (
152
+ f"🔄 NHÀ NÔNG HỎI THÊM\n"
153
+ f"📌 Mã yêu cầu: #{ticket.get('id')}\n"
154
+ f"⏱️ {get_vn_time().strftime('%Y-%m-%d %H:%M:%S')}\n"
155
+ f"🌱 Loại cây: {ticket.get('plant')}\n"
156
+ f"💬 Nội dung hỏi thêm: {followup_text}\n\n"
157
+ f"👉 Đăng nhập hệ thống bằng tài khoản chuyên gia, vào 'Xem Lại Lịch Sử Bệnh Án' để trả lời."
158
+ )
159
+ _dispatch_expert_telegram(text)
160
+ # =========================================================================================
161
  # ==========================================
162
 
163
  current_detected_disease_context = "Chưa thực hiện quét mẫu bệnh phẩm."
 
740
 
741
  if updated:
742
  save_expert_tickets(tickets)
743
+ notify_expert_followup(target_ticket, followup_text.strip())
744
 
745
  status_label, _ = get_ticket_status_display(target_ticket)
746
  updated_option_str = f"#{ticket_id} - {target_ticket['plant']} - {target_ticket['time']} - [{status_label}]"
 
794
  }
795
  tickets.append(new_ticket)
796
  save_expert_tickets(tickets)
797
+ notify_expert_new_question(new_ticket)
798
  h_info, c_info = format_ticket_detail(new_ticket)
799
  return "📩 Đã gửi câu hỏi đến Hộp thư chờ Chuyên gia! Chuyên gia sẽ sớm xem xét và trả lời.", h_info + "<br><hr style='border: 1px solid #d4deda; margin: 12px 0;'><br>" + c_info, saved_img_path
800