API usage overhaul #27
@ -1,33 +1,33 @@
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from os import makedirs, path
|
||||
from random import choice
|
||||
from random import choice, sample
|
||||
from shutil import rmtree
|
||||
from traceback import format_exc, print_exc
|
||||
from uuid import uuid4
|
||||
|
||||
import aiofiles
|
||||
from aiohttp import ClientSession
|
||||
from libbot.pyrogram.classes import PyroClient
|
||||
from photosapi_client.errors import UnexpectedStatus
|
||||
from PIL import Image
|
||||
from pyrogram.client import Client
|
||||
|
||||
from modules.api_client import (
|
||||
authorize,
|
||||
client,
|
||||
photo_find,
|
||||
photo_get,
|
||||
photo_patch,
|
||||
video_find,
|
||||
photo_random,
|
||||
video_get,
|
||||
video_patch,
|
||||
video_random,
|
||||
)
|
||||
from modules.database import col_sent, col_submitted
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def send_content(app: Client, http_session: ClientSession) -> None:
|
||||
async def send_content(app: PyroClient, http_session: ClientSession) -> None:
|
||||
try:
|
||||
try:
|
||||
token = await authorize(http_session)
|
||||
@ -40,25 +40,67 @@ async def send_content(app: Client, http_session: ClientSession) -> None:
|
||||
|
||||
try:
|
||||
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(
|
||||
(
|
||||
await func(
|
||||
print(funcs)
|
||||
|
||||
if app.config["posting"]["types"]["photo"]:
|
||||
funcs.append((photo_random, photo_get, app.send_photo, photo_patch))
|
||||
|
||||
if app.config["posting"]["types"]["video"]:
|
||||
funcs.append((video_random, video_get, app.send_video, video_patch))
|
||||
|
||||
print(funcs)
|
||||
|
||||
if not funcs:
|
||||
raise KeyError(
|
||||
"No media source provided: all seem to be disabled in config"
|
||||
)
|
||||
|
||||
if len(funcs) > 1:
|
||||
found = False
|
||||
for func_iter in sample(funcs, len(funcs)):
|
||||
func = func_iter
|
||||
media = (
|
||||
await func_iter[0](
|
||||
album=app.config["posting"]["api"]["album"],
|
||||
caption="queue",
|
||||
client=client,
|
||||
limit=1,
|
||||
)
|
||||
).results[0]
|
||||
try:
|
||||
response = await func_iter[1](id=media.id, client=client)
|
||||
except Exception as exp:
|
||||
print_exc()
|
||||
logger.error("Media is invalid: %s", exp)
|
||||
if app.config["reports"]["error"]:
|
||||
await app.send_message(
|
||||
app.owner, f"Media is invalid: {exp}"
|
||||
)
|
||||
return
|
||||
found = True
|
||||
break
|
||||
if not found:
|
||||
raise KeyError("No media found")
|
||||
else:
|
||||
func = funcs[0]
|
||||
media = (
|
||||
await func[0](
|
||||
album=app.config["posting"]["api"]["album"],
|
||||
caption="queue",
|
||||
page_size=app.config["posting"]["page_size"],
|
||||
client=client,
|
||||
limit=1,
|
||||
)
|
||||
).results
|
||||
)
|
||||
).results[0]
|
||||
try:
|
||||
response = await func[1](id=media.id, client=client)
|
||||
except Exception as exp:
|
||||
print_exc()
|
||||
logger.error("Media is invalid: %s", exp)
|
||||
if app.config["reports"]["error"]:
|
||||
await app.send_message(app.owner, f"Media is invalid: {exp}")
|
||||
return
|
||||
|
||||
except (KeyError, AttributeError, TypeError, IndexError):
|
||||
logger.info(app._("post_empty", "console"))
|
||||
if app.config["reports"]["error"]:
|
||||
@ -67,6 +109,7 @@ async def send_content(app: Client, http_session: ClientSession) -> None:
|
||||
app._("api_queue_empty", "message"),
|
||||
)
|
||||
return
|
||||
|
||||
except (ValueError, UnexpectedStatus):
|
||||
if app.config["reports"]["error"]:
|
||||
await app.send_message(
|
||||
@ -75,30 +118,6 @@ async def send_content(app: Client, http_session: ClientSession) -> None:
|
||||
)
|
||||
return
|
||||
|
||||
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()
|
||||
logger.warning(
|
||||
"Media is invalid: %s",
|
||||
exp
|
||||
# app._("post_invalid_pic", "console").format(
|
||||
# response.status, str(await response.json())
|
||||
# )
|
||||
)
|
||||
if app.config["reports"]["error"]:
|
||||
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()
|
||||
# ),
|
||||
# )
|
||||
|
||||
tmp_dir = str(uuid4())
|
||||
|
||||
makedirs(path.join(app.config["locations"]["tmp"], tmp_dir), exist_ok=True)
|
||||
@ -116,7 +135,7 @@ async def send_content(app: Client, http_session: ClientSession) -> None:
|
||||
|
||||
if (
|
||||
path.getsize(path.join(app.config["locations"]["tmp"], tmp_path)) > 5242880
|
||||
) and func is photo_find:
|
||||
) and func[0] is photo_random:
|
||||
image = Image.open(path.join(app.config["locations"]["tmp"], tmp_path))
|
||||
width, height = image.size
|
||||
image = image.resize((int(width / 2), int(height / 2)), Image.ANTIALIAS)
|
||||
@ -138,7 +157,7 @@ async def send_content(app: Client, http_session: ClientSession) -> None:
|
||||
|
||||
if (
|
||||
path.getsize(path.join(app.config["locations"]["tmp"], tmp_path)) > 5242880
|
||||
) and func is photo_find:
|
||||
) and func[0] is photo_random:
|
||||
rmtree(
|
||||
path.join(app.config["locations"]["tmp"], tmp_dir), ignore_errors=True
|
||||
)
|
||||
@ -178,20 +197,12 @@ async def send_content(app: Client, http_session: ClientSession) -> None:
|
||||
caption = caption
|
||||
|
||||
try:
|
||||
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"],
|
||||
)
|
||||
sent = await func[2](
|
||||
app.config["posting"]["channel"],
|
||||
path.join(app.config["locations"]["tmp"], tmp_path),
|
||||
caption=caption,
|
||||
disable_notification=app.config["posting"]["silent"],
|
||||
)
|
||||
except Exception as exp:
|
||||
logger.error(
|
||||
f"Could not send media {media.filename} ({media.id}) due to {exp}"
|
||||
@ -216,8 +227,7 @@ async def send_content(app: Client, http_session: ClientSession) -> None:
|
||||
}
|
||||
)
|
||||
|
||||
func_patch = photo_patch if func is photo_find else video_patch
|
||||
await func_patch(id=media.id, client=client, caption="sent")
|
||||
await func[3](id=media.id, client=client, caption="sent")
|
||||
|
||||
rmtree(path.join(app.config["locations"]["tmp"], tmp_dir), ignore_errors=True)
|
||||
|
||||
|
Reference in New Issue
Block a user