From 477c67dd463deda6608d52d8b50aeb03d8f12aaa Mon Sep 17 00:00:00 2001 From: mst Date: Tue, 11 Mar 2025 16:08:49 +0300 Subject: [PATCH] add fedi crosspost setup script --- masto.py | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 masto.py diff --git a/masto.py b/masto.py new file mode 100644 index 0000000..f2571df --- /dev/null +++ b/masto.py @@ -0,0 +1,56 @@ +from mastodon import Mastodon, MastodonUnauthorizedError +from constants import appName, configFile, homepageUrl +from functions import loadJSON, saveJSON +import json +import os + +cfg = loadJSON(configFile) + +scopes = ["read:accounts", "write:statuses"] + +if not cfg['crosspost']['fediverse']['instance']: + cfg['crosspost']['fediverse']['instance'] = input("Instance domain: ") + +if not (cfg['crosspost']['fediverse']['client'].get('id') and cfg['crosspost']['fediverse']['client'].get('secret')): + if not cfg['crosspost']['fediverse']['instance']: + print("You need to set your instance domain before running this script (Admin panel -> Crosspost -> Fediverse -> Instance domain)") + exit(1) + + client_id, client_secret = Mastodon.create_app( + appName, + api_base_url = 'https://' + cfg['crosspost']['fediverse']['instance'], + scopes = scopes, + website = homepageUrl + ) + cfg['crosspost']['fediverse']['client'] = { + "id": client_id, + "secret": client_secret + } + +if not cfg['crosspost']['fediverse']['token']: + client = Mastodon( + client_id = cfg['crosspost']['fediverse']['client']['id'], + client_secret = cfg['crosspost']['fediverse']['client']['secret'], + api_base_url = 'https://' + cfg['crosspost']['fediverse']['instance'] + ) + + print("Open this URL and authenticate to give {} access to your bot's account: {}".format(appName, client.auth_request_url(scopes=scopes))) + + cfg['crosspost']['fediverse']['token'] = client.log_in(code=input("Secret: "), scopes = scopes) + + saveJSON(cfg, configFile) + +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'] +) + +try: + me = client.account_verify_credentials() + print("Setup finished") + exit() +except MastodonUnauthorizedError: + print("The provided access token in {} is invalid. Please remove credentials in Admin panel -> Crosspost -> Fediverse and run {} again.").format(configFile, os.path.basename(__file__)) + exit(1)