Giter Site home page Giter Site logo

tg2obsidian's Introduction

tg2obsidian

This program ("Bot") uses Telegram's free bot functionality in order to save messages from a Telegram group to the Obsidian vault on your local computer.

The Markdown markup used will also work for most other programs that work with local Markdown files.

The Bot is designed to run locally on the computer where the Obsidian files are located.

This readme is also available in Russian.

Use case

  • You type, record, or forward messages to your personal Telegram group on the go
  • Bot receives new messages from Telegram and saves them as Inbox notes in your PKM vault
  • Afterwards, in a quiet environment, you process those notes, moving the information from them to appropriate places in your vault

Features

  • All messages are grouped by date — one note per day — or stored in a single note.
  • Each message in a note has a header with a date and time stamp.
  • Formatting of messages and captions is preserved or ignored depending on settings.
  • For forwarded messages, information about the origin is added.
  • Photos, animations, videos, and documents are saved to the vault and embedded in the note.
  • For contacts, YAML front matter and vcard are saved.
  • For locations, relevant links to Google and Yandex maps are created.
  • It is possible to convert notes with certain keywords into a task.
  • It is possible to tag notes with certain keywords.
  • It is possible to recognize speech from voice notes and audio messages. In this case, the Bot sends the recognized text as a response to the original message.

Set up

  1. Install Python 3.10+
  2. install script dependencies:
pip install aiogram
pip install beautifulsoup4
pip install lxml
  1. Install Whisper and Pytorch modules if you need voice messages get recognized to text:
pip install -U openai-whisper
pip install torch
  1. Install compiled FFMPEG and add the path to the executable (in Windows — ffmpeg.exe) to the path environment variable. Go to the folder containing this script and make sure that ffmpeg.exe could be started there.
  2. Create your own bot using https://t.me/BotFather
  3. Paste the token received from @botfather into the appropriate parameter in config.py and change the rest of the parameters in config.py as desired.
  4. (Optional) Add the bot created above to a private Telegram group and make it administrator so it can read messages.

Usage

  1. Send or forward messages that should go to your Obsidian vault to the private Telegram group or directly to your Telegram bot.

  2. Run Bot:

python tg2obsidian_bot.py
  • You can keep Bot running indefinitely on a computer or server that is permanently turned on. In this case, it will recognize speech and create/update notes in Obsidian in real time.
  • If you only turn your computer on when you're using it, run Bot directly when you need to get Obsidian messages, and close the program when you've received all the messages.

Important! Bot can only retrieve messages for the last 24 hours. Messages sent earlier and not retrieved in a timely manner will not be received by Bot and saved in the vault.

Known issues

Check in the Issues section.

Support author

If you would like to thank the author of this project, your donations will be gratefully accepted here: https://pay.cloudtips.ru/p/1f9bf82f

tg2obsidian's People

Contributors

dimonier avatar pkb avatar mikkovedru avatar

Stargazers

cσgscídєs avatar  avatar Alexander avatar Pavel V. Sysolyatin avatar Aleksandr Panov avatar Dmitry Medvedev avatar  avatar  avatar Karataev Oleg avatar  avatar  avatar  avatar  avatar Sergey Zuev avatar 秋无 avatar  avatar  avatar MisterCron avatar Dmitry avatar  avatar Fedor Kapustin avatar  avatar  avatar  avatar Ruslan Rakhimov avatar Dmitry Kulikov avatar  avatar Darya avatar zotona avatar Dmitriy Shushlebin avatar  avatar Иван Могиш avatar Alexander avatar Aleksey Solokha avatar  avatar Egor Sychev avatar  avatar Jan avatar  avatar Peter Hanzo avatar Владимир Шлеев avatar IRomanichenko avatar Andrei avatar Unknown avatar Баташов Станислав avatar Mikhail Lashkin avatar Light Templar avatar artichoke avatar Pavel V avatar  avatar Debra avatar Roman Deev avatar  avatar Alexander avatar Easton avatar Georgy Cheremovsky avatar Mike avatar Andrey Stepanov avatar  avatar Egor Lynko avatar  avatar Kyu Hyeon Kim avatar Mikhail Loginov avatar Carlos Granier avatar  avatar  avatar Jesús López de Leyva avatar  avatar Pavel Abramov avatar Lucas Kohorst avatar a13ph avatar Alex avatar Vladislav Dolbilov avatar  avatar Zhymabek Roman avatar  avatar  avatar Nikita Petrov avatar  avatar Naveen Johnson avatar Sergey Nikitin avatar  avatar Askin avatar Boris Sinitsyn avatar dwl avatar  avatar Sergei Korolev avatar Ilya V Shirinkin avatar  avatar

