Un bot qui récupère une image random en local et la publie
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
3.0 KiB

# 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)]
#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")
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")
elif args.stream:
stream = BotListener();
while True:
log.info("Start listening...")
mastodon.stream_user(stream, async=False)
except Exception as error:
log.warning('General exception caught: ' + str(error))
print("Require an argument. Use --help to display help")