exemple_mastodon.py/playlist2toot_v2/playlist2toot.py
2022-05-23 20:36:29 +02:00

174 lines
5.8 KiB
Python
Executable File

#!/usr/bin/python3
# coding: utf-8
# -*- coding: utf-8 -*-
from mastodon import Mastodon
import os
import time
import sys
import argparse
from configparser import ConfigParser
import ytscraper
__prog_name__ = 'playlist2toot'
__version__ = '0.2'
__description__ = 'Toot a playlist 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('-p', '--playlist', required=True,
help="Playlist text file")
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)
# Load the playlist file
with open(args.playlist, "r") as fichier:
playlist_mem = fichier.readlines()
# 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
#used bay make a thread
if conf.has_option('preset', 'thread'):
toot_lastid = None
# Log into Mastodon if enabled in settings
print('[ OK ] {} Let the show begin !'.format(time.strftime('%H:%M')))
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 {} as @{}'.format(
time.strftime('%H:%M'), mastodon_hostname, masto_username))
except BaseException as e:
print('[ERROR] Error while logging into Mastodon:', str(e))
sys.exit(0)
for i in range(len(playlist_mem)):
# Prepare the toot
if conf.has_option('toot', 'status'):
toot_status = conf['toot']['status'] + '\n'
else:
toot_status = ''
# video commentary
toot_status += playlist_mem[i].split(";")[0]
toot_status += '\n'
# video title
video = ytscraper.scrape_url(playlist_mem[i].split(";")[1])
toot_status += video.title
toot_status += '\n'
toot_status += video.yturl
# add hashtag
toot_status += '\n'
toot_status += conf['toot']['hashtag']
toot_status += ' '
toot_status += playlist_mem[i].split(";")[2]
# Prepare media IDs
try:
paththumbnail = './' + conf['preset']['dirthumbnail']
mfile = ytscraper.download_image(
video.thumbnail,
video.videoid,
paththumbnail
)
image_byte = open(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
try:
status = mastodonAPI.status_post(
status=toot_status,
in_reply_to_id=toot_lastid,
media_ids=[media_dict],
sensitive=toot_sensitive,
visibility=toot_visibility,
spoiler_text=toot_spoiler
)
print('[ OK ] {} Posting this on Mastodon account : {}'.format(
time.strftime('%H:%M'), status['url']))
except BaseException as e:
print('[ERROR] Error while posting toot:' + str(e))
sys.exit(0)
# make a thread
if conf.getboolean('preset', 'thread'):
toot_lastid = status['id']
else:
toot_lastid = None
# make a pause
print('use duration = ' + conf['preset']['useduration'])
print('delay = ' + conf['preset']['delay'])
if conf.getboolean('preset', 'useduration'):
preset_delay = video.durationinseconds
else:
print('delay = ' + conf['preset']['delay'])
preset_delay = int(conf['preset']['delay'])
print('preset_delay = ' + str(preset_delay), type(preset_delay))
if i < (len(playlist_mem) - 1):
time.sleep(preset_delay)
# The End
print('[ OK ] {} The show is over !'.format(time.strftime('%H:%M')))