add distant image #3

This commit is contained in:
Dryusdan 2018-06-22 22:08:06 +02:00
parent 8fc886351f
commit 8e7f69ecc7
6 changed files with 102 additions and 49 deletions

2
.gitignore vendored
View File

@ -4,3 +4,5 @@ config.txt
__pycache__/*
TootHTMLParser.pyc
blacklist.json
collection.json
output.jpg

View File

@ -11,15 +11,20 @@ Copy `config.sample.txt` to `config.txt` and replace data by your data.
If you don't want any "spoiler text", just leave the line empty.
| **Field name** | Description | Value |
| -------------- | ---------------------------------------------------------------------- | ---------------------- |
| img_path | Path where image are located | /home/bot/img | ../bot |
| name | Name of your bot (name after @). Is usefull to hide it's name in reply | mybot |
| sensitive | Hide picture behind "sensitive content" mask or not | yes | no |
| default_text | Text for --img option | string |
| spoiler_text | Text for every spoiler (or CW) (for --img or --stream option) | string |
| limit | Limit send per minute per person | int |
| limit_hour | Limit send par hour per person | int |
| **Field name** | Description | Value |
| ------------------- | --------------------------------------------------------------------------------------------------------------------------- | ---------------------- |
| img_path | Path where image are located | /home/bot/img | ../bot |
| name | Name of your bot (name after @). Is usefull to hide it's name in reply | mybot |
| secrets_filepath | Path where located secret | secrets/secrets.txt |
| log_filepath | Path where located log file | activity.log |
| blacklist_filepath | Path where located blacklist file | blacklist.json |
| collection_filepath | Path where located distant image collection | collection.json |
| sensitive | Hide picture behind "sensitive content" mask or not | yes | no |
| default_text | Text for --img option | string |
| spoiler_text | Text for every spoiler (or CW) (for --img or --stream option) | string |
| limit | Limit send per minute per person | int |
| limit_hour | Limit send par hour per person | int |
| collection_url | URL of website you deserve image. `<collection>` is a variable who depend on collection.json (you can remove this variable) | string |
Copy `blacklist.sample.json` to `blacklist.json` and replace or add accounts that should not receive any image

118
bot.py
View File

@ -7,14 +7,18 @@ from mastodon import StreamListener
from lxml import html
from logging.handlers import RotatingFileHandler
from pprint import pprint
from random import randint
from utils.config import get_parameter, init_log, init_mastodon
from PIL import Image
from io import BytesIO
import requests, os, random, sys, time, json, logging, argparse, re
config_file = "config.txt"
secrets_filepath = "secrets/secrets.txt"
log_filepath = "activity.log"
blacklist_filepath = "blacklist.json"
config_file = "config.txt"
secrets_filepath = get_parameter("secrets_filepath", config_file)
log_filepath = get_parameter("log_filepath", config_file)
blacklist_filepath = get_parameter("blacklist_filepath", config_file)
collection_filepath = get_parameter("collection_filepath", config_file)
log = init_log(log_filepath)
mastodon = init_mastodon(config_file, secrets_filepath)
@ -22,23 +26,43 @@ blacklist_file = open(blacklist_filepath,'r')
BLACKLIST = json.loads(blacklist_file.read())
blacklist_file.close()
mime_dict = {'.jpg': 'image/jpeg', '.jpe': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.gif': 'image/gif'}
def post_img(mastodon, text, log, config):
img_path = get_parameter("img_path", config)
file = random.choice(os.listdir(img_path+"/"))
image_byte = open(img_path+"/"+file, "rb").read()
def post_img_local(mastodon, text, 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'}
file, ext = os.path.splitext(file)
mime = mime_dict[str.lower(ext)]
#try:
#mime = mime_dict[str.lower(ext)]
try:
mime = mime_dict[str.lower(ext)]
except KeyError:
mime = None;
log.error(ext + " is not present on mime_dict, please add this")
pass
#except KeyError:
# mime = None;
# pass
media_dict = mastodon.media_post(image_byte, mime)
return media_dict;
media_dict = mastodon.media_post(image_byte, mime)
def post_img_distant(mastodon, text, log, config):
collection_url = get_parameter("collection_url", config)
collecion_file = open(collection_filepath,'r')
collections = json.loads(collecion_file.read())
collecion_file.close()
count_collection = len(collections)-1
id_collection = randint(0,count_collection)
collection_url = collection_url.replace("<collection>", str(collections[id_collection]))
response = requests.get(collection_url)
pattern = Image.open(BytesIO(response.content), "r").convert('RGB')
pattern.save('output.jpg')
media_dict = mastodon.media_post("output.jpg")
return media_dict;
def cleanhtml(raw_html):
@ -48,6 +72,9 @@ def cleanhtml(raw_html):
class BotListener(StreamListener):
def __init__(self, args):
self.args = args
# use only notification
def on_notification(self, notification):
@ -147,7 +174,12 @@ class BotListener(StreamListener):
sensitive = True
else:
sensitive = False
media_dict = post_img(mastodon, get_parameter("default_text", config_file), log, config_file)
if self.args.source == "local":
media_dict = post_img_local(mastodon, get_parameter("default_text", config_file), log, config_file)
elif self.args.source == "distant":
media_dict = post_img_distant(mastodon, get_parameter("default_text", config_file), log, config_file)
mastodon.status_post(text, None, media_ids=[media_dict], sensitive=sensitive, visibility=visibility, spoiler_text=get_parameter("spoiler_text", config_file))
else:
log.debug("no picture send :(")
@ -158,29 +190,35 @@ class BotListener(StreamListener):
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, get_parameter("default_text", config_file), log, config_file)
if get_parameter("sensitive", config_file) == "yes":
sensitive = True
else:
sensitive = False
mastodon.status_post(get_parameter("default_text", config_file), None, media_ids=[media_dict], sensitive=sensitive, visibility='public', spoiler_text=get_parameter("spoiler_text", config_file))
sys.exit()
elif args.stream:
stream = BotListener();
while True:
try:
log.info("Start listening...")
mastodon.stream_user(stream)
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")
parser = argparse.ArgumentParser(description='Choose between image or streaming')
parser.add_argument("-i", "--img", action='store_true', help="post image")
parser.add_argument("-s", "--source", help="Source of image [ local | distant ]")
parser.add_argument("--stream", action="store_true", help="stream user profile")
args = parser.parse_args()
if args.img:
if args.source == "local":
media_dict = post_img_local(mastodon, get_parameter("default_text", config_file), log, config_file)
elif args.source == "distant":
media_dict = post_img_distant(mastodon, get_parameter("default_text", config_file), log, config_file)
if get_parameter("sensitive", config_file) == "yes":
sensitive = True
else:
sensitive = False
mastodon.status_post(get_parameter("default_text", config_file), None, media_ids=[media_dict], sensitive=sensitive, visibility='public', spoiler_text=get_parameter("spoiler_text", config_file))
sys.exit()
elif args.stream:
stream = BotListener(args);
while True:
try:
log.info("Start listening...")
mastodon.stream_user(stream)
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()

1
collection.sample.json Normal file
View File

@ -0,0 +1 @@
[]

View File

@ -1,6 +1,12 @@
img_path: uri_path
name_bot: bot
secrets_filepath: secrets/secrets.txt
log_filepath: activity.log
blacklist_filepath: blacklist.json
collection_filepath: collection.json
sensitive: False
default_text: some text here
spoiler_text: some text here
limit: 2
limit_hour: 10
collection_url: https://source.unsplash.com/collection/<collection>/

View File

@ -1,3 +1,4 @@
Mastodon.py
lxml
requests
Pillow