示例#1
0
def main():
    url = "https://mstdn.poyo.me"
    path = Path(__file__).parent.resolve()
    paths = [
        str(path / "token"),
        star(path / "figure"),
        str(path / "data"),
        str(path / "data" / "all"),
        str(path / "data" / "ponytail"),
        str(path / "data" / "kedama")
    ]
    for path in paths:
        check_dir(path)

    Mastodon.create_app(
        client_name="ponymofu_counter",
        scopes=["read", "write"],
        website="https://github.com/kelvin27315/ponymofu_counter",
        to_file=path / "clientcred.secret",
        api_base_url=url)

    mastodon = Mastodon(client_id=(path / "clientcred.secret"),
                        api_base_url=url)

    mail = "*****@example.com"
    password = "******"
    mastodon.log_in(mail,
                    password,
                    scopes=['read', 'write'],
                    to_file=path / "usercred.secret")
示例#2
0
def mastodon_register(ctx: click.Context, cred_file: str,
                      bot_name: str) -> None:
    "register your bot's account on the homeserver"
    Mastodon.create_app(bot_name,
                        api_base_url=ctx.obj["base_url"],
                        to_file=os.path.join(ctx.obj["secret_folder"],
                                             cred_file))
示例#3
0
def register_app(appName, credentialFile, url):

    SECRET_DIR = '/home/z/prj/mastobots/secrets/'

    Mastodon.create_app(appName,
                        api_base_url=url,
                        to_file=SECRET_DIR + credentialFile)
示例#4
0
 def make_clientid(self):
     appname = self.ui.lineEdit.text()
     url = self.ui.lineEdit_2.text()
     cid_file = 'client_id.txt'
     Mastodon.create_app(appname, api_base_url=url, to_file=cid_file)
     with open(cid_file) as ci:
         self.ui.lineEdit_3.setText(ci.read())
示例#5
0
def init_app(app_name, url, email, password):
    if os.path.exists(clientcred_file) is False:
        Mastodon.create_app(app_name,
                            api_base_url=url,
                            to_file=".clientcred.secret")
    app = Mastodon(client_id=".clientcred.secret", api_base_url=url)
    app.log_in(email, password, to_file=".usercred.secret")
示例#6
0
def initialize_mastodon():
    server_url = config("MASTODON_SERVER")
    # make data dir
    mastodon_data_path = Path(__file__).parents[1] / "data" / "mastodon"
    # フォルダの方は Error を回避
    try:
        Path(mastodon_data_path.parent).mkdir()
        Path(mastodon_data_path).mkdir()
    except FileExistsError:
        print("you have already make mastodon data folder")

    mastodon_client_data_path = mastodon_data_path / "my_clientcred.txt"
    mastodon_user_data_path = mastodon_data_path / "my_usercred.txt"
    # If you already have data file, Raise error
    for path in (mastodon_user_data_path, mastodon_client_data_path):
        if path.exists():
            raise FileExistsError(path.as_posix(), "is already exists")

    # get mastodon data
    Mastodon.create_app("client name", api_base_url=server_url,
                        to_file=mastodon_client_data_path.as_posix())
    mastodon = Mastodon(client_id=mastodon_client_data_path.as_posix(),
                        api_base_url=server_url)
    mastodon.log_in(config("MASTODON_EMAIL"), config("MASTODON_PASS"),
                    to_file=mastodon_user_data_path.as_posix())
