megafono.py/megafono.py
2021-01-24 13:33:16 +01:00

54 lines
1.7 KiB
Python

from mastodon import Mastodon
from dotenv import load_dotenv
from pathlib import Path
import os
import time
def megafono():
"""
Toot only one line from ANNOUNCEMENT_FILE gradually or random if RANDOM is set.
It's useful configure a crontab for invocation
"""
load_dotenv()
INSTANCE_BASE = os.getenv('INSTANCE_BASE')
CLIENT_ID = os.getenv('CLIENT_ID')
CLIENT_SECRET = os.getenv('CLIENT_SECRET')
ACCESS_TOKEN = os.getenv('ACCESS_TOKEN')
ANNOUNCEMENT_FILE = os.getenv('ANNOUNCEMENT_FILE')
RANDOM = os.getenv('RANDOM')
IS_DOCKER = os.getenv('IS_DOCKER', False)
if IS_DOCKER:
last_id_file = str(Path('/data') / 'last_id')
ANNOUNCEMENT_FILE = str(Path('/data') / ANNOUNCEMENT_FILE)
else:
last_id_file = str(Path('./txt') / 'last_id.txt')
ANNOUNCEMENT_FILE = str(Path('./txt') / ANNOUNCEMENT_FILE)
mastodon = Mastodon(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
access_token=ACCESS_TOKEN,
api_base_url=INSTANCE_BASE)
if int(RANDOM):
import random
toot = random.choice(list(open(ANNOUNCEMENT_FILE, 'r')))
else:
last_id = 0
with open(last_id_file) as f:
last_id = int(f.read())
with open(ANNOUNCEMENT_FILE, 'r', encoding='utf8') as a:
toot = a.readlines()[last_id]
with open(ANNOUNCEMENT_FILE, 'r') as a:
length = len(a.readlines())
last_id += 1
last_id %= length
with open(last_id_file, 'w+') as f:
f.write(str(last_id))
mastodon.status_post(toot.replace('\\n','\n'), visibility='unlisted')
print("Sent: "+str(toot))
megafono()