This repository has been archived on 2021-02-17. You can view files and clone it, but cannot push or open issues or pull requests.
masto-image-bot/bot.py

136 lines
4.3 KiB
Python

#!/usr/bin/python3
# coding: utf-8
# -*- coding: utf-8 -*-
from mastodon import Mastodon, StreamListener
from TootHTMLParser import TootHTMLParser
import requests, os, random, sys, time, json, logging, argparse
from logging.handlers import RotatingFileHandler
from pprint import pprint
# Mastodon Stream Listener defines functions to react when something happens on Mastodon. We inherit it.
class BotListener(StreamListener):
def __init__(self, mastodon):
print("init")
StreamListener.__init__(self)
self.mastodon = mastodon
pprint(vars(mastodon.stream_user(StreamListener)))
def handle_mention(self, status):
log.debug('Got a mention!')
def on_notification(self, notification):
log.debug("here")
for thread in self.threads:
if(not thread.is_alive()):
logging.info("removing thread" + str(thread))
self.threads.remove(thread)
#We react to mentions only
if(notification['type'] != 'mention'):
log.info("nevermind, it's not a mention")
return
#So there is a toot !
status = notification['status']
#And there is a text in this toot. But it is mixed with HTML we don't want so we get rid of it.
content = str(status["content"])
parser = TootHTMLParser()
parser.feed(content)
content = (parser.txt).lower()
logging.info(content)
atUser = status["account"]["acct"]
userInfo = self.associateToUser(atUser)
#If the toot is not in answer to a drawing
answerTo = status["in_reply_to_id"]
def get_parameter( parameter, file_path ):
# Check if secrets file exists
if not os.path.isfile(file_path):
log.error("File %s not found, exiting."%file_path)
sys.exit(0)
# Find parameter in file
with open( file_path ) as f:
for line in f:
if line.startswith( parameter ):
return line.replace(parameter + ":", "").strip()
# Cannot find parameter, exit
log.critical(file_path + " Missing parameter %s "%parameter)
sys.exit(0)
def post_img(mastodon, text, visibility, logging):
file = random.choice(os.listdir(img_path+"/"))
image_byte = open(img_path+"/"+file, "rb").read()
if file[-3:] == "jpe":
mime = "image/jpeg"
else :
if file[-3:] == "jpg":
mime = "image/jpeg"
else :
if file[-3:] == "png":
mime = "image/png"
else :
if file[-3:] == "gif":
mime = "image/gif"
media_dict = mastodon.media_post(image_byte, mime)
mastodon.status_post("", None, media_ids=[media_dict], sensitive=True, visibility='', spoiler_text="#NSFW")
def init(config, secrets):
log = logging.getLogger()
log.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s')
file_handler = RotatingFileHandler('activity.log', 'a', 1000000, 1)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
log.addHandler(file_handler)
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.DEBUG)
log.addHandler(stream_handler)
uc_client_id = get_parameter("client_id", secrets)
uc_client_secret = get_parameter("client_secret", secrets)
uc_access_token = get_parameter("access_token", secrets)
mastodon_hostname = get_parameter("mastodon_hostname", secrets)
img_path = get_parameter("img_path", config)
mastodon = Mastodon(
client_id = uc_client_id,
client_secret = uc_client_secret,
access_token = uc_access_token,
api_base_url = 'https://' + mastodon_hostname,
)
def run(mastodon, log):
log.info("Start streaming")
listener = BotListener(mastodon, logging)
mastodon.stream_user(listener)
#post_img(mastodon, "NSFW", 1)
def main():
config_file = "config.txt"
secrets_filepath = "secrets/secrets.txt"
init(config_file, secrets_filepath)
parser = argparse.ArgumentParser()
parser.add_argument('command', type=str, choices=['img', 'stream'])
args = parser.parse_args()
if args.command == 'img':
post_img(mastodon, "NSFW", 1, log)
elif args.command == 'stream':
run(mastodon, log)
main()