示例#7
0
def instantiate_bot() -> Mastodon:
    if not os.path.exists(config('MASTODON_SECRET_LOCATION')):
        BOT_LOG.info(f'Creating Mastodon app...')
        Mastodon.create_app(
            'mastodoff',
            api_base_url=config('MASTODON_API'),
            to_file=config('MASTODON_SECRET_LOCATION'),
        )

    if not os.path.exists(config('MASTODON_TOKEN_LOCATION')):
        BOT_LOG.info(f'Getting Mastodon token...')
        mastodon = Mastodon(
            client_id=config('MASTODON_SECRET_LOCATION'),
            api_base_url=config('MASTODON_API'),
        )
        mastodon.log_in(
            config('MASTODON_USERNAME'),
            config('MASTODON_PASSWORD'),
            to_file=config('MASTODON_TOKEN_LOCATION'),
        )

    BOT_LOG.info(f'Instantiating mastodon.Mastodon...')
    client = Mastodon(
        client_id=config('MASTODON_SECRET_LOCATION'),
        access_token=config('MASTODON_TOKEN_LOCATION'),
        api_base_url=config('MASTODON_API'),
        ratelimit_method='throw',
    )

    return (client)
示例#8
0
def login(config: CleanTootsConfig, only_missing: bool):
    """Fetch credentials for each app described in config file."""
    if not _config_has_sections(config):
        return
    prompt = True
    for section in config.sections():
        section = config[section]
        app_file_exists = config.isfile(section.get("app_secret_file"))
        user_file_exists = config.isfile(section.get("user_secret_file"))

        if not (only_missing and app_file_exists):
            Mastodon.create_app(
                "cleantoots",
                api_base_url=section.get("api_base_url"),
                to_file=config.file(section.get("app_secret_file")),
            )

        mastodon = Mastodon(
            client_id=config.file(section.get("app_secret_file")))
        if not (only_missing and user_file_exists and app_file_exists):
            _open_url(mastodon.auth_request_url(), echo=prompt)
            prompt = False
            code = click.prompt("Enter code for {}".format(
                section.get("api_base_url")))
            mastodon.log_in(code=code,
                            to_file=config.file(
                                section.get("user_secret_file")))
示例#9
0
def get_credential(**config):
    api_base_url = config.get('instance_url')
    if not api_base_url:
        raise Exception(
            'Correctly specify instance_url on {}.'.format(CONFIG_FILE_NAME))
    if not exists(CLIENT_SECRET_FILE_NAME):
        Mastodon.create_app(
            client_name=config.get('app_name') or 'chatbotdon',
            website=config.get('website')
            or 'https://github.com/kakakaya/chatbotdon',
            to_file=CLIENT_SECRET_FILE_NAME,
            api_base_url=api_base_url,
        )

    access_token = None
    if exists(USER_SECRET_FILE_NAME):
        access_token = USER_SECRET_FILE_NAME
    m = Mastodon(client_id=CLIENT_SECRET_FILE_NAME,
                 access_token=access_token,
                 api_base_url=api_base_url)
    if not access_token:
        m.log_in(
            username=config.get('username'),
            password=config.get('password'),
            to_file=USER_SECRET_FILE_NAME,
        )
    return m
示例#10
0
def get_access_token():
    config = ConfigParser()
    config.readfp(io.open('token.ini', 'r', encoding='utf_8_sig'))

    section = 'Token'
    api_base_url = config.get(section, 'api_base_url')
    username = config.get(section, 'username')
    password = config.get(section, 'password')

    client_id = config.get(section, 'client_id')
    access_token = config.get(section, 'access_token')
    scopes = ['read', 'write']

    Mastodon.create_app(
        'TOMOYODon',
        scopes=scopes,
        api_base_url=api_base_url,
        to_file=client_id
    )

    mastodon = Mastodon(
        client_id=client_id,
        api_base_url=api_base_url
    )

    mastodon.log_in(
        username=username,
        password=password,
        scopes=scopes,
        to_file=access_token
    )
示例#11
0
文件: client.py 项目: halcy/tootmage
def ensure_app_config(url_file, client_file, user_file):
    if not os.path.isfile(url_file):
        print("No settings found.")
        base_url = input("Instance URL: ")
        user = input("E-Mail: ")
        password = getpass.getpass("Password: "******"w") as f:
                    f.write(base_url)
            else:
                print("Whoops, that went wrong - try again.")
                sys.exit(0)
        except:
            print("Whoops, that went wrong - try again.")
            sys.exit(0)
