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

89 lines
3.0 KiB
Python
Executable File

#!/usr/bin/python3
# coding: utf-8
# -*- coding: utf-8 -*-
# A Fediverse (decentralized social network, for instance using Mastodon) bot
from mastodon import StreamListener
from lxml import html
from logging.handlers import RotatingFileHandler
from pprint import pprint
from utils.config import get_parameter, init_log, init_mastodon
import requests, os, random, sys, time, json, logging, argparse, re
config_file = "config.txt"
secrets_filepath = "secrets/secrets.txt"
log_filepath = "activity.log"
log = init_log(log_filepath)
bot_name = "nosafe"
mastodon = init_mastodon(config_file, secrets_filepath)
def post_img(mastodon, text, visibility, log, config):
img_path = get_parameter("img_path", config)
file = random.choice(os.listdir(img_path+"/"))
image_byte = open(img_path+"/"+file, "rb").read()
file, ext = os.path.splitext(file)
mime_dict = {'.jpg': 'image/jpeg', '.jpe': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.gif': 'image/gif'}
mime = mime_dict[str.lower(ext)]
#try:
#except KeyError:
# mime = None;
# pass
media_dict = mastodon.media_post(image_byte, mime)
return media_dict;
def cleanhtml(raw_html):
cleanr = re.compile('<.*?>')
cleantext = re.sub(cleanr, '', raw_html)
return cleantext
class BotListener(StreamListener):
def on_notification(self, notification):
if notification['type'] == 'mention':
log.debug("Got a mention")
id = notification['status']['id']
sender = notification['account']['acct']
visibility = notification['status']['visibility']
mentions = notification['status']['mentions']
text = "@" + notification['status']["account"]["acct"] + " "
for mention in mentions:
if mention["acct"] != bot_name:
text = text + "@" + mention["acct"] + " "
media_dict = post_img(mastodon, "NSFW", 1, log, config_file)
mastodon.status_post(text, None, media_ids=[media_dict], sensitive=True, visibility=visibility, spoiler_text="#NSFW")
else:
log.debug("Nevermind")
def main():
parser = argparse.ArgumentParser(description='Choose between image or streaming')
parser.add_argument("-i", "--img", action='store_true', help="post image")
parser.add_argument("-s", "--stream", action="store_true", help="stream user profile")
args = parser.parse_args()
if args.img:
media_dict = post_img(mastodon, "NSFW", 1, log, config_file)
mastodon.status_post("", None, media_ids=[media_dict], sensitive=True, visibility='public', spoiler_text="#NSFW")
sys.exit()
elif args.stream:
stream = BotListener();
while True:
try:
log.info("Start listening...")
mastodon.stream_user(stream, async=False)
except Exception as error:
log.warning('General exception caught: ' + str(error))
time.sleep(0.5)
else:
print("Require an argument. Use --help to display help")
main()