Files
trilium-bot/main.py
2025-12-12 10:56:51 +03:00

188 lines
7.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import os
from datetime import datetime
from dotenv import load_dotenv
from aiogram import Bot, Dispatcher
from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ParseMode
from aiogram.filters import CommandStart
from aiogram.types import Message
from trilium_py.client import ETAPI
load_dotenv()
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
TRILIUM_URL = os.getenv("TRILIUM_URL")
TRILIUM_TOKEN = os.getenv("TRILIUM_TOKEN")
INBOX_NOTE_ID = os.getenv("INBOX_NOTE_ID")
DAILY_NOTE_ID = os.getenv("DAILY_NOTE_ID") # ID папки для ежедневных заметок
# создаем Trilium API клиент
ea = ETAPI(server_url=TRILIUM_URL, token=TRILIUM_TOKEN)
bot = Bot(token=TELEGRAM_TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML))
dp = Dispatcher()
@dp.message(CommandStart())
async def start(msg: Message):
await msg.answer("Отправь мне текст — я создам заметку в Trilium.")
@dp.message()
async def handler(msg: Message):
text = msg.text.strip()
# Проверяем флаг /daily
is_daily = text.startswith("/daily")
if is_daily:
# Удаляем флаг из текста
text = text[6:].strip() # удаляем "/daily"
# разделяем на заголовок и тело
lines = text.split("\n", 1)
title = lines[0][:100] # заголовок = первая строка
content = lines[1] if len(lines) > 1 else "" # остальное — тело заметки
if is_daily:
# Работаем с ежедневной заметкой
today = datetime.now()
month_name = (
today.strftime("%m - %B")
.replace("January", "Январь")
.replace("February", "Февраль")
.replace("March", "Март")
.replace("April", "Апрель")
.replace("May", "Май")
.replace("June", "Июнь")
.replace("July", "Июль")
.replace("August", "Август")
.replace("September", "Сентябрь")
.replace("October", "Октябрь")
.replace("November", "Ноябрь")
.replace("December", "Декабрь")
)
day_name = (
today.strftime("%d - %A")
.replace("Monday", "Понедельник")
.replace("Tuesday", "Вторник")
.replace("Wednesday", "Среда")
.replace("Thursday", "Четверг")
.replace("Friday", "Пятница")
.replace("Saturday", "Суббота")
.replace("Sunday", "Воскресенье")
)
today_date = today.strftime("%Y-%m-%d")
try:
# Получаем папку с ежедневными заметками
daily_root = ea.get_note(DAILY_NOTE_ID)
month_folder = None
# Вспомогательная функция для получения ID
def get_id(obj):
if isinstance(obj, dict):
return obj.get("noteId") or obj.get("id")
return obj.noteId if hasattr(obj, "noteId") else obj.id
# Ищем папку месяца
if hasattr(daily_root, "children"):
for child in daily_root.children:
child_title = (
child.get("title") if isinstance(child, dict) else child.title
)
if month_name in child_title:
month_folder = child
break
if not month_folder:
# Создаём папку месяца, если её нет
month_folder = ea.create_note(
parentNoteId=DAILY_NOTE_ID, title=month_name, type="text"
)
month_id = get_id(month_folder)
# Ищем папку дня внутри месячной папки
day_folder = None
month_folder_refresh = ea.get_note(month_id)
if hasattr(month_folder_refresh, "children"):
for child in month_folder_refresh.children:
child_title = (
child.get("title") if isinstance(child, dict) else child.title
)
if day_name in child_title:
day_folder = child
break
if not day_folder:
# Создаём папку дня, если её нет
day_folder = ea.create_note(
parentNoteId=month_id, title=day_name, type="text"
)
day_id = get_id(day_folder)
# Ищем заметку с сегодняшней датой
existing_note = None
day_folder_refresh = ea.get_note(day_id)
if hasattr(day_folder_refresh, "children"):
for child in day_folder_refresh.children:
child_title = (
child.get("title") if isinstance(child, dict) else child.title
)
if child_title == today_date:
existing_note = child
break
if existing_note:
# Дописываем в существующую заметку
existing_content = (
existing_note.get("content")
if isinstance(existing_note, dict)
else existing_note.content
)
new_content = (
existing_content + "\n\n---\n" + content
if existing_content
else content
)
existing_id = get_id(existing_note)
ea.update_note(noteId=existing_id, content=new_content)
await msg.answer(f"Добавлено в ежедневную заметку за {today_date}.")
else:
# Создаём новую заметку на сегодня
try:
ea.create_note(
parentNoteId=day_id,
title=today_date,
content=content,
type="text",
)
await msg.answer(f"Создана ежедневная заметка за {today_date}.")
except Exception as create_err:
await msg.answer(f"Ошибка при создании заметки: {str(create_err)}")
except Exception as e:
await msg.answer(f"Ошибка при работе с ежедневной заметкой: {str(e)}")
else:
# Обычное сохранение в Inbox
try:
ea.create_note(
parentNoteId=INBOX_NOTE_ID, title=title, content=content, type="text"
)
await msg.answer("Заметка сохранена в Trilium.")
except Exception as e:
await msg.answer(f"Ошибка при сохранении в Inbox: {str(e)}")
async def main():
await dp.start_polling(bot)
if __name__ == "__main__":
import asyncio
asyncio.run(main())