From 24fa84dfefbc81d9fda8a083ba3f281664a88717 Mon Sep 17 00:00:00 2001 From: James Ravenscroft Date: Tue, 1 Nov 2022 19:59:51 +0000 Subject: [PATCH] implemented conversation and bookmarking --- src/rafael/Untitled-1.ipynb | 126 ++++++++++++++++++++++++++++++++++++ src/rafael/__init__.py | 84 +++++++++++++++++++++--- src/rafael/bookmarks.py | 62 ++++++++++++++---- src/rafael/dailynote.py | 0 4 files changed, 251 insertions(+), 21 deletions(-) create mode 100644 src/rafael/Untitled-1.ipynb create mode 100644 src/rafael/dailynote.py diff --git a/src/rafael/Untitled-1.ipynb b/src/rafael/Untitled-1.ipynb new file mode 100644 index 0000000..fdb7912 --- /dev/null +++ b/src/rafael/Untitled-1.ipynb @@ -0,0 +1,126 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import requests" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "TOKEN_ID=\"CWwz5OlbKwcKe1GP3gTj31LvT90SfJ3u\"\n", + "TOKEN_SECRET=\"dYQDlFaY0BW7nUCXNJaK8tAVSSQEim7K\"" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "session = requests.Session()\n", + "session.headers = {'Authorization': f\"Token {TOKEN_ID}:{TOKEN_SECRET}\"}" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "# Bookmarks\n", + "\n", + "\n", + "\n", + "[example](http://www.google.com)\n" + ] + } + ], + "source": [ + "print(r.json()['markdown'])" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 26, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "r = session.get(\"https://wiki.jamesravey.me/api/pages/58\")\n", + "\n", + "session.put(\"https://wiki.jamesravey.me/api/pages/58\", json={\n", + " \"markdown\": r.json()['markdown'] + \"\\n\\n - [example](http://www.google.com)\"\n", + "})" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3.10.4 ('rafael')", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.4" + }, + "orig_nbformat": 4, + "vscode": { + "interpreter": { + "hash": "6b9c6d1df15e718815a7a88d34bef3dcfbc18a324f553f0104fbca6893bdb354" + } + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/src/rafael/__init__.py b/src/rafael/__init__.py index 9d3c817..aab8e85 100644 --- a/src/rafael/__init__.py +++ b/src/rafael/__init__.py @@ -5,8 +5,9 @@ import requests from flask import Flask -from telegram import Update -from telegram.ext import Updater, MessageHandler, CommandHandler, Filters, CallbackContext + +from telegram import Update, PhotoSize, File, BotCommand +from telegram.ext import Updater, MessageHandler, CommandHandler, Filters, CallbackContext, ConversationHandler app = Flask("rafael") @@ -15,6 +16,63 @@ RAFAEL_UA = "RAFAEL/0.1" from rafael.bookmarks import RafaelBookmarkPlugin +def handle(update: Update, context: CallbackContext): + + print("args:", context.args) + + + print(f"Received a message: {update.message.text}") + update.message.reply_text(f"You said: {update.message.text}") + + print(update.message.to_json()) + + if update.message.document is not None: + print("Document", update.message.document.get_file()) + + elif update.message.effective_attachment: + + for att in update.message.effective_attachment: + + if isinstance(att, PhotoSize): + print(att.get_file()) + else: + print("unknown attachment:", att) + + update.message.reply_text("done m8") + +ADDING = 0 + +class JournalPlugin(): + + def init_convo(self, update: Update, context: CallbackContext): + update.message.reply_text("Add photos for your journal") + return ADDING + + def handle_file(self, update: Update, context: CallbackContext): + update.message.reply_text("Got your update m8") + return ADDING + + def done_handler(self, update: Update, context: CallbackContext): + update.message.reply_text("Great storing your images...") + return ConversationHandler.END + + def invalid_handler(self, update: Update, context: CallbackContext): + update.message.reply_text("Sorry, I don't understand. Please upload photos or type 'Done' to exit") + + def register(self, updater: Updater): + + updater.dispatcher.add_handler(ConversationHandler( + entry_points=[ + CommandHandler("journal", self.init_convo) + ], + states={ + ADDING: [MessageHandler(Filters.attachment, self.handle_file)] + }, + fallbacks=[ + MessageHandler(Filters.regex("^Done$"), self.done_handler), + MessageHandler(Filters.all, self.invalid_handler) + ] + )) class RafaelBot: @@ -23,18 +81,25 @@ class RafaelBot: self.dispatcher = self.updater.dispatcher - bh = RafaelBookmarkPlugin() - bh.register(self.dispatcher) - try: - self.wiki = dokuwiki.DokuWiki(os.getenv('DOKU_URL'), os.getenv('DOKU_USER'), os.getenv('DOKU_PASS'), cookieAuth=True) - except (dokuwiki.DokuWikiError, Exception) as err: - print('unable to connect: %s' % err) + bh = RafaelBookmarkPlugin() + bh.register(self.updater) + + jp = JournalPlugin() + jp.register(self.updater) + + #self.updater.dispatcher.add_handler(CommandHandler("journal", handle)) + #self.updater.dispatcher.add_handler(MessageHandler(Filters.attachment, handle)) + + + + def run(self): self.updater.start_polling() + @app.route("/", methods=['GET']) def index(): return "hello" @@ -42,8 +107,11 @@ def index(): def main(): dotenv.load_dotenv() + print("run bot") bot = RafaelBot() + bot.run() + print("bot run") # app.run() diff --git a/src/rafael/bookmarks.py b/src/rafael/bookmarks.py index 9c1c8ce..242cbad 100644 --- a/src/rafael/bookmarks.py +++ b/src/rafael/bookmarks.py @@ -1,4 +1,5 @@ import time +import traceback import dotenv import os import click @@ -20,16 +21,37 @@ from rafael import RAFAEL_UA class RafaelBookmarkPlugin: def __init__(self): - self.updater = Updater(os.getenv("TELEGRAM_API_KEY")) - try: - self.wiki = dokuwiki.DokuWiki(os.getenv('DOKU_URL'), os.getenv('DOKU_USER'), os.getenv('DOKU_PASS'), cookieAuth=True) - except (dokuwiki.DokuWikiError, Exception) as err: - print('unable to connect: %s' % err) + self.wiki_url = os.getenv('BOOKSTACK_URL') + + TOKEN_ID = os.getenv('BOOKSTACK_TOKEN_ID') + TOKEN_SECRET = os.getenv('BOOKMARK_TOKEN_SECRET') + + self.bookstack_bookmark_id = os.getenv('BOOKSTACK_BOOKMARK_PAGE') + + self.session = requests.Session() + self.session.headers = {'Authorization': f"Token {TOKEN_ID}:{TOKEN_SECRET}"} - def register(self, dispatcher: Dispatcher): - dispatcher.add_handler(MessageHandler(Filters.entity('url'), self.handle_url)) + # try: + # self.wiki = dokuwiki.DokuWiki(os.getenv('DOKU_URL'), os.getenv('DOKU_USER'), os.getenv('DOKU_PASS'), cookieAuth=True) + # except (dokuwiki.DokuWikiError, Exception) as err: + # print('unable to connect: %s' % err) + + + def update_page(self, update_html): + + r = self.session.get(f"{self.wiki_url}/api/pages/{self.bookstack_bookmark_id}") + + print(r.json()) + + return self.session.put(f"{self.wiki_url}/api/pages/{self.bookstack_bookmark_id}", json={ + "markdown": r.json()['markdown'] + f"\n\n - {update_html}" + }) + + + def register(self, updater: Updater): + updater.dispatcher.add_handler(MessageHandler(Filters.entity('url'), self.handle_url)) def get_title(self, url): @@ -49,17 +71,31 @@ class RafaelBookmarkPlugin: url = update.message.text[ent.offset:ent.length] try: title = self.get_title(url) - link = f"[[{url}|{title}]]" + link = f"[{title}]({url})" except Exception as err: update.message.reply_text(f"Failed to retrieve title for page {url}: {err}. Storing url only") link = f"{url}" added_ds = f"(retrieved at: {datetime.now().strftime('%d/%m/%Y, %H:%M:%S')})" - update_body += f" * {link} {added_ds}" + update_body += f" - {link} {added_ds}" + + # + #r = requests.get("") try: - self.wiki.pages.append("bookmarks/inbox", f"\n\n{update_body}") - update.message.reply_text(f"Updated bookmarks page: {os.getenv('DOKU_URL')}bookmarks/inbox") - except (dokuwiki.DokuWikiError) as err: - update.message.reply_text(f"Failed to store url: {err}") \ No newline at end of file + page = self.update_page(update_body) + + + + update.message.reply_text(f"Updated bookmarks page: {os.getenv('BOOKSTACK_URL')}") + except Exception as err: + update.message.reply_text(f"Failed to store url: {link}") + print(err) + traceback.print_exc() + + # try: + # self.wiki.pages.append("bookmarks/inbox", f"\n\n{update_body}") + # update.message.reply_text(f"Updated bookmarks page: {os.getenv('DOKU_URL')}bookmarks/inbox") + # except (dokuwiki.DokuWikiError) as err: + # update.message.reply_text(f"Failed to store url: {err}") \ No newline at end of file diff --git a/src/rafael/dailynote.py b/src/rafael/dailynote.py new file mode 100644 index 0000000..e69de29