Skip to content

Instantly share code, notes, and snippets.

@arminus
Created September 13, 2021 11:01
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arminus/34d28f5cb73940383f1d0068342d6bf5 to your computer and use it in GitHub Desktop.
Save arminus/34d28f5cb73940383f1d0068342d6bf5 to your computer and use it in GitHub Desktop.
Telegram bot to receive messages and store them in a Nextcloud hosted .md file
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=W0613, C0116
# type: ignore[union-attr]
# This program is dedicated to the public domain under the CC0 license.
import logging, os
from datetime import datetime
# pyocclient
import owncloud
# python-telegram-bot
from telegram import Update, KeyboardButton, ReplyKeyboardMarkup, InlineKeyboardButton, InlineKeyboardMarkup, ParseMode
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext, CallbackQueryHandler
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
# change the following variables for local configuration
nc_server = "http://localhost/nextcloud" # change that to the NC URL for the host this script runs on
nc_user = "<nextcloud user>"
nc_password = "<nextcloud user>"
link_file = "Obsidian/0-Incoming/0-SentLinks.md" # change that Obsidian "sent links" file
tmp_dir = "/tmp" # local temp dir
telegram_token = "<telegram token>" # see https://core.telegram.org/bots#6-botfather
def append_to_nc_file(text):
oc = owncloud.Client(nc_server)
oc.login(nc_user,nc_password)
tmp_file = os.path.basename(link_file)
tmp_file = f"{tmp_dir}/{tmp_file}"
oc.get_file(link_file, tmp_file)
if not os.path.isfile(tmp_file) or not os.access(tmp_file, os.W_OK):
return f"Could not load {link_file}"
with open(tmp_file, "a") as f:
f.write(format_text(text))
if not oc.put_file(link_file, tmp_file):
os.remove(tmp_file)
return f"Could not save {link_file}"
os.remove(tmp_file)
return "saved message"
def format_text(text):
now = datetime.now().strftime("%d.%m.%Y")
return f"- {now}: {text}\n"
def text_command(update: Update, context: CallbackContext):
text = update.message.text
logging.info("got '"+text+"'")
result = append_to_nc_file(text)
logger.info(result)
if result != "saved message":
update.message.reply_text(result)
def main():
updater = Updater(telegram_token, use_context=True)
dispatcher = updater.dispatcher
dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, text_command))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment