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

255 lines
11 KiB
Python
Raw Normal View History

2023-02-14 17:25:56 +02:00
from datetime import datetime, timezone
from os import makedirs, path
from shutil import copyfileobj, rmtree
2023-01-10 13:52:44 +02:00
from traceback import format_exc
2023-02-14 17:25:56 +02:00
from uuid import uuid4
2023-02-17 17:46:44 +02:00
from PIL import Image
2023-02-14 17:25:56 +02:00
from bson import ObjectId
2023-02-17 17:46:44 +02:00
from classes.poster_client import PosterClient
2023-02-14 17:25:56 +02:00
from requests import get
2023-01-17 15:11:23 +02:00
from modules.api_client import authorize, move_pic, random_pic
2023-02-14 17:25:56 +02:00
from modules.database import col_sent, col_submitted
from modules.logger import logWrite
from modules.utils import configGet, locale
2023-01-10 13:52:44 +02:00
2023-02-17 17:46:44 +02:00
async def send_content(app: PosterClient):
2023-01-10 13:52:44 +02:00
try:
2023-02-14 17:25:56 +02:00
try:
token = await authorize()
except ValueError:
await app.send_message(configGet("admin"), locale("api_creds_invalid", "message", locale=configGet("locale")))
return
2023-01-17 15:11:23 +02:00
2023-02-14 17:25:56 +02:00
try:
pic = await random_pic()
except KeyError:
logWrite(locale("post_empty", "console", locale=configGet("locale")))
if configGet("error", "reports"):
await app.send_message(configGet("admin"), locale("api_queue_empty", "message", locale=configGet("locale")))
return
except ValueError:
if configGet("error", "reports"):
await app.send_message(configGet("admin"), 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)
2023-01-17 15:11:23 +02:00
2023-02-14 17:25:56 +02:00
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(configGet("admin"), locale("post_invalid_pic", "message", locale=configGet("locale")).format(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-02-14 17:25:56 +02:00
makedirs(path.join(configGet("tmp", "locations"), tmp_dir), exist_ok=True)
2023-01-17 15:11:23 +02:00
2023-02-14 17:25:56 +02:00
tmp_path = path.join(tmp_dir, pic[1])
2023-01-17 15:11:23 +02:00
2023-02-14 17:25:56 +02:00
with open(path.join(configGet("tmp", "locations"), tmp_path), 'wb') as out_file:
copyfileobj(response.raw, out_file)
2023-01-17 15:11:23 +02:00
2023-02-17 17:46:44 +02:00
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
2023-02-14 17:25:56 +02:00
del response
2023-01-10 13:52:44 +02:00
2023-02-14 17:25:56 +02:00
submitted_caption = col_submitted.find_one( {"image": ObjectId(pic[0])} )
2023-01-10 13:52:44 +02:00
2023-02-14 17:25:56 +02:00
if submitted_caption is not None:
caption = submitted_caption["caption"].strip()
2023-01-10 13:52:44 +02:00
else:
caption = ""
if configGet("enabled", "caption"):
if configGet("link", "caption") != None:
caption = f"{caption}\n\n[{configGet('text', 'caption')}]({configGet('link', 'caption')})"
else:
caption = f"{caption}\n\n{configGet('text', 'caption')}"
else:
caption = caption
2023-02-14 17:25:56 +02:00
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(configGet("admin"), locale("post_exception", "message", locale=configGet("locale")).format(exp, format_exc()))
# rmtree(path.join(configGet("tmp", "locations"), tmp_dir), ignore_errors=True)
return
2023-01-10 13:52:44 +02:00
2023-02-14 17:25:56 +02:00
col_sent.insert_one(
{
"date": datetime.now(tz=timezone.utc),
"image": pic[0],
"filename": pic[1],
"channel": configGet("channel", "posting"),
"caption": None if submitted_caption is None else submitted_caption["caption"].strip()
}
)
2023-01-10 13:52:44 +02:00
2023-02-14 17:25:56 +02:00
await move_pic(pic[0])
2023-01-10 13:52:44 +02:00
2023-02-14 17:25:56 +02:00
rmtree(path.join(configGet("tmp", "locations"), tmp_dir), ignore_errors=True)
2023-01-10 13:52:44 +02:00
2023-02-14 17:25:56 +02:00
logWrite(locale("post_sent", "console", locale=configGet("locale")).format(pic[0], str(configGet("channel", "posting")), caption.replace("\n", "%n"), str(configGet("silent", "posting"))))
2023-01-10 13:52:44 +02:00
2023-02-14 17:25:56 +02:00
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(configGet("admin"), locale("post_exception", "message", locale=configGet("locale")).format(exp, format_exc()))
2023-02-17 17:46:44 +02:00
try:
rmtree(path.join(configGet("tmp", "locations"), tmp_dir), ignore_errors=True)
except:
pass
2023-01-17 15:11:23 +02:00
2023-01-10 13:52:44 +02:00
2023-02-17 17:46:44 +02:00
# async def send_content_old(app: PosterClient):
2023-01-10 13:52:44 +02:00
2023-02-14 17:25:56 +02:00
# # Send post to channel
# try:
2023-01-10 13:52:44 +02:00
2023-02-14 17:25:56 +02:00
# index = jsonLoad(configGet("index", "locations"))
2023-01-10 13:52:44 +02:00
2023-02-14 17:25:56 +02:00
# if configGet("api_based", "mode"):
2023-01-10 13:52:44 +02:00
2023-02-14 17:25:56 +02:00
# try:
# pic = random_pic()
# except:
# logWrite(locale("post_empty", "console", locale=configGet("locale")))
# if configGet("error", "reports"):
# await app.send_message(configGet("admin"), locale("post_empty", "message", locale=configGet("locale")))
# return
# token = authorize()
# response = get(f'{configGet("address", "posting", "api")}/photos/{pic[0]}', headers={"Authorization": f"Bearer {token}"}, stream=True)
# with open(configGet("tmp", "locations")+sep+pic[0]+".jpg", 'wb') as out_file:
# copyfileobj(response.raw, out_file)
# del response
# candidate = configGet("tmp", "locations")+sep+pic[0]+".jpg"
# candidate_file = pic[1]
# ext_type = "photo"
# if not configGet("api_based", "mode"):
# list_queue = listdir(configGet("queue", "locations"))
# for file in list_queue:
# if not file in index["sent"]:
# ext_match = False
# for ext in configGet("photo", "posting", "extensions"):
# if file.endswith(ext):
# ext_match = True
# ext_type = "photo"
# break
# for ext in configGet("video", "posting", "extensions"):
# if file.endswith(ext):
# ext_match = True
# ext_type = "video"
# break
# if not ext_match:
# list_queue.remove(file)
# else:
# list_queue.remove(file)
# if len(list_queue) > 0:
# candidate_file = choice(list_queue)
# candidate = configGet("queue", "locations")+sep+candidate_file
# else:
# logWrite(locale("post_empty", "console", locale=configGet("locale")))
# if configGet("error", "reports"):
# await app.send_message(configGet("admin"), locale("post_empty", "message", locale=configGet("locale")))
# return
# if candidate_file in index["captions"]:
# caption = index["captions"][candidate_file]
# else:
# caption = ""
# if configGet("enabled", "caption"):
# if configGet("link", "caption") != None:
# caption = f"{caption}\n\n[{configGet('text', 'caption')}]({configGet('link', 'caption')})"
# else:
# caption = f"{caption}\n\n{configGet('text', 'caption')}"
# else:
# caption = caption
# if ext_type == "photo":
# if configGet("enabled", "caption"):
# if configGet("link", "caption") != None:
# sent = await app.send_photo(configGet("channel", "posting"), candidate, caption=caption, disable_notification=configGet("silent", "posting"))
# else:
# sent = await app.send_photo(configGet("channel", "posting"), candidate, caption=caption, disable_notification=configGet("silent", "posting"))
# else:
# sent = await app.send_photo(configGet("channel", "posting"), candidate, caption=caption, disable_notification=configGet("silent", "posting"))
# elif ext_type == "video":
# if configGet("enabled", "caption"):
# if configGet("link", "caption") != None:
# sent = await app.send_video(configGet("channel", "posting"), candidate, caption=caption, disable_notification=configGet("silent", "posting"))
# else:
# sent = await app.send_video(configGet("channel", "posting"), candidate, caption=caption, disable_notification=configGet("silent", "posting"))
# else:
# sent = await app.send_video(configGet("channel", "posting"), candidate, caption=caption, disable_notification=configGet("silent", "posting"))
# else:
# return
# if configGet("api_based", "mode"):
# remove(configGet("tmp", "locations")+sep+pic[0]+".jpg")
# move_pic(pic[0])
# index["sent"].append(candidate_file)
# index["last_id"] = sent.id
# jsonSave(index, configGet("index", "locations"))
# if configGet("move_sent", "posting"):
# move(candidate, configGet("sent", "locations")+sep+candidate_file)
# logWrite(locale("post_sent", "console", locale=configGet("locale")).format(candidate, ext_type, str(configGet("channel", "posting")), caption.replace("\n", "%n"), str(configGet("silent", "posting"))))
# if configGet("sent", "reports"):
# await app.send_message(configGet("admin"), f"Posted `{candidate_file}`", disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup([
# [InlineKeyboardButton(locale("post_view", "button", locale=configGet("locale")), url=sent.link)]
# ]))
# 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(configGet("admin"), locale("post_exception", "message", locale=configGet("locale")).format(exp, format_exc()))
# pass
2023-01-10 13:52:44 +02:00
# Work in progress
# Check last posts forwards
# check_forwards(app)