-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot_handlers.py
More file actions
329 lines (267 loc) · 13.2 KB
/
Copy pathbot_handlers.py
File metadata and controls
329 lines (267 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Bot Handler Fonksiyonları - Part 2
bot.py dosyasının devamı
"""
from datetime import datetime, timedelta
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import ContextTypes
from telegram.constants import ParseMode
class BotHandlers:
"""Bot handler fonksiyonlarının bulunduğu sınıf"""
def __init__(self, bot_instance):
self.bot = bot_instance
self.db = bot_instance.db
self.scraper = bot_instance.scraper
self.logger = bot_instance.logger
async def reminder_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Hatırlatıcı ayarlama komutu"""
try:
keyboard = [
[InlineKeyboardButton("🔔 1 gün önceden", callback_data="remind_1")],
[InlineKeyboardButton("🔔 3 gün önceden", callback_data="remind_3")],
[InlineKeyboardButton("🔔 1 hafta önceden", callback_data="remind_7")],
[InlineKeyboardButton("❌ Hatırlatıcıyı Kapat", callback_data="remind_off")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
message = """
🔔 **HATIRLATICI AYARLARI**
Vergi yükümlülükleriniz için ne kadar önceden hatırlatma almak istiyorsunuz?
**Mevcut Hatırlatmalar:**
• Kurumlar Vergisi beyannamesi
• KDV beyannamesi
• Muhtasar beyanname
• Gelir vergisi stopajı
• Diğer önemli vergi tarihleri
Aşağıdan bir seçenek seçin:
"""
await update.message.reply_text(
message,
parse_mode=ParseMode.MARKDOWN,
reply_markup=reply_markup
)
except Exception as e:
self.logger.error(f"Reminder command hatası: {str(e)}")
await update.message.reply_text("❌ Hatırlatıcı ayarları yüklenirken hata oluştu.")
async def status_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Bot durumu komutu"""
try:
# Veritabanı bağlantısını test et
db_status = "✅ Bağlı"
try:
self.db.execute_query("SELECT 1")
except:
db_status = "❌ Bağlantı sorunu"
# Scraper durumunu test et
scraper_status = "✅ Çalışıyor"
try:
test_updates = self.scraper.get_all_updates()
if not test_updates:
scraper_status = "⚠️ Veri çekme sorunu"
except:
scraper_status = "❌ Hata"
# Kullanıcı sayısı
try:
result = self.db.execute_query("SELECT COUNT(*) as count FROM users WHERE is_active = TRUE")
user_count = result[0]['count'] if result else 0
except:
user_count = "Bilinmiyor"
status_message = f"""
🤖 **BOT DURUM RAPORU**
**Sistem Durumu:**
🗄️ Veritabanı: {db_status}
🌐 Web Scraper: {scraper_status}
👥 Aktif Kullanıcı: {user_count}
**Bot Bilgileri:**
📅 Son güncelleme: {datetime.now().strftime('%d.%m.%Y %H:%M')}
⚡ Uptime: Bot aktif
🔄 Otomatik güncelleme: Açık
**Veri Kaynakları:**
• GİB Dijital Vergi Dairesi
• GİB Ana Sayfa
• İl Defterdarlıkları
• Vergi mevzuatı siteleri
✅ **Sistem normal çalışıyor!**
"""
await update.message.reply_text(status_message, parse_mode=ParseMode.MARKDOWN)
except Exception as e:
self.logger.error(f"Status command hatası: {str(e)}")
await update.message.reply_text("❌ Durum bilgisi alınırken hata oluştu.")
async def test_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Test komutu"""
try:
await update.message.reply_text("🔧 Sistem testleri başlatılıyor...")
test_results = []
# 1. Veritabanı testi
try:
self.db.execute_query("SELECT 1")
test_results.append("✅ Veritabanı bağlantısı: OK")
except Exception as e:
test_results.append(f"❌ Veritabanı bağlantısı: HATA - {str(e)[:50]}")
# 2. Scraper testi
try:
updates = self.scraper.get_all_updates()
if updates and len(updates.get('news', [])) > 0:
test_results.append("✅ Web scraper: OK")
else:
test_results.append("⚠️ Web scraper: Veri bulunamadı")
except Exception as e:
test_results.append(f"❌ Web scraper: HATA - {str(e)[:50]}")
# 3. Bot komut testi
test_results.append("✅ Bot komutları: OK")
# 4. Kullanıcı kaydı testi
try:
user_id = update.effective_user.id
result = self.db.execute_query("SELECT * FROM users WHERE user_id = %s", (user_id,))
if result:
test_results.append("✅ Kullanıcı kaydı: OK")
else:
test_results.append("⚠️ Kullanıcı kaydı: Bulunamadı")
except Exception as e:
test_results.append(f"❌ Kullanıcı kaydı: HATA")
test_message = f"""
🔧 **SİSTEM TEST SONUÇLARI**
{chr(10).join(test_results)}
📊 **Performans:**
• Response time: < 1 saniye
• Memory usage: Normal
• Error rate: Düşük
🕐 Test tamamlanma zamanı: {datetime.now().strftime('%d.%m.%Y %H:%M:%S')}
Sorun devam ediyorsa /yardim komutunu kullanın.
"""
await update.message.reply_text(test_message, parse_mode=ParseMode.MARKDOWN)
except Exception as e:
self.logger.error(f"Test command hatası: {str(e)}")
await update.message.reply_text("❌ Test işlemi sırasında hata oluştu.")
async def button_callback(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Inline keyboard button callback'i"""
query = update.callback_query
await query.answer()
try:
if query.data == "updates":
await self.bot.updates_command(update, context)
elif query.data == "calendar":
await self.bot.calendar_command(update, context)
elif query.data == "reminder":
await self.reminder_command(update, context)
elif query.data == "help":
await self.bot.help_command(update, context)
elif query.data.startswith("remind_"):
await self.handle_reminder_setting(update, context, query.data)
except Exception as e:
self.logger.error(f"Button callback hatası: {str(e)}")
await query.edit_message_text("❌ İşlem sırasında hata oluştu.")
async def handle_reminder_setting(self, update: Update, context: ContextTypes.DEFAULT_TYPE, callback_data: str):
"""Hatırlatıcı ayarlarını işle"""
query = update.callback_query
user_id = update.effective_user.id
try:
if callback_data == "remind_off":
# Hatırlatıcıyı kapat
self.db.execute_query(
"UPDATE users SET reminder_days = NULL WHERE user_id = %s",
(user_id,)
)
await query.edit_message_text(
"🔕 Hatırlatıcılar kapatıldı.\n\nİstediğiniz zaman /hatirlatici komutu ile tekrar açabilirsiniz."
)
else:
# Hatırlatıcı günü ayarla
days = int(callback_data.split("_")[1])
self.db.execute_query(
"UPDATE users SET reminder_days = %s WHERE user_id = %s",
(days, user_id)
)
await query.edit_message_text(
f"✅ Hatırlatıcı ayarlandı!\n\n"
f"🔔 Vergi yükümlülüklerinizden {days} gün önce hatırlatma alacaksınız.\n\n"
f"Hatırlatıcıları kapatmak için /hatirlatici komutunu kullanın."
)
except Exception as e:
self.logger.error(f"Reminder setting hatası: {str(e)}")
await query.edit_message_text("❌ Hatırlatıcı ayarlanırken hata oluştu.")
async def handle_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Genel mesaj handler'ı"""
try:
message_text = update.message.text.lower()
# Anahtar kelime bazlı otomatik cevaplar
if any(word in message_text for word in ['kdv', 'katma değer vergisi']):
await update.message.reply_text(
"💡 KDV ile ilgili güncel bilgiler için /guncellemeler komutunu kullanabilirsiniz!"
)
elif any(word in message_text for word in ['beyanname', 'vergi beyannamesi']):
await update.message.reply_text(
"📋 Beyanname tarihleri için /takvim komutunu kullanabilirsiniz!"
)
elif any(word in message_text for word in ['hatırlatıcı', 'hatırlatma']):
await update.message.reply_text(
"🔔 Hatırlatıcı ayarları için /hatirlatici komutunu kullanın!"
)
else:
# Genel yardım mesajı
await update.message.reply_text(
"🤖 Merhaba! Vergi ile ilgili yardım için aşağıdaki komutları kullanabilirsiniz:\n\n"
"/guncellemeler - Son vergi haberleri\n"
"/takvim - Vergi tarihleri\n"
"/yardim - Tüm komutlar"
)
except Exception as e:
self.logger.error(f"Message handler hatası: {str(e)}")
async def send_scheduled_reminders(self):
"""Zamanlanmış hatırlatmaları gönder"""
try:
# Aktif hatırlatıcısı olan kullanıcıları getir
users = self.db.execute_query(
"SELECT user_id, chat_id, reminder_days FROM users WHERE is_active = TRUE AND reminder_days IS NOT NULL"
)
if not users:
return
# Vergi takvim verilerini çek
calendar_data = self.scraper.scrape_tax_calendar()
for user in users:
try:
reminder_days = user['reminder_days']
chat_id = user['chat_id']
# Kullanıcının hatırlatma günü içindeki vergi yükümlülüklerini bul
now = datetime.now()
reminder_date = now + timedelta(days=reminder_days)
upcoming_taxes = [
tax for tax in calendar_data
if tax['deadline_date'].date() == reminder_date.date()
]
if upcoming_taxes:
message_parts = [f"🔔 **{reminder_days} GÜN SONRA VERGİ YÜKÜMLÜLÜĞÜNÜZ VAR!**\n"]
for tax in upcoming_taxes:
message_parts.append(f"📋 **{tax['tax_type']}**")
message_parts.append(f"📅 Son tarih: {tax['deadline_date'].strftime('%d.%m.%Y')}")
message_parts.append(f"📝 {tax['description']}\n")
message_parts.append("⚠️ Unutmamak için takvime not alın!")
reminder_message = "\n".join(message_parts)
await self.bot.app.bot.send_message(
chat_id=chat_id,
text=reminder_message,
parse_mode=ParseMode.MARKDOWN
)
self.logger.info(f"Hatırlatma gönderildi: {chat_id}")
except Exception as e:
self.logger.error(f"Kullanıcı hatırlatma hatası {user['user_id']}: {str(e)}")
continue
except Exception as e:
self.logger.error(f"Scheduled reminders hatası: {str(e)}")
# Yardımcı fonksiyonlar
def create_bot_instance(token: str):
"""Bot instance'ı oluşturur"""
from bot import VergiBot
bot = VergiBot(token)
handlers = BotHandlers(bot)
# Handler'ları bot'a ekle
bot.reminder_command = handlers.reminder_command
bot.status_command = handlers.status_command
bot.test_command = handlers.test_command
bot.button_callback = handlers.button_callback
bot.handle_message = handlers.handle_message
bot.send_scheduled_reminders = handlers.send_scheduled_reminders
return bot
if __name__ == "__main__":
print("Bu dosya bot.py tarafından import edilmelidir.")