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

246 lines
8.4 KiB
Python
Raw Normal View History

2023-06-21 17:39:33 +03:00
import logging
2023-06-21 23:03:52 +03:00
from datetime import datetime
2023-02-14 17:25:56 +02:00
from os import makedirs, path
2023-03-15 22:58:14 +02:00
from random import choice
2023-03-02 23:38:48 +02:00
from shutil import rmtree
2023-06-22 16:17:44 +03:00
from traceback import format_exc, print_exc
2023-02-14 17:25:56 +02:00
from uuid import uuid4
2023-06-21 23:03:52 +03:00
2023-03-02 23:38:48 +02:00
import aiofiles
2023-06-21 20:28:17 +03:00
from aiohttp import ClientSession
2023-06-21 23:03:52 +03:00
from photosapi_client.errors import UnexpectedStatus
from PIL import Image
2023-06-21 20:28:17 +03:00
from pyrogram.client import Client
2023-02-14 17:25:56 +02:00
2023-06-22 16:17:44 +03:00
from modules.api_client import (
authorize,
client,
photo_find,
photo_get,
photo_patch,
video_find,
video_get,
video_patch,
)
2023-02-14 17:25:56 +02:00
from modules.database import col_sent, col_submitted
2023-06-21 17:39:33 +03:00
logger = logging.getLogger(__name__)
2023-01-10 13:52:44 +02:00
2023-06-21 17:39:33 +03:00
2023-06-21 20:28:17 +03:00
async def send_content(app: Client, http_session: ClientSession) -> None:
2023-01-10 13:52:44 +02:00
try:
2023-02-14 17:25:56 +02:00
try:
2023-06-21 20:28:17 +03:00
token = await authorize(http_session)
2023-02-14 17:25:56 +02:00
except ValueError:
2023-03-09 12:33:02 +02:00
await app.send_message(
app.owner,
2023-06-21 17:39:33 +03:00
app._("api_creds_invalid", "message"),
2023-03-09 12:33:02 +02:00
)
2023-02-14 17:25:56 +02:00
return
2023-01-17 15:11:23 +02:00
2023-02-14 17:25:56 +02:00
try:
2023-06-22 16:17:44 +03:00
funcs = []
if app.config["posting"]["types"]["photo"]:
funcs.append(photo_find)
if (
app.config["posting"]["types"]["video"]
or app.config["posting"]["types"]["animation"]
):
funcs.append(video_find)
func = choice(funcs)
media = choice(
2023-06-21 20:28:17 +03:00
(
2023-06-22 16:17:44 +03:00
await func(
2023-06-21 20:28:17 +03:00
album=app.config["posting"]["api"]["album"],
caption="queue",
page_size=app.config["posting"]["page_size"],
client=client,
)
).results
)
2023-06-21 22:43:23 +03:00
except (KeyError, AttributeError, TypeError, IndexError):
2023-06-21 17:39:33 +03:00
logger.info(app._("post_empty", "console"))
if app.config["reports"]["error"]:
2023-03-09 12:33:02 +02:00
await app.send_message(
app.owner,
2023-06-21 17:39:33 +03:00
app._("api_queue_empty", "message"),
2023-03-09 12:33:02 +02:00
)
2023-02-14 17:25:56 +02:00
return
2023-06-21 17:39:33 +03:00
except (ValueError, UnexpectedStatus):
if app.config["reports"]["error"]:
2023-03-09 12:33:02 +02:00
await app.send_message(
app.owner,
2023-06-21 17:39:33 +03:00
app._("api_queue_error", "message"),
2023-03-09 12:33:02 +02:00
)
2023-02-14 17:25:56 +02:00
return
2023-03-09 12:33:02 +02:00
2023-06-22 16:17:44 +03:00
try:
if func is photo_find:
response = await photo_get(id=media.id, client=client)
else:
response = await video_get(id=media.id, client=client)
except Exception as exp:
print_exc()
2023-06-21 17:39:33 +03:00
logger.warning(
2023-06-22 16:17:44 +03:00
"Media is invalid: %s",
exp
# app._("post_invalid_pic", "console").format(
# response.status, str(await response.json())
# )
2023-03-09 12:33:02 +02:00
)
2023-06-21 17:39:33 +03:00
if app.config["reports"]["error"]:
2023-06-22 16:17:44 +03:00
await app.send_message(app.owner, f"Media is invalid: {exp}")
return
# await app.send_message(
# app.owner,
# app._("post_invalid_pic", "message").format(
# response.status, await response.json()
# ),
# )
2023-01-17 15:11:23 +02:00
2023-02-14 17:25:56 +02:00
tmp_dir = str(uuid4())
2023-01-17 15:11:23 +02:00
2023-06-21 20:28:17 +03:00
makedirs(path.join(app.config["locations"]["tmp"], tmp_dir), exist_ok=True)
2023-01-17 15:11:23 +02:00
2023-06-22 16:17:44 +03:00
tmp_path = path.join(tmp_dir, media.filename)
2023-01-17 15:11:23 +02:00
2023-03-09 12:33:02 +02:00
async with aiofiles.open(
2023-06-21 20:28:17 +03:00
path.join(app.config["locations"]["tmp"], tmp_path), "wb"
2023-03-09 12:33:02 +02:00
) as out_file:
2023-06-22 16:17:44 +03:00
await out_file.write(response.payload.read())
2023-01-17 15:11:23 +02:00
2023-06-21 17:39:33 +03:00
logger.info(
2023-06-22 16:17:44 +03:00
f"Candidate {media.filename} ({media.id}) is {path.getsize(path.join(app.config['locations']['tmp'], tmp_path))} bytes big",
2023-03-09 12:33:02 +02:00
)
2023-02-17 17:46:44 +02:00
2023-06-22 16:17:44 +03:00
if (
path.getsize(path.join(app.config["locations"]["tmp"], tmp_path)) > 5242880
) and func is photo_find:
2023-06-21 20:28:17 +03:00
image = Image.open(path.join(app.config["locations"]["tmp"], tmp_path))
2023-02-17 17:46:44 +02:00
width, height = image.size
2023-03-09 12:33:02 +02:00
image = image.resize((int(width / 2), int(height / 2)), Image.ANTIALIAS)
2023-02-17 17:46:44 +02:00
if tmp_path.lower().endswith(".jpeg") or tmp_path.lower().endswith(".jpg"):
2023-03-09 12:33:02 +02:00
image.save(
2023-06-21 20:28:17 +03:00
path.join(app.config["locations"]["tmp"], tmp_path),
2023-03-09 12:33:02 +02:00
"JPEG",
optimize=True,
quality=50,
)
2023-02-17 17:46:44 +02:00
elif tmp_path.lower().endswith(".png"):
2023-03-09 12:33:02 +02:00
image.save(
2023-06-21 20:28:17 +03:00
path.join(app.config["locations"]["tmp"], tmp_path),
2023-03-09 12:33:02 +02:00
"PNG",
optimize=True,
compress_level=8,
)
2023-02-17 17:46:44 +02:00
image.close()
2023-03-09 12:33:02 +02:00
2023-06-22 16:17:44 +03:00
if (
path.getsize(path.join(app.config["locations"]["tmp"], tmp_path)) > 5242880
) and func is photo_find:
2023-03-09 12:33:02 +02:00
rmtree(
2023-06-21 20:28:17 +03:00
path.join(app.config["locations"]["tmp"], tmp_dir), ignore_errors=True
2023-03-09 12:33:02 +02:00
)
2023-02-17 17:46:44 +02:00
raise BytesWarning
2023-02-14 17:25:56 +02:00
del response
2023-01-10 13:52:44 +02:00
2023-06-22 16:17:44 +03:00
submitted = col_submitted.find_one({"temp.file": media.filename})
2023-01-10 13:52:44 +02:00
2023-02-18 00:18:34 +02:00
if submitted is not None and submitted["caption"] is not None:
caption = submitted["caption"].strip()
2023-01-10 13:52:44 +02:00
else:
caption = ""
2023-03-09 12:33:02 +02:00
if (
submitted is not None
2023-06-21 17:39:33 +03:00
and app.config["posting"]["submitted_caption"]["enabled"]
2023-03-09 12:33:02 +02:00
and (
(submitted["user"] not in app.admins)
2023-06-21 20:28:17 +03:00
or (
app.config["posting"]["submitted_caption"]["ignore_admins"] is False
)
2023-03-09 12:33:02 +02:00
)
2023-02-24 20:48:06 +02:00
):
2023-03-09 12:33:02 +02:00
caption = (
2023-06-21 17:39:33 +03:00
f"{caption}\n\n{app.config['posting']['submitted_caption']['text']}\n"
2023-03-09 12:33:02 +02:00
)
2023-02-24 19:39:33 +02:00
else:
caption = f"{caption}\n\n"
2023-06-21 17:39:33 +03:00
if app.config["caption"]["enabled"]:
if app.config["caption"]["link"] is not None:
caption = f"{caption}[{choice(app.config['caption']['text'])}]({app.config['caption']['link']})"
2023-01-10 13:52:44 +02:00
else:
2023-06-21 17:39:33 +03:00
caption = f"{caption}{choice(app.config['caption']['text'])}"
2023-01-10 13:52:44 +02:00
else:
caption = caption
2023-02-14 17:25:56 +02:00
try:
2023-06-22 16:17:44 +03:00
if func is photo_find:
sent = await app.send_photo(
app.config["posting"]["channel"],
path.join(app.config["locations"]["tmp"], tmp_path),
caption=caption,
disable_notification=app.config["posting"]["silent"],
)
else:
sent = await app.send_video(
app.config["posting"]["channel"],
path.join(app.config["locations"]["tmp"], tmp_path),
caption=caption,
disable_notification=app.config["posting"]["silent"],
)
2023-02-14 17:25:56 +02:00
except Exception as exp:
2023-06-22 16:17:44 +03:00
logger.error(
f"Could not send media {media.filename} ({media.id}) due to {exp}"
)
2023-06-21 17:39:33 +03:00
if app.config["reports"]["error"]:
2023-03-09 12:33:02 +02:00
await app.send_message(
app.owner,
2023-06-21 17:39:33 +03:00
app._("post_exception", "message").format(exp, format_exc()),
2023-03-09 12:33:02 +02:00
)
2023-06-21 17:39:33 +03:00
# rmtree(path.join(app.config['locations']['tmp'], tmp_dir), ignore_errors=True)
2023-02-14 17:25:56 +02:00
return
2023-01-10 13:52:44 +02:00
2023-02-14 17:25:56 +02:00
col_sent.insert_one(
{
2023-02-17 22:55:38 +02:00
"date": datetime.now(),
2023-06-22 16:17:44 +03:00
"image": media.id,
"filename": media.filename,
2023-06-21 17:39:33 +03:00
"channel": app.config["posting"]["channel"],
2023-03-09 12:33:02 +02:00
"caption": None
if (submitted is None or submitted["caption"] is None)
else submitted["caption"].strip(),
2023-02-14 17:25:56 +02:00
}
)
2023-01-10 13:52:44 +02:00
2023-06-22 16:17:44 +03:00
func_patch = photo_patch if func is photo_find else video_patch
await func_patch(id=media.id, client=client, caption="sent")
2023-01-10 13:52:44 +02:00
2023-06-21 20:28:17 +03:00
rmtree(path.join(app.config["locations"]["tmp"], tmp_dir), ignore_errors=True)
2023-01-10 13:52:44 +02:00
2023-06-21 17:39:33 +03:00
logger.info(
app._("post_sent", "console").format(
2023-06-22 16:17:44 +03:00
media.id,
2023-06-21 17:39:33 +03:00
str(app.config["posting"]["channel"]),
2023-03-09 12:33:02 +02:00
caption.replace("\n", "%n"),
2023-06-21 17:39:33 +03:00
str(app.config["posting"]["silent"]),
2023-03-09 12:33:02 +02:00
)
)
2023-01-10 13:52:44 +02:00
2023-02-14 17:25:56 +02:00
except Exception as exp:
2023-06-21 17:39:33 +03:00
logger.error(app._("post_exception", "console").format(str(exp), format_exc()))
if app.config["reports"]["error"]:
2023-03-09 12:33:02 +02:00
await app.send_message(
app.owner,
2023-06-21 17:39:33 +03:00
app._("post_exception", "message").format(exp, format_exc()),
2023-03-09 12:33:02 +02:00
)
2023-02-17 17:46:44 +02:00
try:
2023-03-09 12:33:02 +02:00
rmtree(
2023-06-21 20:28:17 +03:00
path.join(app.config["locations"]["tmp"], tmp_dir), ignore_errors=True
2023-03-09 12:33:02 +02:00
)
2023-02-17 17:46:44 +02:00
except:
2023-03-09 12:33:02 +02:00
pass