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)