Watchers

 avatar Alex avatar Peter Hanzo avatar  avatar artichoke avatar  avatar

tg2obsidian's Issues

Проблемы с AIOgram

Пытаюсь развернуть бота у себя.
Столкнулся с тем, что aiogram обновил версию (с 2 на 3 - и предпринял ряд изменений), и теперь tg2obsidian_bot.py жалуется:
C:(путь)\tg2obsidian-main>python tg2obsidian_bot.py
Traceback (most recent call last):
File "C:(путь)\tg2obsidian-main\tg2obsidian_bot.py", line 18, in
from aiogram.dispatcher.filters.builtin import CommandStart, CommandHelp
ModuleNotFoundError: No module named 'aiogram.dispatcher.filters'

Есть ли у вас в планах обновление бота под актуальную версию aiogram?

После распознавания гс бот занимает 3гб оперативки в фоне.

Все было хорошо до установки PyTorch, хотел чтобы использовалась видеокарта, но появился такой неприятный момент. Планировал держать бота включенным в фоне, но если он будет постоянно занимать столько оперативки будет не приятно. Пока поставил распознование принудительно на процессоре.
image

feature request: Telegram + Obsidian = Трекер привычек

Одна из функций для чего я использую обсидиан - я трекаю привычки.
В самом обсидиане это реализовано достаточно топорно, а с помощью тг-бота это можно организовать вообще очень красиво и удобно.

На сколько я помню в Python в библиотеке Aiogram есть обработчик команд вида /command_name.
Идея заключается в том, чтобы добавить функцию примерно такого вида:

Обработчик команд ждёт команду (/command_name)
Затем по определённому пути "ПУТЬ К ЗАМЕТКЕ"
Пишет определённый текст: "ТЕКСТ ЗАМЕТКИ"

А в конфиге прописываются связки КОМАНДА + ПУТЬ + ТЕКСТ, например:
"/read" + "C:\Obsidian\Чтение.md" + "- [x] Читал один час [completion:: 2023-01-11]"

И если в дальнейшем прислать в бота команду /read, то в соответствующую заметку бот добавит соответствующую строчку.

В дальнейшем с помощью плагина Dataview можно будет обрабатывать выполненные задачи и считать сколькь раз в неделю я занимался какой-либо привычкой.

При чём в конфиге желательно сделать так, чтобы можно было добавить хоть 100 связок КОМАНДА + ПУТЬ + ТЕКСТ, а обработчик будет сопоставлять эти связки и писать в нужные заметки нужный текст в зависимости от команды

feature request: Добавить параметр в конфиг "Не хранить логи" или "Срок хранения логов"

Мой опыт говорит о том, что неконтролируемые логи - это плохая практика.
Они потом разрастаются до неимоверных размеров, утекают куда не нужно и т.д.

Предлагаю в конфиге сделать параметр, который позволит включать или выключать логирование.

На крайний случай можно сделать параметр, которым можно задавать срок жизни логов в днях.
Например если выставить параметр равным 1 день, то каждый день некая процедура будет проверять логи и все файлы старше 1 дня будут удаляться.

Кроссплатформенность проекта

Здравствуйте!
Проект очень полезный и явно найдет своего пользователя. Спасибо Вам за работу!

Такой вопрос: планируется ли образ docker и docker-compose?
Чтоб крутить бота не на своей системе windows (хотя я больше использую linux), но можно было крутить и на серверах, vds да и на чем угодно (говоря про докер).
Хотел собрать докер-компос, но завис на зависимостях:
как минимум

kivy-deps.angle
kivy-deps.glew
kivy-deps.sdl2
pywin32
pywin32-ctypes
py-win-keyboard-layout

есть только на вин, поэтому сразу всё отпадает...

Ладно образ, но просто возможность запускать на linux...

после отправки поста, содержащий эмодзи - меняется кодировка документа

Сначала отправляю пару текстовых сообщений (на русском языке). Отображается всё отлично и заносится в документ.
Следует мне переслать пост, содержащий картинку, гиперссылку и эмодзи - кодировка всего документа меняется.
С постами без эмодзи - всё ок.

Вот до отправки поста

скрин

image

После

скрин

image

Пост выглядит следующим образом:
ссылка на пост

скрин

image

Прошу проверить баг с эмозди анимированными и без анимации.

система:
ubuntu 22.04
5.15.0-71-generic
VDS

feature request: Нейминг файлов

Названия картинок когда сохраняются в хранилище имеют название fsdkjfhwkehvjsfk.
Я так понимаю, что подобные названия присваивает телеграм.

Идея в том, чтобы их как-нибудь попытаться упорядочить, например "2023-01-10 - %Название канала% - %Рандомное 2х значое число%".