示例#12
0
def login():
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.content_type = "application/json"
    username = request.forms.get("username")  # pylint: disable=no-member
    password = request.forms.get("password")  # pylint: disable=no-member
    instance = request.forms.get("instance")  # pylint: disable=no-member
    if debug:
        appname = "Nordcast (debug)"
    else:
        appname = "Nordcast"
    if not os.path.exists('clientcred.' + instance + '.secret'):
        Mastodon.create_app(appname,
                            api_base_url='https://' + instance,
                            to_file='clientcred.' + instance + '.secret')
    mastodon = Mastodon(client_id='clientcred.' + instance + '.secret',
                        api_base_url='https://' + instance)
    mastodon.log_in(
        username,
        password,
        to_file='authtokens/' + username + '.' + instance + '.secret',
    )
    if not os.path.exists("usercred.secret"):
        suid = str(uuid.uuid1())
        if r.get("nordcast/uuids/" + username + "$$" + instance) == None:
            r.set("nordcast/uuids/" + username + "$$" + instance, suid)
        else:
            r.set(
                "nordcast/uuids/" + username + "$$" + instance,
                str(r.get("nordcast/uuids/" + username + "$$" +
                          instance)).replace("b'", "").replace("'", "") + "," +
                suid)
        return json.dumps({"login": "******", "uuid": suid})
    else:
        return "{\"login\": \"error\"}"
示例#13
0
def createmastodonapp(appname, baseurl, email, password):
    Mastodon.create_app(appname,
                        api_base_url=baseurl,
                        to_file='pytooter_clientcred.secret')
    # Then login. This can be done every time, or use persisted.
    mastodon = Mastodon(client_id='pytooter_clientcred.secret',
                        api_base_url=baseurl)
    mastodon.log_in(email, password, to_file='pytooter_usercred.secret')
示例#14
0
def send_toot(ticket, config):
    logging.info("toot the release")

    target = ''
    if ticket.voctoweb_enable and ticket.profile_voctoweb_enable:
        target = config['voctoweb']['instance_name']
    if ticket.youtube_enable and ticket.profile_youtube_enable:
        if len(target) > 1:
            target += ' and '
        target += 'YouTube'

    msg = ' has been released on ' + target
    title = ticket.title
    if len(title) >= (500 - len(msg)):
        title = title[0:len(msg)]
    message = title + msg

    if ticket.voctoweb_enable and ticket.profile_voctoweb_enable:
        voctoweb_url = ' ' + config['voctoweb'][
            'frontend_url'] + '/v/' + ticket.slug
        if len(voctoweb_url) <= (500 - len(message)):
            message = message + voctoweb_url
    if ticket.youtube_enable and ticket.profile_youtube_enable and len(
            ticket.youtube_urls['YouTube.Url0']) <= (500 - len(message)):
        message = message + ' ' + ticket.youtube_urls['YouTube.Url0']

    try:
        # check if we already have our client token and secret and if not get a new one
        if not Path('./mastodon_clientcred.secret').exists():
            logging.debug(
                'no mastodon client credentials found, get fresh ones')
            Mastodon.create_app(
                'voctopublish',
                api_base_url=config['mastodon']['api_base_url'],
                to_file='mastodon_clientcred.secret')
        else:
            logging.debug('Using exisiting Mastodon client credentials')

        mastodon = Mastodon(client_id='mastodon_clientcred.secret',
                            api_base_url=config['mastodon']['api_base_url'])

        # check if we already have an access token, if not get a fresh one
        if not Path('./mastodon_usercred.secret').exists():
            logging.debug(
                'no mastodon user credentials found, getting a fresh token')
            mastodon.log_in(config['mastodon']['email'],
                            config['mastodon']['password'],
                            to_file='mastodon_usercred.secret')
        else:
            logging.debug('Using existing Mastodon user token')

        # Create actual API instance
        mastodon = Mastodon(access_token='mastodon_usercred.secret',
                            api_base_url=config['mastodon']['api_base_url'])
        mastodon.toot(message)
    except Exception as e_:
        # we don't care if tooting fails here.
        logging.error('Tooting failed: ' + str(e_))
