#!/usr/bin/python3 # coding: utf-8 # -*- coding: utf-8 -*- from mastodon import Mastodon import os import random import sys import argparse from configparser import ConfigParser __prog_name__ = 'txt2toot' __version__ = '0.1' __description__ = 'Toot a random text file on Mastodon' if __name__ == "__main__": # Read arguments parser = argparse.ArgumentParser(prog=__prog_name__, description=__description__) parser.add_argument('--version', action='version', version=__version__) parser.add_argument('-d', '--dir', required=True, help="Text file\'s directory") parser.add_argument('-c', '--config', default='config.ini', help="Config file (default: %(default)s)") args = parser.parse_args() config_filepath = args.config # Check if config file exists if not os.path.isfile(config_filepath): print("Config file %s not found, exiting." % config_filepath) sys.exit(0) else: # Read config file conf = ConfigParser() conf.read(config_filepath) # Need a directory if not args.dir: print("Image\'s directory argument missing") sys.exit(0) txt_dir = args.dir + "/" # Overwrite default settings if conf.has_option('toot', 'status'): toot_status = conf['toot']['status'] + '\n' else: toot_status = '' if conf.has_option('toot', 'visibility'): toot_visibility = conf['toot']['visibility'] else: toot_visibility = '' if conf.has_option('toot', 'sensitive'): toot_sensitive = conf['toot']['sensitive'] else: toot_sensitive = False if conf.has_option('toot', 'spoiler'): toot_spoiler = conf['toot']['spoiler'] else: toot_spoiler = None # Log into Mastodon if enabled in settings mastodon_hostname = conf['mastodon']['mastodon_hostname'] try: mastodonAPI = Mastodon( client_id=conf['mastodon']['client_id'], client_secret=conf['mastodon']['client_secret'], access_token=conf['mastodon']['access_token'], api_base_url='https://' + mastodon_hostname ) masto_username = mastodonAPI.account_verify_credentials()['username'] print ('[ OK ] Sucessfully authenticated on ' + mastodon_hostname + ' as @' + masto_username) except BaseException as e: print ('[ERROR] Error while logging into Mastodon:', str(e)) sys.exit(0) #Prepare media IDs try: mfile = random.choice(os.listdir(txt_dir)) txt_byte = open(txt_dir + mfile, "r").read() print(type(txt_byte)) #TODO : améliorer avec prise en compte hashtag+txt txt_len = len(toot_status) + len(conf['toot']['hashtag']) print(type(txt_len)) txt_maxlen = 500 - txt_len toot_status += txt_byte[:txt_maxlen] except BaseException as e: print ('[ERROR] Error while reading text file : ' + str(e)) sys.exit(0) # Post the toot toot_status += '\n' toot_status += conf['toot']['hashtag'] try: status = mastodonAPI.status_post( status=toot_status, in_reply_to_id=None, media_ids=None, sensitive=toot_sensitive, visibility=toot_visibility, spoiler_text=toot_spoiler ) print ( '[ OK ] Posting this on Mastodon account with media attachment : ' + status['url']) except BaseException as e: print ('[ERROR] Error while posting toot:' + str(e)) sys.exit(0)