many improvements

This commit is contained in:
Moon Man 2024-12-16 12:59:26 +00:00
parent f525310f1c
commit b5d430ed37
4 changed files with 46 additions and 45 deletions

2
.gitignore vendored
View File

@ -2,3 +2,5 @@ __pycache__
list list
token token
./*.png ./*.png
.env
feditree/feditree.png

View File

@ -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 Create a venv and inside of it run:
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.
Basado en el Niceness Bot https://botsin.space/@nicenessbot pip install -r requirements.txt
## Bienvenibot ## Running feditree
Revisa las notificaciones de un usuario con los privilegios suficientes para buscar nuevos registros y envía un mensaje de bienvenida.
Create a '.env' file containing:
## Requisitos FEDI_DOMAIN=your-domain.tld
- Python 3
- Mastodon.py https://github.com/halcy/Mastodon.py Create a file 'token/faggotree' containing your bearer token value
- Apreciabot: bs4
then just activate your venv or run python from your venv, with 'feditree.py'

View File

@ -1,3 +1,5 @@
from dotenv import load_dotenv
from PIL import Image, ImageFile from PIL import Image, ImageFile
from common import get_api, get_new_notifications, list_read, list_append from common import get_api, get_new_notifications, list_read, list_append
import datetime import datetime
@ -5,11 +7,12 @@ import gettext
import requests import requests
import os import os
import sys import sys
import random import tempfile
import string
ImageFile.LOAD_TRUNCATED_IMAGES = True ImageFile.LOAD_TRUNCATED_IMAGES = True
load_dotenv()
bot_name = "faggotree" bot_name = "faggotree"
coordinates = [ coordinates = [
@ -25,17 +28,9 @@ coordinates = [
(575,650), (575,650),
] ]
def generate_random_filename(): temp_image_name = (tempfile.NamedTemporaryFile(suffix='.png', delete=False)).name
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)
def get_ordered_accounts_ids(account_id): def get_ordered_accounts_ids(account_id):
print("getting ordered accounts ids")
current_year = datetime.date.today().year current_year = datetime.date.today().year
accounts = {} accounts = {}
stop = False stop = False
@ -47,9 +42,7 @@ def get_ordered_accounts_ids(account_id):
if(status.created_at.year < current_year): if(status.created_at.year < current_year):
stop = True stop = True
break break
print("mentions: " + str(len(status.mentions)))
for mention in status.mentions: for mention in status.mentions:
print(mention.username)
if mention.username == bot_name or mention.username == status.account.username: if mention.username == bot_name or mention.username == status.account.username:
print("skipping: " + mention.username) print("skipping: " + mention.username)
else: else:
@ -61,14 +54,12 @@ def get_ordered_accounts_ids(account_id):
loops = loops + 1 loops = loops + 1
if loops > 10 : if loops > 10 :
stop = True stop = True
print("stopping loop")
accounts_list = sorted(accounts, key=accounts.get, reverse=True) accounts_list = sorted(accounts, key=accounts.get, reverse=True)
accounts_list.insert(0,account_id) accounts_list.insert(0,account_id)
accounts_list.pop accounts_list.pop
return accounts_list return accounts_list
def get_accounts(accounts_ids): def get_accounts(accounts_ids):
print("getting accounts: " + str(len(accounts_ids)))
accounts = [] accounts = []
for i in range(len(accounts_ids)): for i in range(len(accounts_ids)):
account = api.account(accounts_ids[i]) account = api.account(accounts_ids[i])
@ -79,18 +70,15 @@ def get_accounts(accounts_ids):
def get_avatar(): def get_avatar():
try: try:
print("trying to open: " + temp_image_name)
with Image.open(temp_image_name) as avatar: with Image.open(temp_image_name) as avatar:
avatar.load() avatar.load()
return avatar return avatar
except: except:
print("failed to use avatar so using a default")
with Image.open('feditree/default.png') as avatar: with Image.open('feditree/default.png') as avatar:
avatar.load() avatar.load()
return avatar return avatar
def create_image(accounts): def create_image(accounts):
print("Creating image now")
with Image.open("feditree/fediverse-christmas-tree.png") as feditree: with Image.open("feditree/fediverse-christmas-tree.png") as feditree:
feditree.load() feditree.load()
with Image.open("feditree/bola_radio.png") as bola_radio: 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 = avatar.resize((100,100)).convert("RGB")
avatar.paste(bola_radio, (0,0), bola_radio) avatar.paste(bola_radio, (0,0), bola_radio)
feditree.paste(avatar, coordinates[i], bola_mask) 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_radio.close()
bola_mask.close() bola_mask.close()
avatar.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 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 + " " + _("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") 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' localedir = './locales'
api = get_api('shitposter.world', bot_name) api = get_api(os.getenv("FEDI_DOMAIN"), bot_name)
print("getting notifications") notifications = get_filtered_notifications()
notifications = get_new_notifications(api, bot_name, ["mention"])
print("getting previous ids")
previous_ids = list_read(bot_name + "_previous_ids") 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: for notification in notifications:
i18n = gettext.translation(bot_name, localedir, fallback=True, languages=['en'])
i18n.install()
print("handling for: " + notification.account.username)
try: try:
if str(notification.account.id) in previous_ids: if str(notification.account.id) in previous_ids:
status = "@" + notification.account.acct + " " status = "@" + notification.account.acct + " "
@ -145,7 +139,8 @@ for notification in notifications:
image = create_image(accounts) image = create_image(accounts)
status = _("These are the fags who have adorned the #FaggoTree of") + " @" + notification.account.acct + ":\n\n" status = _("These are the fags who have adorned the #FaggoTree of") + " @" + notification.account.acct + ":\n\n"
for account in accounts: 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) api.status_post(status, media_ids=image, visibility="unlisted", in_reply_to_id=notification.status.id)
previous_ids.append(notification.account.id) previous_ids.append(notification.account.id)
except Exception as e: except Exception as e:
@ -155,8 +150,9 @@ for notification in notifications:
print(e) print(e)
api.status_post(_("An error ocurred. Please try again or contact my creator"), visibility="direct", in_reply_to_id=notification.status.id) 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: if os.path.exists(temp_image_name):
os.remove(temp_image_name) try:
except Exception: os.remove(temp_image_name)
print(f"File {temp_image_name} does not exist") except Exception:
pass

3
requirements.txt Normal file
View File

@ -0,0 +1,3 @@
python-dotenv
Mastodon.py
pillow