示例#15
0
def register_app():
    """
    Register the bot.

    :note: run only once
    """
    Mastodon.create_app('asciimimebot',
                        api_base_url='https://botsin.space',
                        to_file='asciimime_clientcred.secret')
示例#16
0
def register_app(world: World, api_base_url: str) -> int:
    world.fs.makedirs(graftbot.dirs.config_dir())
    Mastodon.create_app(
        "graft",
        api_base_url=api_base_url,
        website="https://github.com/andybalaam/graft",
        to_file=graftbot.dirs.client_file(),
    )
    return 0
示例#17
0
 def register(self):
     """
     Register application and saves client secret.
     """
     print("Registering app")
     Mastodon.create_app(self.name,
                         api_base_url=self.url,
                         scopes=self.scopes,
                         to_file=self.client_secret)
示例#18
0
def make_cred_secret():
    Mastodon.create_app('good night',
                        api_base_url=mstd_website,
                        to_file='pytooter_clientcred.secret')
    mastodon = Mastodon(client_id='pytooter_clientcred.secret',
                        api_base_url=mstd_website)
    mastodon.log_in(BOT_ACCOUNT,
                    BOT_PASSWD,
                    to_file='pytooter_usercred.secret')
示例#19
0
def setup():
	print("------------------")
	print("  MASTODON SETUP  ")
	print("------------------\n")

	print("To connect to Mastodon I need some informations.")

	mastodonWorks = False

	while not mastodonWorks:
		print("\n")
		mastodonURL      = "https://" + input("Your Mastodon instance URL: https://")
		mastodonEMail    =              input("      Your Mastodon e-mail: ")
		mastodonPassword =    getpass.getpass("    Your Mastodon password: "******"\nOkay, let's try to connect to Mastodon!\n")

		try:
			Mastodon.create_app(
				'MastoTwitter',
				scopes       = ['read', 'write'],
				api_base_url = mastodonURL,
				to_file      = 'mastodon_client.secret'
			)
		except Exception as error:
			print("Cannot create a Mastodon app: " + error)
			sys.exit(1)


		try:
			api = Mastodon(
				client_id    = 'mastodon_client.secret',
				api_base_url = mastodonURL
			)
			api.log_in(
				username = mastodonEMail,
				password = mastodonPassword,
				to_file  = 'mastodon_user.secret',
				scopes   = ["read", "write"]
			)
		except Exception as error:
			print("You made a mistake, theses informations didn't worked...\nLet's start again!")
			print(error)

		else:
			mastodonWorks = True

	print("Alright, that worked!")

	mastodonSecrets = open(mastodonSecretsLoc, "w")

	mastodonSecrets.write(mastodonURL)

	mastodonSecrets.close()

	print("Theses keys are now saved inside " + mastodonSecretsLoc + ", please keep it secret!")
示例#20
0
def create_app(file_name, api_url):
    """
    アプリケーションを登録する
    """
    Mastodon.create_app(
        client_name="mastodon-wordcloud",
        scopes=["read", "write"],
        website="https://github.com/kelvin27315/mastodon-wordcloud",
        to_file=PATH + file_name,
        api_base_url=api_url)
def init_mastodon():
    Mastodon.create_app(f'paramsinstaimporter-{str(uuid.uuid4())}',
                        api_base_url='https://mitron.social',
                        to_file='paramsinstaimporter.secret')
    global mastodon
    mastodon = Mastodon(client_id='paramsinstaimporter.secret',
                        api_base_url='https://mitron.social')
    mastodon.log_in(username='******',
                    password='******',
                    to_file='paramsusercred.secret')
