exemple_mastodon.py/img2toot_v3/img2toot.py
2022-05-23 20:36:29 +02:00

117 lines
3.8 KiB
Python
Executable File

#!/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__ = 'img2toot'
__version__ = '0.3'
__description__ = 'Toot bot for random local NSFW image for 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="Image\'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)
image_dir = args.dir + "/"
# Overwrite default settings
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 = True
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(image_dir))
image_byte = open(image_dir + mfile, "rb").read()
if mfile[-3:] == "jpe":
mime = "image/jpeg"
elif mfile[-3:] == "jpg":
mime = "image/jpeg"
elif mfile[-3:] == "png":
mime = "image/png"
elif mfile[-3:] == "gif":
mime = "image/gif"
elif mfile[-3:] == "gifv":
mime = "video/mp4"
elif mfile[-3:] == "mp4":
mime = "video/mp4"
else:
print("Incorrect media file format")
media_dict = mastodonAPI.media_post(image_byte, mime)
except BaseException as e:
print ('[ERROR] Error while reading media file : ' + str(e))
sys.exit(0)
# Post the toot
toot_status = conf['toot']['status']
toot_status += '\n'
toot_status += conf['toot']['hashtag']
try:
status = mastodonAPI.status_post(
status=toot_status,
in_reply_to_id=None,
media_ids=[media_dict],
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))