This repository has been archived on 2024-08-21. You can view files and clone it, but cannot push or open issues or pull requests.
TelegramPoster/modules/sender.py

127 lines
5.7 KiB
Python

from datetime import datetime
from os import makedirs, path
from shutil import copyfileobj, rmtree
from traceback import format_exc
from uuid import uuid4
from PIL import Image
from classes.poster_client import PosterClient
from requests import get
from modules.api_client import authorize, move_pic, random_pic
from modules.database import col_sent, col_submitted
from modules.logger import logWrite
from modules.utils import configGet, locale
async def send_content(app: PosterClient) -> None:
try:
try:
token = await authorize()
except ValueError:
await app.send_message(app.owner, locale("api_creds_invalid", "message", locale=configGet("locale")))
return
try:
pic = await random_pic()
except KeyError:
logWrite(locale("post_empty", "console", locale=configGet("locale")))
if configGet("error", "reports"):
await app.send_message(app.owner, locale("api_queue_empty", "message", locale=configGet("locale")))
return
except ValueError:
if configGet("error", "reports"):
await app.send_message(app.owner, locale("api_queue_error", "message", locale=configGet("locale")))
return
response = get(f'{configGet("address", "posting", "api")}/photos/{pic[0]}', headers={"Authorization": f"Bearer {token}"}, stream=True)
if response.status_code != 200:
logWrite(locale("post_invalid_pic", "console", locale=configGet("locale")).format(str(response.json())))
if configGet("error", "reports"):
await app.send_message(app.owner, locale("post_invalid_pic", "message", locale=configGet("locale")).format(response.json()))
tmp_dir = str(uuid4())
makedirs(path.join(configGet("tmp", "locations"), tmp_dir), exist_ok=True)
tmp_path = path.join(tmp_dir, pic[1])
with open(path.join(configGet("tmp", "locations"), tmp_path), 'wb') as out_file:
copyfileobj(response.raw, out_file)
logWrite(f'Candidate {pic[1]} ({pic[0]}) is {path.getsize(path.join(configGet("tmp", "locations"), tmp_path))} bytes big', debug=True)
if path.getsize(path.join(configGet("tmp", "locations"), tmp_path)) > 5242880:
image = Image.open(path.join(configGet("tmp", "locations"), tmp_path))
width, height = image.size
image = image.resize((int(width/2), int(height/2)), Image.ANTIALIAS)
if tmp_path.lower().endswith(".jpeg") or tmp_path.lower().endswith(".jpg"):
image.save(path.join(configGet("tmp", "locations"), tmp_path), "JPEG", optimize=True, quality=50)
elif tmp_path.lower().endswith(".png"):
image.save(path.join(configGet("tmp", "locations"), tmp_path), "PNG", optimize=True, compress_level=8)
image.close()
if path.getsize(path.join(configGet("tmp", "locations"), tmp_path)) > 5242880:
rmtree(path.join(configGet("tmp", "locations"), tmp_dir), ignore_errors=True)
raise BytesWarning
del response
submitted = col_submitted.find_one({"temp.file": pic[1]})
if submitted is not None and submitted["caption"] is not None:
caption = submitted["caption"].strip()
else:
caption = ""
if submitted is not None and configGet("enabled", "posting", "submitted_caption") and (
(submitted["user"] not in app.admins) or (configGet("ignore_admins", "posting", "submitted_caption") is False)
):
caption = f"{caption}\n\n{configGet('text', 'posting', 'submitted_caption')}\n"
else:
caption = f"{caption}\n\n"
if configGet("enabled", "caption"):
if configGet("link", "caption") != None:
caption = f"{caption}[{configGet('text', 'caption')}]({configGet('link', 'caption')})"
else:
caption = f"{caption}{configGet('text', 'caption')}"
else:
caption = caption
try:
sent = await app.send_photo(configGet("channel", "posting"), path.join(configGet("tmp", "locations"), tmp_path), caption=caption, disable_notification=configGet("silent", "posting"))
except Exception as exp:
logWrite(f"Could not send image {pic[1]} ({pic[0]}) due to {exp}")
if configGet("error", "reports"):
await app.send_message(app.owner, locale("post_exception", "message", locale=configGet("locale")).format(exp, format_exc()))
# rmtree(path.join(configGet("tmp", "locations"), tmp_dir), ignore_errors=True)
return
col_sent.insert_one(
{
"date": datetime.now(),
"image": pic[0],
"filename": pic[1],
"channel": configGet("channel", "posting"),
"caption": None if (submitted is None or submitted["caption"] is None) else submitted["caption"].strip()
}
)
await move_pic(pic[0])
rmtree(path.join(configGet("tmp", "locations"), tmp_dir), ignore_errors=True)
logWrite(locale("post_sent", "console", locale=configGet("locale")).format(pic[0], str(configGet("channel", "posting")), caption.replace("\n", "%n"), str(configGet("silent", "posting"))))
except Exception as exp:
logWrite(locale("post_exception", "console", locale=configGet("locale")).format(str(exp), format_exc()))
if configGet("error", "reports"):
await app.send_message(app.owner, locale("post_exception", "message", locale=configGet("locale")).format(exp, format_exc()))
try:
rmtree(path.join(configGet("tmp", "locations"), tmp_dir), ignore_errors=True)
except:
pass