示例#22
0
文件: __init__.py 项目: paologlim/t2m
def _ensure_client_exists_for_instance(instance):
    "Create the client creds file if it does not exist, and return its path."
    client_id = "t2m_%s_clientcred.txt" % instance
    if not os.path.exists(client_id):
        Mastodon.create_app(
            't2m',
            to_file=client_id,
            api_base_url='https://%s' % instance,
        )
    return client_id
示例#23
0
def create_app():
    global MASTODON_HOST
    global BASE_URL
    global SECRET_NAME

    Mastodon.create_app(
        APP_NAME,
        api_base_url=BASE_URL,
        to_file=SECRET_NAME
    )
    def on_internet_available(self, agent):
        config = agent.config()
        display = agent.view()
        last_session = agent.last_session
        api_base_url = self.options['instance_url']
        email = self.options['email']
        password = self.options['password']
        visibility = self.options['visibility']
        client_cred = '/root/.mastodon.client.secret'
        user_cred = '/root/.mastodon.user.secret'

        if last_session.is_new() and last_session.handshakes > 0:
            logging.info('[mastodon] Detected internet and new activity: time to post!')

            if not os.path.isfile(user_cred) or not os.path.isfile(client_cred):
                # Runs only if there are any missing credential files
                Mastodon.create_app(
                    config['main']['name'],
                    api_base_url=api_base_url,
                    to_file=client_cred
                )
            picture = '/root/pwnagotchi.png'
            display.on_manual_mode(last_session)
            display.image().save(picture, 'png')
            display.update(force=True)

            try:
                logging.info('[mastodon] Connecting to Mastodon API')
                mastodon = Mastodon(
                    client_id=client_cred,
                    api_base_url=api_base_url
                )
                mastodon.log_in(
                    email,
                    password,
                    to_file=user_cred
                )
                mastodon = Mastodon(
                    access_token=user_cred,
                    api_base_url=api_base_url
                )
                message = Voice(lang=config['main']['lang']).on_last_session_tweet(last_session)
                mastodon.status_post(
                    message,
                    media_ids=mastodon.media_post(picture),
                    visibility=visibility
                )

                last_session.save_session_id()
                logging.info('[mastodon] posted: %s', message)
                display.set('status', 'Posted!')
                display.update(force=True)
            except Exception as ex:
                logging.exception('[mastodon] error while posting: %s', ex)
示例#25
0
def init_twitter_api():
    global api
    if (os.path.isfile('clientcred.secret') == False):
        Mastodon.create_app('ace-attorney',
                            api_base_url=keys['domain'],
                            to_file='clientcred.secret')
    if (os.path.isfile('usercred.secret') == False):
        m = Mastodon(client_id='clientcred.secret',
                     api_base_url=keys['domain'])
        m.log_in(keys['mail'], keys['password'], to_file='usercred.secret')

    api = Mastodon(access_token='usercred.secret', api_base_url=keys['domain'])
示例#26
0
def submitToot(tweetText):
    if DEBUG_MODE == False:
        Mastodon.create_app('HNToots', to_file='HNToots_clientcred.txt')
        mastodon = Mastodon(client_id='HNToots_clientcred.txt')
        mastodon.log_in(MASTADON_USER,
                        MASTADON_PASSWORD,
                        to_file='HNToots_usercred.txt')
        mastodon = Mastodon(client_id='HNToots_clientcred.txt',
                            access_token='HNToots_usercred.txt')
        mastodon.toot(tweetText)
    else:
        print(tweetText)
示例#27
0
def login():
    """Logs into Mastodon and creates local credentials files."""
    password = getpass.getpass("Enter Mastodon password: "******"Created credential files: {}, {}".format(CLIENT_SECRET_FILE,
                                                    MASTODON_SECRET_FILE))
示例#28
0
def create(filename):
    global url
    global user
    global password
    global secret
    with open(filename, "r") as f:
        r = f.readlines()
        secret = r[0].replace("\n", "") + ".secret"
        url = "https://" + r[0].replace("\n", "")
        user = r[1].replace("\n", "")
        password = r[2].replace("\n", "")
    if os.path.exists(secret) == False:
        Mastodon.create_app('pleromabot', api_base_url=url, to_file=secret)
