-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTaskBot.py
More file actions
638 lines (536 loc) · 31.5 KB
/
TaskBot.py
File metadata and controls
638 lines (536 loc) · 31.5 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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
import os
import json
import logging
import asyncio
import ssl
from datetime import datetime, timedelta
import aiohttp
import asyncpg
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup, KeyboardButton
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, CallbackQueryHandler, filters, ContextTypes
# --- КОНФИГУРАЦИЯ ---
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
IMPORTANT_DIR = os.path.join(BASE_DIR, 'important')
CONFIG_PATH = os.path.join(IMPORTANT_DIR, 'config_task.json')
SSL_ROOT_CERT = os.path.join(IMPORTANT_DIR, 'root.crt')
USER_MAP_PATH = os.path.join(IMPORTANT_DIR, 'user_map.json')
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger("TaskBot_v1.7.0_BoolFlag")
try:
with open(CONFIG_PATH, 'r', encoding='utf-8') as f:
config = json.load(f)
except FileNotFoundError:
exit(f"CRITICAL: Config not found at {CONFIG_PATH}")
BOT_TOKEN = config.get("BOT_TOKEN")
DB_CONFIG = config.get("DATABASE")
YGPT = config.get("YANDEX_GPT", {})
YSK = config.get("YANDEX_SPEECHKIT", {}) # Настройки SpeechKit
ADMIN_ID = config.get("ADMIN_ID")
user_pools = {}
user_db_map = {}
# --- ВСПОМОГАТЕЛЬНЫЕ ФУНКЦИИ ВРЕМЕНИ ---
async def get_user_offset(user_id):
pool = user_pools.get(user_id)
if not pool: return None # Return None if not found/error
async with pool.acquire() as conn:
try:
row = await conn.fetchrow("SELECT timezone_offset FROM user_settings WHERE user_id = $1", user_id)
return row['timezone_offset'] if row else None
except: return None
async def get_user_now(user_id):
offset = await get_user_offset(user_id)
if offset is None: offset = 3 # Default to Moscow if not set for calculation
return datetime.utcnow() + timedelta(hours=offset)
async def get_next_monday(user_id):
now = await get_user_now(user_id)
days_ahead = 7 - now.weekday()
if days_ahead <= 0: days_ahead += 7
return (now + timedelta(days=days_ahead)).replace(hour=9, minute=0, second=0, microsecond=0)
# --- БАЗА ДАННЫХ И ПЛАНИРОВЩИК ---
def load_user_map():
global user_db_map
if os.path.exists(USER_MAP_PATH):
try:
with open(USER_MAP_PATH, 'r') as f:
user_db_map = {int(k): v for k, v in json.load(f).items()}
except Exception as e:
logger.error(f"Error loading user map: {e}")
def save_user_map():
try:
with open(USER_MAP_PATH, 'w') as f:
json.dump(user_db_map, f)
except Exception as e:
logger.error(f"Error saving user map: {e}")
async def init_db(app):
load_user_map()
databases = config.get("DATABASES", {})
# Обратная совместимость: если нет DATABASES, но есть DATABASE
if not databases and DB_CONFIG:
if ADMIN_ID:
databases[str(ADMIN_ID)] = DB_CONFIG
# Если админа нет в карте, добавляем
if ADMIN_ID not in user_db_map:
user_db_map[ADMIN_ID] = str(ADMIN_ID)
save_user_map()
# Инициализация пулов для известных пользователей
for user_id, db_key in user_db_map.items():
if str(db_key) in databases:
await create_user_pool(user_id, databases[str(db_key)])
elif DB_CONFIG:
await create_user_pool(user_id, DB_CONFIG)
# Инициализация для ключей, которые являются ID (если вдруг прописаны вручную в конфиге)
for key, db_conf in databases.items():
if key.isdigit() and int(key) not in user_pools:
await create_user_pool(int(key), db_conf)
user_db_map[int(key)] = key
asyncio.create_task(reminder_scheduler(app))
asyncio.create_task(cleanup_scheduler(app))
async def create_user_pool(user_id, db_conf):
try:
dsn = f"postgresql://{db_conf['USER']}:{db_conf['PASSWORD']}@{db_conf['HOST']}:{db_conf['PORT']}/{db_conf['DB_NAME']}"
ssl_ctx = ssl.create_default_context(cafile=SSL_ROOT_CERT)
ssl_ctx.check_hostname = False
ssl_ctx.verify_mode = ssl.CERT_REQUIRED
pool = await asyncpg.create_pool(dsn, ssl=ssl_ctx)
user_pools[user_id] = pool
await ensure_tables(pool)
logger.info(f"✅ Pool created for user {user_id}")
except Exception as e:
logger.error(f"❌ Failed to create pool for {user_id}: {e}")
async def ensure_tables(pool):
sql_create = """
CREATE TABLE IF NOT EXISTS tasks (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL,
username TEXT,
sender_info TEXT,
original_text TEXT,
task_title TEXT,
task_description TEXT,
is_completed BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT NOW(),
remind_at TIMESTAMP WITHOUT TIME ZONE,
reminder_sent BOOLEAN DEFAULT FALSE,
repeat_days INTEGER
);
CREATE TABLE IF NOT EXISTS user_settings (
user_id BIGINT PRIMARY KEY,
timezone_offset INTEGER DEFAULT 3
);
CREATE INDEX IF NOT EXISTS idx_tasks_remind_scheduler
ON tasks (remind_at, is_completed, reminder_sent);
"""
async with pool.acquire() as conn:
await conn.execute(sql_create)
async def reminder_scheduler(app):
logger.info("⏰ Планировщик запущен.")
while True:
for user_id, pool in user_pools.items():
try:
async with pool.acquire() as conn:
now_utc = datetime.utcnow()
# ИЗМЕНЕНИЕ: Добавлено условие AND reminder_sent = FALSE
reminders = await conn.fetch(
"SELECT * FROM tasks WHERE user_id = $1 AND is_completed = FALSE AND remind_at IS NOT NULL AND remind_at <= $2 AND reminder_sent = FALSE",
user_id, now_utc
)
for r in reminders:
try:
text = f"🔔 *НАПОМИНАНИЕ*\n\n📌 {r['task_title']}\n\n{r['task_description']}"
await app.bot.send_message(chat_id=r['user_id'], text=text, parse_mode="Markdown")
if r['repeat_days']:
# Повторяющаяся задача: ставим новую дату И сбрасываем флаг отправки в FALSE
new_date = now_utc + timedelta(days=r['repeat_days'])
await conn.execute("UPDATE tasks SET remind_at = $1, reminder_sent = FALSE WHERE id = $2", new_date, r['id'])
else:
# Одноразовая: дату НЕ стираем (чтобы видеть в истории), но ставим флаг TRUE
await conn.execute("UPDATE tasks SET reminder_sent = TRUE WHERE id = $1", r['id'])
logger.info(f"✅ Уведомление отправлено для #{r['id']}")
except Exception as e:
logger.error(f"Ошибка отправки напоминания {r['id']}: {e}")
except Exception as e:
logger.error(f"Scheduler Error for user {user_id}: {e}")
await asyncio.sleep(30)
async def cleanup_scheduler(app):
logger.info("🧹 Scheduler cleanup initialized. Running every 5 days at midnight UTC.")
while True:
try:
now = datetime.utcnow()
# "В полночь пятого дня" -> Check if day is divisible by 5 (5, 10, 15, 20, 25, 30) AND it's midnight
if now.day % 5 == 0 and now.hour == 0 and now.minute == 0:
logger.info("🧹 Starting auto-cleanup of completed tasks...")
count_deleted = 0
# Use list() to avoid "dictionary changed size during iteration" error
for user_id, pool in list(user_pools.items()):
try:
async with pool.acquire() as conn:
# Удаляем все задачи со статусом is_completed = TRUE
result = await conn.execute("DELETE FROM tasks WHERE is_completed = TRUE")
# result is usually "DELETE <count>"
if result:
try:
cnt = int(result.split()[-1])
count_deleted += cnt
except: pass
except Exception as e:
logger.error(f"Cleanup error for user {user_id}: {e}")
if count_deleted > 0:
logger.info(f"✅ Cleanup finished. Deleted {count_deleted} completed tasks total.")
else:
logger.info("✅ Cleanup finished. No completed tasks found to delete.")
# Wait 70 seconds to ensure we don't run again in the same minute
await asyncio.sleep(70)
else:
# Check every minute
await asyncio.sleep(60)
except Exception as e:
logger.error(f"Critical error in cleanup_scheduler: {e}")
await asyncio.sleep(60)
# --- ЛОГИКА КНОПОК ---
async def get_tasks_keyboard(user_id, mode="todo", page=0):
pool = user_pools.get(user_id)
if not pool: return None
async with pool.acquire() as conn:
if mode == "done":
query = "SELECT * FROM tasks WHERE user_id = $2 AND is_completed = TRUE ORDER BY created_at DESC LIMIT 10 OFFSET $1"
elif mode == "remind":
# Показываем задачи, где есть установленная дата напоминания
query = "SELECT * FROM tasks WHERE user_id = $2 AND remind_at IS NOT NULL AND is_completed = FALSE ORDER BY remind_at ASC LIMIT 10 OFFSET $1"
else:
# Обычный список - те, где нет напоминания ИЛИ оно уже прошло и отмечено как отправленное (чтобы не висели в топе, если это не отдельный список)
# Но по твоей логике "remind_at IS NULL" означало обычную задачу.
# Если мы теперь оставляем дату, но ставим флаг, то сюда попадут только те, у кого remind_at вообще нет.
query = "SELECT * FROM tasks WHERE user_id = $2 AND is_completed = FALSE AND remind_at IS NULL ORDER BY created_at DESC LIMIT 10 OFFSET $1"
tasks = await conn.fetch(query, page * 10, user_id)
keyboard = []
for t in tasks:
icon = ""
if t['is_completed']: icon = "✔️ "
elif t['repeat_days']: icon = "🔄 "
elif t['remind_at']: icon = "📢 "
title = (t['task_title'][:37] + "...") if len(t['task_title']) > 40 else t['task_title']
keyboard.append([InlineKeyboardButton(f"{icon}{title}", callback_data=f"view_{t['id']}")])
nav = []
if page > 0: nav.append(InlineKeyboardButton("⬅️", callback_data=f"list_{mode}_{page-1}"))
if len(tasks) == 10: nav.append(InlineKeyboardButton("➡️", callback_data=f"list_{mode}_{page+1}"))
if nav: keyboard.append(nav)
return InlineKeyboardMarkup(keyboard)
async def get_timezone_keyboard():
# Common timezones for RU/CIS
tz_map = [
("UTC-8 (Лос-Анджелес)", -8),
("UTC-6 (Чикаго)", -6),
("UTC-5 (Нью-Йорк, Торонто)", -5),
("UTC-3 (Сан-Паулу)", -3),
("UTC+0 (Лондон, UTC)", 0),
("UTC+1 (Париж, Цюрих, Лагос)", 1),
("UTC+2 (Каир, Йоханнесбург)", 2),
("UTC+3 (Москва, Стамбул)", 3),
("UTC+4 (Дубай)", 4),
]
kb = []
for label, offset in tz_map:
kb.append([InlineKeyboardButton(label, callback_data=f"settz_{offset}")])
return InlineKeyboardMarkup(kb)
# --- AI & SPEECH ---
async def process_text_with_ai(text):
if not YGPT.get("API_KEY"): return text[:50], text
sys_prompt = YGPT.get("SYSTEM_PROMPT", """Ты помощник по управлению задачами. Твоя задача:
1. Прочитай текст задачи
2. Переформулируй её ясно и понятно (убери лишнее, оставь смысл)
3. Сделай краткий заголовок (до 40 символов)
4. Раздели заголовок и описание символами |||
Пример формата:
Купить продукты|||Купить в магазине: молоко, хлеб, яйца. Сметана обязательна. Бюджет ~500р.
Будь конкретен и практичен.""")
headers = {"Authorization": f"Api-Key {YGPT['API_KEY']}"}
body = {
"modelUri": YGPT["MODEL_URI"],
"completionOptions": {"temperature": 0.3},
"messages": [
{"role": "system", "text": sys_prompt},
{"role": "user", "text": text}
]
}
try:
async with aiohttp.ClientSession() as sess:
async with sess.post("https://llm.api.cloud.yandex.net/foundationModels/v1/completion", headers=headers, json=body) as resp:
res = await resp.json()
raw = res["result"]["alternatives"][0]["message"]["text"]
return (raw.split("|||")[0].strip(), raw.split("|||")[1].strip()) if "|||" in raw else (raw[:50], raw)
except Exception as e:
logger.error(f"GPT Error: {e}")
return "Новая задача", text
async def recognize_speech(audio_data):
if not YSK.get("API_KEY"):
return None
url = "https://stt.api.cloud.yandex.net/speech/v1/stt:recognize"
headers = {"Authorization": f"Api-Key {YSK['API_KEY']}"}
params = {
"topic": "general",
"folderId": YSK["FOLDER_ID"],
"lang": "ru-RU"
}
try:
async with aiohttp.ClientSession() as sess:
async with sess.post(url, headers=headers, params=params, data=audio_data) as resp:
if resp.status != 200:
logger.error(f"SpeechKit Error: {await resp.text()}")
return None
res = await resp.json()
return res.get("result")
except Exception as e:
logger.error(f"SpeechKit Connection Error: {e}")
return None
async def create_new_task(user, text, original_source="text"):
pool = user_pools.get(user.id)
if not pool: return "Ошибка БД"
title, desc = await process_text_with_ai(text)
async with pool.acquire() as conn:
await conn.execute(
"INSERT INTO tasks (user_id, username, sender_info, original_text, task_title, task_description) VALUES ($1,$2,$3,$4,$5,$6)",
user.id, user.username, f"Я сам ({original_source})", text, title, desc
)
return title
# --- ОБРАБОТЧИКИ ---
async def handle_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.callback_query
user_id = query.from_user.id
if user_id not in user_pools:
await query.answer("⚠️ Вы не авторизованы. Нажмите /start", show_alert=True)
return
pool = user_pools[user_id]
data = query.data
await query.answer()
if data.startswith("list_"):
mode, page = data.split("_")[1], int(data.split("_")[2])
kb = await get_tasks_keyboard(user_id, mode, page)
await query.edit_message_text(f"*Список {mode}:*", reply_markup=kb, parse_mode="Markdown")
elif data.startswith("view_"):
task_id = int(data.split("_")[1])
async with pool.acquire() as conn:
t = await conn.fetchrow("SELECT * FROM tasks WHERE id = $1 AND user_id = $2", task_id, user_id)
if not t:
await query.answer("Задача не найдена или доступ запрещен", show_alert=True)
return
rem_txt = ""
if t['remind_at']:
offset = await get_user_offset(user_id)
if offset is None: offset = 3
msk_dt = t['remind_at'] + timedelta(hours=offset)
# Добавим инфо, если напоминание уже сработало
status_icon = "✅ Отправлено" if t.get('reminder_sent') else "⏳ Ожидает"
rem_txt = f"\n⏰ Напомнить: {msk_dt.strftime('%d.%m %H:%M')} ({status_icon})"
rep_txt = f"\n🔁 Повтор: каждые {t['repeat_days']} дн." if t['repeat_days'] else ""
kb = []
if not t['is_completed']:
kb.append([InlineKeyboardButton("✔️ Завершить", callback_data=f"status_{task_id}_true")])
kb.append([InlineKeyboardButton("⏰ Уст. напоминание", callback_data=f"remmenu_{task_id}")])
kb.append([InlineKeyboardButton("🔄 Повторять (дни)", callback_data=f"setrep_{task_id}")])
else:
kb.append([InlineKeyboardButton("🔄 Восстановить", callback_data=f"status_{task_id}_false")])
back_mode = "done" if t['is_completed'] else ("remind" if t['remind_at'] else "todo")
kb.append([InlineKeyboardButton("📂 К списку", callback_data=f"list_{back_mode}_0")])
await query.edit_message_text(f"📍 *{t['task_title']}*\n{rem_txt}{rep_txt}\n---\n{t['task_description']}",
reply_markup=InlineKeyboardMarkup(kb), parse_mode="Markdown")
elif data.startswith("status_"):
tid, stat = int(data.split("_")[1]), data.split("_")[2] == "true"
async with pool.acquire() as conn:
await conn.execute("UPDATE tasks SET is_completed = $1 WHERE id = $2 AND user_id = $3", stat, tid, user_id)
msg = "🎉 Задача завершена!" if stat else "🔄 Задача восстановлена в общий список"
await query.edit_message_text(msg)
kb = await get_tasks_keyboard(user_id, "todo", 0)
await query.message.reply_text("Обновленный список:", reply_markup=kb)
elif data.startswith("remmenu_"):
# Check if TZ is set
offset = await get_user_offset(user_id)
tid = data.split("_")[1]
if offset is None:
# TZ not set, force user to set it first
context.user_data['pending_rem_tid'] = tid
kb = await get_timezone_keyboard()
await query.edit_message_text("🌏 Для установки напоминаний укажите ваш часовой пояс:", reply_markup=kb)
return
kb = [
[InlineKeyboardButton("Через 1 час", callback_data=f"rempreset_{tid}_1h")],
[InlineKeyboardButton("Через 2 часа", callback_data=f"rempreset_{tid}_2h")],
[InlineKeyboardButton("Вечером (20:00)", callback_data=f"rempreset_{tid}_eve")],
[InlineKeyboardButton("Завтра 09:00", callback_data=f"rempreset_{tid}_tom")],
[InlineKeyboardButton("Пн 09:00", callback_data=f"rempreset_{tid}_mon")],
[InlineKeyboardButton("⌨️ Ввести вручную", callback_data=f"setrem_{tid}")]
]
await query.edit_message_text("Выберите время:", reply_markup=InlineKeyboardMarkup(kb))
elif data.startswith("rempreset_"):
parts = data.split("_")
tid = int(parts[1])
ptype = parts[2]
now_msk = await get_user_now(user_id)
if ptype == "1h": target_msk = now_msk + timedelta(hours=1)
elif ptype == "tom": target_msk = (now_msk + timedelta(days=1)).replace(hour=9, minute=0, second=0, microsecond=0)
elif ptype == "mon": target_msk = await get_next_monday(user_id)
else: return
offset = await get_user_offset(user_id)
if offset is None: offset = 3
target_utc = target_msk - timedelta(hours=offset)
async with pool.acquire() as conn:
# ИЗМЕНЕНИЕ: При установке нового времени сбрасываем флаг отправки
await conn.execute("UPDATE tasks SET remind_at = $1, reminder_sent = FALSE WHERE id = $2 AND user_id = $3", target_utc, tid, user_id)
await query.edit_message_text(f"✅ Установлено на {target_msk.strftime('%d.%m %H:%M')}")
elif data.startswith("setrem_"):
context.user_data['awaiting_rem'] = data.split("_")[1]
await query.message.reply_text("Введите время: `ДД.ММ.ГГГГ ЧЧ:ММ` (напр. 09.02.2026 15:30)")
elif data.startswith("setrep_"):
context.user_data['awaiting_rep'] = data.split("_")[1]
await query.message.reply_text("Введите интервал повтора (в днях):")
elif data.startswith("settz_"):
offset = int(data.split("_")[1])
async with pool.acquire() as conn:
await conn.execute("INSERT INTO user_settings (user_id, timezone_offset) VALUES ($1, $2) ON CONFLICT (user_id) DO UPDATE SET timezone_offset = EXCLUDED.timezone_offset", user_id, offset)
await query.answer(f"✅ Установлен часовой пояс UTC{'+' if offset>=0 else ''}{offset}")
# Check if we were pending a reminder setting
if 'pending_rem_tid' in context.user_data:
tid = context.user_data.pop('pending_rem_tid')
# Redirect back to remmenu
# We can't easily recurse into handle_callback since we need to fake the data
# So just dup the logic or instruct user
kb = [
[InlineKeyboardButton("Через 1 час", callback_data=f"rempreset_{tid}_1h")],
[InlineKeyboardButton("Через 2 часа", callback_data=f"rempreset_{tid}_2h")],
[InlineKeyboardButton("Вечером (20:00)", callback_data=f"rempreset_{tid}_eve")],
[InlineKeyboardButton("Завтра 09:00", callback_data=f"rempreset_{tid}_tom")],
[InlineKeyboardButton("Пн 09:00", callback_data=f"rempreset_{tid}_mon")],
[InlineKeyboardButton("⌨️ Ввести вручную", callback_data=f"setrem_{tid}")]
]
await query.edit_message_text("✅ Часовой пояс сохранен!\nТеперь выберите время напоминания:", reply_markup=InlineKeyboardMarkup(kb))
else:
await query.edit_message_text(f"✅ Ваш часовой пояс: UTC{'+' if offset>=0 else ''}{offset}.\nТеперь время будет отображаться корректно.")
async def handle_text(update: Update, context: ContextTypes.DEFAULT_TYPE):
user = update.message.from_user
if user.id not in user_pools:
await update.message.reply_text("⚠️ Вы не авторизованы. Нажмите /start")
return
pool = user_pools[user.id]
val = update.message.text
if context.user_data.get('awaiting_timezone'):
if val.lower() == 'отмена':
context.user_data.pop('awaiting_timezone')
await update.message.reply_text("Отменено.")
return
try:
new_offset = int(val)
if -12 <= new_offset <= 14:
async with pool.acquire() as conn:
await conn.execute("INSERT INTO user_settings (user_id, timezone_offset) VALUES ($1, $2) ON CONFLICT (user_id) DO UPDATE SET timezone_offset = EXCLUDED.timezone_offset", user.id, new_offset)
context.user_data.pop('awaiting_timezone')
await update.message.reply_text(f"✅ Часовой пояс изменен на UTC{'+' if new_offset>=0 else ''}{new_offset}")
else:
await update.message.reply_text("❌ Введите число от -12 до 14.")
except ValueError:
await update.message.reply_text("❌ Пожалуйста, введите целое число.")
return
if 'awaiting_rem' in context.user_data:
tid = int(context.user_data.pop('awaiting_rem'))
try:
user_dt = datetime.strptime(val, "%d.%m.%Y %H:%M")
offset = await get_user_offset(user.id)
if offset is None: offset = 3
utc_dt = user_dt - timedelta(hours=offset)
async with pool.acquire() as conn:
# ИЗМЕНЕНИЕ: При ручной установке тоже сбрасываем флаг
await conn.execute("UPDATE tasks SET remind_at = $1, reminder_sent = FALSE WHERE id = $2 AND user_id = $3", utc_dt, tid, user.id)
await update.message.reply_text(f"✅ Напоминание сохранено: {val}")
except: await update.message.reply_text("❌ Ошибка формата. Пример: 09.02.2026 15:30")
return
if 'awaiting_rep' in context.user_data:
tid = int(context.user_data.pop('awaiting_rep'))
if val.isdigit() and 1 <= int(val) <= 365:
async with pool.acquire() as conn:
await conn.execute("UPDATE tasks SET repeat_days = $1 WHERE id = $2 AND user_id = $3", int(val), tid, user.id)
await update.message.reply_text(f"🔄 Повтор настроен: каждые {val} дн.")
else: await update.message.reply_text("❌ Введите число от 1 до 365.")
return
# Главное меню
if val == "Не выполненные":
await update.message.reply_text("📝 Текущие задачи:", reply_markup=await get_tasks_keyboard(user.id, "todo"))
elif val == "Выполненные":
await update.message.reply_text("✅ Архив выполненных:", reply_markup=await get_tasks_keyboard(user.id, "done"))
elif val == "Напоминания":
await update.message.reply_text("📢 Список активных напоминаний:", reply_markup=await get_tasks_keyboard(user.id, "remind"))
else:
status = await update.message.reply_text("🧠 Анализирую задачу...")
title = await create_new_task(user, val, "text")
await status.edit_text(f"✅ Сохранено: {title}")
async def handle_voice(update: Update, context: ContextTypes.DEFAULT_TYPE):
user = update.message.from_user
if user.id not in user_pools:
await update.message.reply_text("⚠️ Вы не авторизованы. Нажмите /start")
return
status = await update.message.reply_text("🎤 Слушаю и расшифровываю...")
try:
file = await context.bot.get_file(update.message.voice.file_id)
file_bytes = await file.download_as_bytearray()
text = await recognize_speech(file_bytes)
if not text:
await status.edit_text("❌ Не удалось распознать речь или пустой ответ.")
return
await status.edit_text(f"🗣 Распознано: \"{text}\"\n🧠 Обрабатываю AI...")
title = await create_new_task(user, text, "voice")
await status.edit_text(f"✅ Сохранено (Voice): {title}")
except Exception as e:
logger.error(f"Voice Handle Error: {e}")
await status.edit_text("❌ Произошла ошибка при обработке голосового.")
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
user = update.effective_user
main_kb = ReplyKeyboardMarkup([["Не выполненные", "Выполненные", "Напоминания"]], resize_keyboard=True)
if user.id in user_pools:
offset = await get_user_offset(user.id)
if offset is None:
kb = await get_timezone_keyboard()
await update.message.reply_text("🚀 TaskBot готов к работе!\n\n🌏 Пожалуйста, выберите ваш часовой пояс для корректной работы напоминаний:", reply_markup=kb)
else:
await update.message.reply_text("🚀 TaskBot готов к работе!", reply_markup=main_kb)
else:
kb = ReplyKeyboardMarkup([[KeyboardButton("📱 Отправить номер телефона", request_contact=True)]], resize_keyboard=True, one_time_keyboard=True)
await update.message.reply_text("Привет! Для доступа к вашей базе данных мне нужно знать ваш номер телефона.", reply_markup=kb)
async def handle_contact(update: Update, context: ContextTypes.DEFAULT_TYPE):
user = update.effective_user
contact = update.message.contact
if contact.user_id != user.id:
await update.message.reply_text("Пожалуйста, отправьте СВОЙ контакт.")
return
phone = contact.phone_number.replace('+', '')
databases = config.get("DATABASES", {})
if phone in databases or DB_CONFIG:
user_db_map[user.id] = phone
save_user_map()
db_conf = databases.get(phone, DB_CONFIG)
await create_user_pool(user.id, db_conf)
main_kb = ReplyKeyboardMarkup([["Не выполненные", "Выполненные", "Напоминания"]], resize_keyboard=True)
await update.message.reply_text("✅ Доступ разрешен! База данных подключена.", reply_markup=main_kb)
else:
await update.message.reply_text("❌ Ваш номер не найден в списке разрешенных и нет общей базы данных.")
def main():
app = ApplicationBuilder().token(BOT_TOKEN).post_init(init_db).build()
app.add_handler(CommandHandler("start", start_command))
async def timezone_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
user = update.effective_user
if user.id not in user_pools:
await update.message.reply_text("⚠️ Вы не авторизованы.")
return
await update.message.reply_text("⚠️ Вы не авторизованы.")
return
offset = await get_user_offset(user.id)
if offset is None:
kb = await get_timezone_keyboard()
await update.message.reply_text("🌏 У вас не установлен часовой пояс. Выберите из списка:", reply_markup=kb)
else:
kb = await get_timezone_keyboard()
await update.message.reply_text(f"Ваш текущий часовой пояс: UTC{'+' if offset>=0 else ''}{offset}.\nВыберите новый из списка или нажмите 'Отмена' (просто проигнорируйте):", reply_markup=kb)
app.add_handler(CommandHandler("timezone", timezone_command))
app.add_handler(MessageHandler(filters.CONTACT, handle_contact))
app.add_handler(CallbackQueryHandler(handle_callback))
app.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), handle_text))
app.add_handler(MessageHandler(filters.VOICE, handle_voice))
app.run_polling()
if __name__ == "__main__":
main()