communistquotes/templates/main.py

62 lines
1.9 KiB
Python

#!/usr/bin/python3
import os
from mastodon import Mastodon
import csv
import itertools
import random
import os
import argparse
instance = os.environ['MASTODON_INSTANCE']
username = os.environ['MASTODON_USERNAME']
parser = argparse.ArgumentParser(description='Parse quotes from .csv files, and post a random quote to Mastodon API')
parser.add_argument('--debug', action='store_true', help='Dont actually login or post to the remote API')
args = parser.parse_args()
mastodon_api = None
if not args.debug:
# Create application if it does not exist
# TODO: store this file in volume
if not os.path.isfile(instance+'.secret'):
if Mastodon.create_app(
'tootbot',
api_base_url='https://'+instance,
to_file = instance+'.secret'
):
print('tootbot app created on instance '+instance)
else:
print('failed to create app on instance '+instance)
exit(1)
mastodon_api = Mastodon(
client_id=instance+'.secret',
api_base_url='https://'+instance
)
mastodon_api.log_in(
username=username,
password=os.environ['MASTODON_PASSWORD'],
scopes=['read', 'write'],
to_file=username+".secret"
)
quotes = []
for root, dirs, files in os.walk('quotes/'):
for name in files:
(base, ext) = os.path.splitext(name)
if ext == '.csv':
full_name = os.path.join(root, name)
with open(full_name) as csvfile:
csvreader = csv.reader(csvfile, delimiter=',', quotechar='`', skipinitialspace=True)
quotes += list(csvreader)
print('Found %d total quotes' % len(quotes))
row = random.choice(quotes)
text = '<p>{}</p>&nbsp;&nbsp;&nbsp;&nbsp;- {}, <a href={}>{}</a>'.format(row[0], row[1], row[2], row[3])
print(text)
if not args.debug:
mastodon_api.status_post(text, visibility='public', content_type='text/html')