示例#29
0
def createCreds(pool):
    instance = pool.mastInstance
    user = pool.mastUser
    password = pool.mastPassword
    secPath = pool.mastSecPath
    appName = pool.mastAppName
    clientCredFile = os.path.join(secPath, "ghi_clientcred.secret")
    userCredFile = os.path.join(secPath, "ghi_usercred.secret")

    Mastodon.create_app(appName, api_base_url=instance, to_file=clientCredFile)

    mastodon = Mastodon(client_id=clientCredFile, api_base_url=instance)

    mastodon.log_in(user, password, to_file=userCredFile)
示例#30
0
文件: bot.py 项目: csmall/420bot
def register(args, clientcred_file, usercred_file):
    Mastodon.create_app(BOT_NAME,
                        to_file=clientcred_file,
                        api_base_url=BASE_URL)

    mastodon = Mastodon(client_id=clientcred_file, api_base_url=BASE_URL)

    (login, password) = args.register
    try:
        mastodon.log_in(login, password, to_file=usercred_file)
    except Exception as login_err:
        print('Unable to login new bot: {0}'.format(login_err))

    print('Bot is registered successfully')
示例#31
0
    def register(self):
        import webbrowser

        self.check_params('handle')
        api_base_url = self.params['handle'].split('@')[-1]
        # get client data
        client_id = self.context.params.get(service_name, 'client_id')
        client_secret = self.context.params.get(service_name, 'client_secret')
        if (not client_id) or (not client_secret):
            client_id, client_secret = Mastodon.create_app(
                'pywws', scopes=['write'], api_base_url=api_base_url)
            self.context.params.set(service_name, 'client_id', client_id)
            self.context.params.set(service_name, 'client_secret', client_secret)
        # create api
        api = Mastodon(client_id=client_id, client_secret=client_secret,
                       api_base_url=api_base_url)
        # authorise
        auth_request_url = api.auth_request_url(scopes=['write'])
        if not webbrowser.open(auth_request_url, new=2, autoraise=0):
            print('Please use a web browser to open the following URL')
            print(auth_request_url)
        if sys.version_info[0] >= 3:
            input_ = input
        else:
            input_ = raw_input
        code = input_('Please enter the auth code shown in your web browser: ')
        code = code.strip()
        # log in
        access_token = api.log_in(code=code, scopes=['write'])
        self.context.params.set(service_name, 'access_token', access_token)
示例#32
0
    def auth(self, request):
        """
            get the auth of the services
            :param request: contains the current session
            :type request: dict
            :rtype: dict
        """
        # create app
        redirect_uris = '%s://%s%s' % (request.scheme, request.get_host(),
                                       reverse('mastodon_callback'))
        us = UserService.objects.get(user=request.user,
                                     name='ServiceMastodon')
        client_id, client_secret = MastodonAPI.create_app(
            client_name="TriggerHappy", api_base_url=us.host,
            redirect_uris=redirect_uris)

        us.client_id = client_id
        us.client_secret = client_secret
        us.save()

        us = UserService.objects.get(user=request.user,
                                     name='ServiceMastodon')
        # get the token by logging in
        mastodon = MastodonAPI(
            client_id=client_id,
            client_secret=client_secret,
            api_base_url=us.host
        )
        token = mastodon.log_in(username=us.username, password=us.password)
        us.token = token
        us.save()
        return self.callback_url(request)
示例#33
0
def init(config):
    API_BASE_URL = config['Mastodon']['API_BASE_URL']

    if not os.path.exists('clientcred.secret'):
        Mastodon.create_app(
            config['Mastodon']['APP_NAME'],
            api_base_url = API_BASE_URL,
            to_file = 'clientcred.secret'
        )

    mastodon = Mastodon(
        client_id = 'clientcred.secret',
        api_base_url = API_BASE_URL
    )

    mastodon.log_in(
        config['Mastodon']['EMAIL'],
        config['Mastodon']['PASS_WORD'],
        to_file = 'usercred.secret'
    )

    return mastodon
