From b5d430ed37d52e060c6b2572dd98c13e5941152b Mon Sep 17 00:00:00 2001 From: Moon Man Date: Mon, 16 Dec 2024 12:59:26 +0000 Subject: [PATCH] many improvements --- .gitignore | 2 ++ README.md | 22 ++++++++--------- feditree.py | 64 +++++++++++++++++++++++------------------------- requirements.txt | 3 +++ 4 files changed, 46 insertions(+), 45 deletions(-) create mode 100644 requirements.txt diff --git a/.gitignore b/.gitignore index f47d0ac..290bb97 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,5 @@ __pycache__ list token ./*.png +.env +feditree/feditree.png \ No newline at end of file diff --git a/README.md b/README.md index eb7d8c0..327a551 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,17 @@ -# Bots de masto.es +# SPC fork of Bots from masto.es -Aquí se encuentra el código de los bots que se utilizan en masto.es para ayudar con tareas de administración como guiar a los nuevos usuarios, ofrecer funciones adicionales o simplemente servir de pasatiempo. +## Installation -## Apreciabot -Envía un mensaje directo (visibilidad "sólo cuentas mencionadas") a @apreciabot@masto.es incluyendo el usuario que quieres apreciar con el formato "usuario@servidor" (excluyendo el primer "@" para evitar mencionarlo). Añade "croqueta" al final para activar el modo croqueta. +Create a venv and inside of it run: -Basado en el Niceness Bot https://botsin.space/@nicenessbot + pip install -r requirements.txt -## Bienvenibot -Revisa las notificaciones de un usuario con los privilegios suficientes para buscar nuevos registros y envía un mensaje de bienvenida. +## Running feditree +Create a '.env' file containing: -## Requisitos -- Python 3 -- Mastodon.py https://github.com/halcy/Mastodon.py -- Apreciabot: bs4 + FEDI_DOMAIN=your-domain.tld + +Create a file 'token/faggotree' containing your bearer token value + +then just activate your venv or run python from your venv, with 'feditree.py' diff --git a/feditree.py b/feditree.py index 383241f..e922279 100644 --- a/feditree.py +++ b/feditree.py @@ -1,3 +1,5 @@ + +from dotenv import load_dotenv from PIL import Image, ImageFile from common import get_api, get_new_notifications, list_read, list_append import datetime @@ -5,11 +7,12 @@ import gettext import requests import os import sys -import random -import string +import tempfile ImageFile.LOAD_TRUNCATED_IMAGES = True +load_dotenv() + bot_name = "faggotree" coordinates = [ @@ -25,17 +28,9 @@ coordinates = [ (575,650), ] -def generate_random_filename(): - length = random.randint(10, 15) # Random length between 5-15 characters - chars = string.ascii_lowercase + string.digits - filename = ''.join(random.choice(chars) for _ in range(length)) - return filename + '.png' - -temp_image_name = generate_random_filename() -print("generated random image filename: " + temp_image_name) +temp_image_name = (tempfile.NamedTemporaryFile(suffix='.png', delete=False)).name def get_ordered_accounts_ids(account_id): - print("getting ordered accounts ids") current_year = datetime.date.today().year accounts = {} stop = False @@ -47,9 +42,7 @@ def get_ordered_accounts_ids(account_id): if(status.created_at.year < current_year): stop = True break - print("mentions: " + str(len(status.mentions))) for mention in status.mentions: - print(mention.username) if mention.username == bot_name or mention.username == status.account.username: print("skipping: " + mention.username) else: @@ -61,14 +54,12 @@ def get_ordered_accounts_ids(account_id): loops = loops + 1 if loops > 10 : stop = True - print("stopping loop") accounts_list = sorted(accounts, key=accounts.get, reverse=True) accounts_list.insert(0,account_id) accounts_list.pop return accounts_list def get_accounts(accounts_ids): - print("getting accounts: " + str(len(accounts_ids))) accounts = [] for i in range(len(accounts_ids)): account = api.account(accounts_ids[i]) @@ -79,18 +70,15 @@ def get_accounts(accounts_ids): def get_avatar(): try: - print("trying to open: " + temp_image_name) with Image.open(temp_image_name) as avatar: avatar.load() return avatar except: - print("failed to use avatar so using a default") with Image.open('feditree/default.png') as avatar: avatar.load() return avatar def create_image(accounts): - print("Creating image now") with Image.open("feditree/fediverse-christmas-tree.png") as feditree: feditree.load() with Image.open("feditree/bola_radio.png") as bola_radio: @@ -107,7 +95,8 @@ def create_image(accounts): avatar = avatar.resize((100,100)).convert("RGB") avatar.paste(bola_radio, (0,0), bola_radio) feditree.paste(avatar, coordinates[i], bola_mask) - feditree.save("feditree/feditree.png") + tmp_file = (tempfile.NamedTemporaryFile(suffix='.png', delete=False)).name + feditree.save(tmp_file) bola_radio.close() bola_mask.close() avatar.close() @@ -117,21 +106,26 @@ def create_image(accounts): description = description + " " + _("The accounts appear in the tree in the same order as the mentions, from top to bottom and from left to right.") description = description + " " + _("The order symbolizes the number of interactions, from most to least.") description = description + "\n\n" + _("The Fediverse logo was created by @eudaimon@fe.disroot.org and the tree design was obtained from https://freesvgdesigns.com") - return api.media_post("feditree/feditree.png", description=description) + ret = api.media_post(tmp_file, description=description) + try: + os.remove(tmp_file) + except Exception: + pass + return ret + +def get_filtered_notifications(): + return [n for n in get_new_notifications(api, bot_name, ["mention"]) if n.status.visibility in ["public", "unlisted"]] localedir = './locales' -api = get_api('shitposter.world', bot_name) -print("getting notifications") -notifications = get_new_notifications(api, bot_name, ["mention"]) -print("getting previous ids") +api = get_api(os.getenv("FEDI_DOMAIN"), bot_name) +notifications = get_filtered_notifications() previous_ids = list_read(bot_name + "_previous_ids") -print("to handle: " + str(len(notifications))) +i18n = gettext.translation(bot_name, localedir, fallback=True, languages=['en']) +i18n.install() + for notification in notifications: - i18n = gettext.translation(bot_name, localedir, fallback=True, languages=['en']) - i18n.install() - print("handling for: " + notification.account.username) try: if str(notification.account.id) in previous_ids: status = "@" + notification.account.acct + " " @@ -145,7 +139,8 @@ for notification in notifications: image = create_image(accounts) status = _("These are the fags who have adorned the #FaggoTree of") + " @" + notification.account.acct + ":\n\n" for account in accounts: - status += " " + account.acct + "\n" + if account.username != notification.account.username: + status += " - " + account.acct + "\n" api.status_post(status, media_ids=image, visibility="unlisted", in_reply_to_id=notification.status.id) previous_ids.append(notification.account.id) except Exception as e: @@ -155,8 +150,9 @@ for notification in notifications: print(e) api.status_post(_("An error ocurred. Please try again or contact my creator"), visibility="direct", in_reply_to_id=notification.status.id) -print("deleting temp image file") -try: - os.remove(temp_image_name) -except Exception: - print(f"File {temp_image_name} does not exist") + +if os.path.exists(temp_image_name): + try: + os.remove(temp_image_name) + except Exception: + pass diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..deebbf4 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +python-dotenv +Mastodon.py +pillow \ No newline at end of file