Таким образом в хранилище обсидиан будет больше порядка, а не куча файлов вида "fsdfkjsdfkjsdlkfjdslf"

Формат ГГГГ-ММ-ДД - выбран не случайно, т.к. все файлы в т.ч. в обсидиане по умолчанию фильтруются по названию и таким образом будет обеспечен еще дополнительный порядок - сверху самые древние файлы, снизу - самые свежие.

Suggestion: save previews/content of external URLs (crawler and logic/template support)

It would really be nice to have this program support saving the previews of external URLs. Either like Telegram is doing:
image
or extend it to be able to crawl (something simple like https://github.com/baranazal/HTML-PAGE-SCRAPER-BOT ) the page and save info from the page according to the logic/template files.

But why?..

In addition to normal Obsidian notes (daily or zettelkasten) I also use Obsidian to keep track of references and sources. Some of them are .pdfs of research, some are links or even files of videos, some are long articles (opinion pieces) and my opinion on them. But a lot of them are simple news articles.

This has been incredibly helpful. I now have a database of actual raw news that I can reference in my normal notes. News are linked together and I can easily search for developments, noticing patterns and inconsistencies/lies. With this system I feel like a superhuman, acting as if I remember everything and can provide the sources to my opinions and point the flip-flopping in an instant.

The only problem is that it just takes a lot of time. Imagine having merely 10 news articles per day worth saving - how much times is spent on manual and tedious work of saving this raw data into my Obsidian. It would be amazing if this could be done automatically with me simply forwarding the news links I view worthy within the Telegram.

Solution

  • having one LOGIC FILE for each URL source. New logic file needs to be created for each new base URL because every website is different and info locates in different places.
  • having one NEWS TEMPLATE FILE per person. Each person either uses the current creates his own basing on several given news template example files.

There is not many sources that I consider reputable enough to be my sources and I suspect creating merely 20-30 logic files (and one template) would be enough to cover the vast majority of my grunt work. Other people could create logic files for other sources, as well as can easily modify the template file to fit their individual needs.

How I invision the solution (to have at some point)

  1. Check if message consists of URL only.
  2. If yes, then check if there is a LOGIC FILE associated with the base URL.
  3. If yes, then crawl the page and send it fully to the specific URL's logic file.
  4. The logic file processes the content of the page and returns the content in parts (date, title, short content/description, full content)
  5. All the returned info is then used according to the NEWS TEMPLATE FILE to create a new file.
  6. PROFIT. The most tedious work is done and if I want, I can go and manually process the news note further: add some tags, write my own opinion about this news, link the news to other news, and make some names clickable/active.

The features needed

  • Template (in addition to the support of the mentioned: date, title, short content/description, full content; so that it):
    • Generate YYYYMMDDHHMMSS zettelkasten index number as well as have a restriction of slowing the process enough for there to be at max only one generation each second (in case the program needs to process several messages with URLs).

Discussion

What do you think? I know that this is quite a lot of work. But could we at least start working in this direction?

OCR text recognition from images

We already have voice recognition from audio messages.

It would also be useful to have text in images automatically recognized.

Does anyone know any good free OCR libraries?

feature request: Удалять разрывы строк и переносы

Сейчас если боту прислать сообщение вида:

Привет
Сходи за хлебом
Купи еще сметану 
А еще яйца

То он сохранит всё это в заметку так же с переносами строк.
А хотелось бы иметь возможность например в конфиге проставить параметр "ВсегдаБезПереносов" и в конечном итоге получить текст вот такого вида:
Привет Сходи за хлебом Купи еще сметану А еще яйца

feature request: Telegram + Obsidian = Read Later

По примерно такой же логики отсюда сделать список "Прочитать позже".
В конфиге создаём параметр "ReadLater" = True
Затем параметр "ReadLaterWords" - это массив, в который через запятую пишем сайты с которых ссылки будут складываться в отдельную заметку, например: (vc.ru, habr.ru)
Затем параметр "ReadLaterNote" - это куда будут складываться ссылки
Затем параметр "ReadLaterText" - это то, что будет приписываться к ссылке до, например "- [ ] Прочитать "ССЫЛКА НА ХАБР"

feature request: Не выделять ничего жирным текстом

Сейчас в коде есть вот такая строчка №187
result = f'**Forwarded {forward_info}**\n'

Вот при сохранении заметки из-за этой строчки часть текста выделяется жирным.

Конечно не сложно каждый раз при обновлении бота удалять из этой строчки звёздочки, но чтоб приблизить бота к совершенству можно было бы в конфиге сделать параметр "Выделять жирным Forwarded" и чтобы каждый для себя мог это настроить.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.