示例#34
0
    def check(self, request, user):
        """
        check if the service is well configured
        :return: Boolean
        """
        redirect_uris = '%s://%s%s' % (request.scheme, request.get_host(), reverse('mastodon_callback'))
        us = UserService.objects.get(user=user,
                                     name='ServiceMastodon')
        client_id, client_secret = MastodonAPI.create_app(
            client_name="TriggerHappy", api_base_url=us.host,
            redirect_uris=redirect_uris)

        # get the token by logging in
        mastodon = MastodonAPI(
            client_id=client_id,
            client_secret=client_secret,
            api_base_url=us.host
        )
        try:
            mastodon.log_in(username=us.username, password=us.password)
            return True
        except MastodonIllegalArgumentError as e:
            return e
示例#35
0
def send_toot(ticket, config):
    logging.info("toot the release")

    target = ''
    if ticket.voctoweb_enable and ticket.profile_voctoweb_enable:
        target = config['voctoweb']['instance_name']
    if ticket.youtube_enable and ticket.profile_youtube_enable:
        if len(target) > 1:
            target += ' and '
        target += 'YouTube'

    msg = ' has been released on ' + target
    title = ticket.title
    if len(title) >= (500 - len(msg)):
        title = title[0:len(msg)]
    message = title + msg

    if ticket.voctoweb_enable and ticket.profile_voctoweb_enable:
        voctoweb_url = ' ' + config['voctoweb']['frontend_url'] + '/v/' + ticket.slug
        if len(voctoweb_url) <= (500 - len(message)):
            message = message + voctoweb_url
    if ticket.youtube_enable and ticket.profile_youtube_enable and len(ticket.youtube_urls['YouTube.Url0']) <= (500 - len(message)):
        message = message + ' ' + ticket.youtube_urls['YouTube.Url0']

    try:
        # check if we already have our client token and secret and if not get a new one
        if not Path('./mastodon_clientcred.secret').exists():
            logging.debug('no mastodon client credentials found, get fresh ones')
            Mastodon.create_app(
                'voctopublish',
                api_base_url=config['mastodon']['api_base_url'],
                to_file='mastodon_clientcred.secret'
            )
        else:
            logging.debug('Using exisiting Mastodon client credentials')

        mastodon = Mastodon(
            client_id='mastodon_clientcred.secret',
            api_base_url=config['mastodon']['api_base_url']
        )

        # check if we already have an access token, if not get a fresh one
        if not Path('./mastodon_usercred.secret').exists():
            logging.debug('no mastodon user credentials found, getting a fresh token')
            mastodon.log_in(
                config['mastodon']['email'],
                config['mastodon']['password'],
                to_file='mastodon_usercred.secret'
            )
        else:
            logging.debug('Using existing Mastodon user token')

        # Create actual API instance
        mastodon = Mastodon(
            access_token='mastodon_usercred.secret',
            api_base_url=config['mastodon']['api_base_url']
        )
        mastodon.toot(message)
    except Exception as e_:
        # we don't care if tooting fails here.
        logging.error('Tooting failed: ' + str(e_))
示例#36
0
    return True

if __name__ == '__main__':
    from mastodon import Mastodon

    try:
        base_url, email, password, clientname, clientcred, usercred = sys.argv[1:]
    except:
        print("Usage: %s base_url email password clientname clientcredsfile usercredsfile" % sys.argv[0])
        sys.exit(2)

    if not os.path.isfile(clientcred):
        Mastodon.create_app(
            clientname,
            to_file = clientcred,
            scopes = [ 'read', 'write' ],
            api_base_url = base_url)

    if not os.path.isfile(usercred):
        mastodon_api = Mastodon(
            client_id = clientcred,
            api_base_url = base_url)

        mastodon_api.log_in(
            email,
            password,
            to_file = usercred,
            scopes = [ 'read', 'write' ],
            )