From bdc61c31bc081c608cbdf77a13717a099930bd87 Mon Sep 17 00:00:00 2001 From: mst Date: Tue, 11 Mar 2025 16:07:34 +0300 Subject: [PATCH] add crosspost functionality --- functions.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/functions.py b/functions.py index be21819..6cce774 100644 --- a/functions.py +++ b/functions.py @@ -7,6 +7,7 @@ from pathlib import Path from mistune import HTMLRenderer, escape from PIL import Image from psycopg.rows import dict_row +from mastodon import Mastodon import base64 import time import zipfile @@ -291,6 +292,7 @@ def addAnswer(question_id: int, answer: str, cw: str) -> dict: cursor.execute("UPDATE questions SET answered=%s, answer_id=%s WHERE id=%s", (True, answer_id, question_id)) conn.commit() + # except Exception as e: # conn.rollback() # app.logger.error(e) @@ -301,6 +303,35 @@ def addAnswer(question_id: int, answer: str, cw: str) -> dict: return jsonify({'message': _('Answer added successfully!')}), 201 +def postOnFediverse(question_id: int, answer: str, cw: str) -> None: + # reloading config file + cfg = loadJSON(const.configFile) + + conn = connectToDb() + cursor = conn.cursor() + + app.logger.debug(f"[postOnFediverse] Grabbing question {question_id} from database...") + + cursor.execute("SELECT id, content FROM questions WHERE id=%s", (question_id,)) + question = cursor.fetchone() + + app.logger.debug("[postOnFediverse] Initializing Mastodon client...") + + client = Mastodon( + client_id = cfg['crosspost']['fediverse']['client']['id'], + client_secret = cfg['crosspost']['fediverse']['client']['secret'], + api_base_url = 'https://' + cfg['crosspost']['fediverse']['instance'], + access_token = cfg['crosspost']['fediverse']['token'] + ) + if cw: + warning = f"{cfg['crosspost']['fediverse']['cw']}, {cw}" + else: + warning = cfg['crosspost']['fediverse']['cw'] + post_content = f"{question['content']} — {answer} {cfg['instance']['fullBaseUrl']}/q/{question['id']}/" + client.status_post(post_content, visibility=cfg['crosspost']['fediverse']['visibility'], spoiler_text=warning) + + app.logger.debug(f"[postOnFediverse] Made Fediverse post: {post_content}") + def ntfySend(cw, return_val, from_who, question) -> None: app.logger.debug("[CatAsk/functions/ntfySend] started ntfy flow") ntfy_cw = f" [CW: {cw}]" if cw else ""