Now using black for formatting
This commit is contained in:
@@ -21,50 +21,81 @@ from modules.logger import logWrite
|
||||
from modules.utils import configGet
|
||||
|
||||
|
||||
http_session = ClientSession(json_serialize=dumps, )
|
||||
http_session = ClientSession(
|
||||
json_serialize=dumps,
|
||||
)
|
||||
|
||||
|
||||
async def authorize() -> str:
|
||||
makedirs(configGet("cache", "locations"), exist_ok=True)
|
||||
if path.exists(configGet("cache", "locations")+sep+"api_access") is True:
|
||||
async with aiofiles.open(configGet("cache", "locations")+sep+"api_access", "rb") as file:
|
||||
if path.exists(configGet("cache", "locations") + sep + "api_access") is True:
|
||||
async with aiofiles.open(
|
||||
configGet("cache", "locations") + sep + "api_access", "rb"
|
||||
) as file:
|
||||
token = b64decode(await file.read()).decode("utf-8")
|
||||
if (await http_session.get(configGet("address", "posting", "api")+"/users/me/", headers={"Authorization": f"Bearer {token}"})).status == 200:
|
||||
if (
|
||||
await http_session.get(
|
||||
configGet("address", "posting", "api") + "/users/me/",
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
)
|
||||
).status == 200:
|
||||
return token
|
||||
payload = {
|
||||
"grant_type": "password",
|
||||
"scope": "me albums.list albums.read albums.write photos.list photos.read photos.write videos.list videos.read videos.write",
|
||||
"username": configGet("username", "posting", "api"),
|
||||
"password": configGet("password", "posting", "api")
|
||||
"password": configGet("password", "posting", "api"),
|
||||
}
|
||||
response = await http_session.post(configGet("address", "posting", "api")+"/token", data=payload)
|
||||
response = await http_session.post(
|
||||
configGet("address", "posting", "api") + "/token", data=payload
|
||||
)
|
||||
if not response.ok:
|
||||
logWrite(f'Incorrect API credentials! Could not login into "{configGet("address", "posting", "api")}" using login "{configGet("username", "posting", "api")}": HTTP {response.status}')
|
||||
logWrite(
|
||||
f'Incorrect API credentials! Could not login into "{configGet("address", "posting", "api")}" using login "{configGet("username", "posting", "api")}": HTTP {response.status}'
|
||||
)
|
||||
raise ValueError
|
||||
async with aiofiles.open(configGet("cache", "locations")+sep+"api_access", "wb") as file:
|
||||
await file.write(b64encode((await response.json())["access_token"].encode("utf-8")))
|
||||
async with aiofiles.open(
|
||||
configGet("cache", "locations") + sep + "api_access", "wb"
|
||||
) as file:
|
||||
await file.write(
|
||||
b64encode((await response.json())["access_token"].encode("utf-8"))
|
||||
)
|
||||
return (await response.json())["access_token"]
|
||||
|
||||
|
||||
async def random_pic(token: Union[str, None] = None) -> Tuple[str, str]:
|
||||
"""Returns random image id and filename from the queue.
|
||||
|
||||
### Returns:
|
||||
* `Tuple[str, str]`: First value is an ID and the filename in the filesystem to be indexed.
|
||||
"""
|
||||
"""
|
||||
token = await authorize() if token is None else token
|
||||
logWrite(f'{configGet("address", "posting", "api")}/albums/{configGet("album", "posting", "api")}/photos?q=&page_size={configGet("page_size", "posting")}&caption=queue')
|
||||
resp = await http_session.get(f'{configGet("address", "posting", "api")}/albums/{configGet("album", "posting", "api")}/photos?q=&page_size={configGet("page_size", "posting")}&caption=queue', headers={"Authorization": f"Bearer {token}"})
|
||||
logWrite(
|
||||
f'{configGet("address", "posting", "api")}/albums/{configGet("album", "posting", "api")}/photos?q=&page_size={configGet("page_size", "posting")}&caption=queue'
|
||||
)
|
||||
resp = await http_session.get(
|
||||
f'{configGet("address", "posting", "api")}/albums/{configGet("album", "posting", "api")}/photos?q=&page_size={configGet("page_size", "posting")}&caption=queue',
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
)
|
||||
print(await resp.json(), flush=True)
|
||||
if resp.status != 200:
|
||||
logWrite(f'Could not get photos from album {configGet("album", "posting", "api")}: HTTP {resp.status}')
|
||||
logWrite(f'Could not get photos from "{configGet("address", "posting", "api")}/albums/{configGet("album", "posting", "api")}/photos?q=&page_size={configGet("page_size", "posting")}&caption=queue" using token "{token}": HTTP {resp.status}', debug=True)
|
||||
logWrite(
|
||||
f'Could not get photos from album {configGet("album", "posting", "api")}: HTTP {resp.status}'
|
||||
)
|
||||
logWrite(
|
||||
f'Could not get photos from "{configGet("address", "posting", "api")}/albums/{configGet("album", "posting", "api")}/photos?q=&page_size={configGet("page_size", "posting")}&caption=queue" using token "{token}": HTTP {resp.status}',
|
||||
debug=True,
|
||||
)
|
||||
raise ValueError
|
||||
if len((await resp.json())["results"]) == 0:
|
||||
raise KeyError
|
||||
pic = choice((await resp.json())["results"])
|
||||
return pic["id"], pic["filename"]
|
||||
|
||||
async def upload_pic(filepath: str, allow_duplicates: bool = False, token: Union[str, None] = None) -> Tuple[bool, list]:
|
||||
|
||||
async def upload_pic(
|
||||
filepath: str, allow_duplicates: bool = False, token: Union[str, None] = None
|
||||
) -> Tuple[bool, list]:
|
||||
token = await authorize() if token is None else token
|
||||
try:
|
||||
pic_name = path.basename(filepath)
|
||||
@@ -72,32 +103,53 @@ async def upload_pic(filepath: str, allow_duplicates: bool = False, token: Union
|
||||
async with aiofiles.open(filepath, "rb") as f:
|
||||
file_bytes = await f.read()
|
||||
formdata = FormData()
|
||||
formdata.add_field('file', file_bytes, filename=pic_name, content_type='image/jpeg')
|
||||
formdata.add_field(
|
||||
"file", file_bytes, filename=pic_name, content_type="image/jpeg"
|
||||
)
|
||||
response = await http_session.post(
|
||||
f'{configGet("address", "posting", "api")}/albums/{configGet("album", "posting", "api")}/photos',
|
||||
params={"caption": "queue", "compress": "false", "ignore_duplicates": str(allow_duplicates).lower()},
|
||||
params={
|
||||
"caption": "queue",
|
||||
"compress": "false",
|
||||
"ignore_duplicates": str(allow_duplicates).lower(),
|
||||
},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
data=formdata
|
||||
data=formdata,
|
||||
)
|
||||
if response.status != 200 and response.status != 409:
|
||||
logWrite(f"Could not upload '{filepath}' to API: HTTP {response.status} with message '{response.content}'")
|
||||
raise SubmissionUploadError(str(filepath), response.status, response.content)
|
||||
logWrite(
|
||||
f"Could not upload '{filepath}' to API: HTTP {response.status} with message '{response.content}'"
|
||||
)
|
||||
raise SubmissionUploadError(
|
||||
str(filepath), response.status, response.content
|
||||
)
|
||||
duplicates = []
|
||||
if "duplicates" in (await response.json()):
|
||||
for index, duplicate in enumerate((await response.json())["duplicates"]):
|
||||
if (await response.json())["access_token"] is None:
|
||||
duplicates.append(f'`{duplicate["id"]}`:\n{configGet("address_external", "posting", "api")}/photos/{duplicate["id"]}')
|
||||
duplicates.append(
|
||||
f'`{duplicate["id"]}`:\n{configGet("address_external", "posting", "api")}/photos/{duplicate["id"]}'
|
||||
)
|
||||
else:
|
||||
duplicates.append(f'`{duplicate["id"]}`:\n{configGet("address_external", "posting", "api")}/token/photo/{(await response.json())["access_token"]}?id={index}')
|
||||
duplicates.append(
|
||||
f'`{duplicate["id"]}`:\n{configGet("address_external", "posting", "api")}/token/photo/{(await response.json())["access_token"]}?id={index}'
|
||||
)
|
||||
return True, duplicates
|
||||
except Exception as exp:
|
||||
print_exc()
|
||||
return False, []
|
||||
|
||||
async def find_pic(name: str, caption: Union[str, None] = None, token: Union[str, None] = None) -> Union[dict, None]:
|
||||
|
||||
|
||||
async def find_pic(
|
||||
name: str, caption: Union[str, None] = None, token: Union[str, None] = None
|
||||
) -> Union[dict, None]:
|
||||
token = await authorize() if token is None else token
|
||||
try:
|
||||
response = await http_session.get(f'{configGet("address", "posting", "api")}/albums/{configGet("album", "posting", "api")}/photos', params={"q": name, "caption": caption}, headers={"Authorization": f"Bearer {token}"})
|
||||
response = await http_session.get(
|
||||
f'{configGet("address", "posting", "api")}/albums/{configGet("album", "posting", "api")}/photos',
|
||||
params={"q": name, "caption": caption},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
)
|
||||
# logWrite(response.json())
|
||||
if response.status != 200:
|
||||
return None
|
||||
@@ -105,16 +157,23 @@ async def find_pic(name: str, caption: Union[str, None] = None, token: Union[str
|
||||
return None
|
||||
return (await response.json())["results"]
|
||||
except Exception as exp:
|
||||
logWrite(f"Could not find image with name '{name}' and caption '{caption}' due to: {exp}")
|
||||
logWrite(
|
||||
f"Could not find image with name '{name}' and caption '{caption}' due to: {exp}"
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
async def move_pic(id: str, token: Union[str, None] = None) -> bool:
|
||||
token = await authorize() if token is None else token
|
||||
try:
|
||||
await http_session.patch(f'{configGet("address", "posting", "api")}/photos/{id}?caption=sent', headers={"Authorization": f"Bearer {token}"})
|
||||
await http_session.patch(
|
||||
f'{configGet("address", "posting", "api")}/photos/{id}?caption=sent',
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
)
|
||||
return True
|
||||
except:
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(asyncio.run(authorize()))
|
||||
print(asyncio.run(authorize()))
|
||||
|
@@ -1,4 +1,9 @@
|
||||
from modules.utils import configGet
|
||||
from classes.poster_client import PosterClient
|
||||
|
||||
app = PosterClient("duptsiaposter", bot_token=configGet("bot_token", "bot"), api_id=configGet("api_id", "bot"), api_hash=configGet("api_hash", "bot"))
|
||||
app = PosterClient(
|
||||
"duptsiaposter",
|
||||
bot_token=configGet("bot_token", "bot"),
|
||||
api_id=configGet("api_id", "bot"),
|
||||
api_hash=configGet("api_hash", "bot"),
|
||||
)
|
||||
|
@@ -3,21 +3,35 @@ from classes.poster_client import PosterClient
|
||||
from pyrogram.types import BotCommand, BotCommandScopeChat
|
||||
from modules.utils import configGet, locale
|
||||
|
||||
async def register_commands(app: PosterClient) -> None:
|
||||
|
||||
async def register_commands(app: PosterClient) -> None:
|
||||
if configGet("submit", "mode"):
|
||||
# Registering user commands
|
||||
for entry in listdir(configGet("locale", "locations")):
|
||||
if entry.endswith(".json"):
|
||||
commands_list = []
|
||||
for command in configGet("commands"):
|
||||
commands_list.append(BotCommand(command, locale(command, "commands", locale=entry.replace(".json", ""))))
|
||||
await app.set_bot_commands(commands_list, language_code=entry.replace(".json", ""))
|
||||
commands_list.append(
|
||||
BotCommand(
|
||||
command,
|
||||
locale(
|
||||
command, "commands", locale=entry.replace(".json", "")
|
||||
),
|
||||
)
|
||||
)
|
||||
await app.set_bot_commands(
|
||||
commands_list, language_code=entry.replace(".json", "")
|
||||
)
|
||||
|
||||
# Registering user commands for fallback locale
|
||||
commands_list = []
|
||||
for command in configGet("commands"):
|
||||
commands_list.append(BotCommand(command, locale(command, "commands", locale=configGet("locale_fallback"))))
|
||||
commands_list.append(
|
||||
BotCommand(
|
||||
command,
|
||||
locale(command, "commands", locale=configGet("locale_fallback")),
|
||||
)
|
||||
)
|
||||
await app.set_bot_commands(commands_list)
|
||||
|
||||
# Registering admin commands
|
||||
@@ -25,10 +39,19 @@ async def register_commands(app: PosterClient) -> None:
|
||||
|
||||
if configGet("submit", "mode"):
|
||||
for command in configGet("commands"):
|
||||
|
||||
commands_admin_list.append(BotCommand(command, locale(command, "commands", locale=configGet("locale"))))
|
||||
commands_admin_list.append(
|
||||
BotCommand(
|
||||
command, locale(command, "commands", locale=configGet("locale"))
|
||||
)
|
||||
)
|
||||
for command in configGet("commands_admin"):
|
||||
commands_admin_list.append(BotCommand(command, locale(command, "commands_admin", locale=configGet("locale"))))
|
||||
commands_admin_list.append(
|
||||
BotCommand(
|
||||
command, locale(command, "commands_admin", locale=configGet("locale"))
|
||||
)
|
||||
)
|
||||
|
||||
for admin in app.admins:
|
||||
await app.set_bot_commands(commands_admin_list, scope=BotCommandScopeChat(chat_id=admin))
|
||||
await app.set_bot_commands(
|
||||
commands_admin_list, scope=BotCommandScopeChat(chat_id=admin)
|
||||
)
|
||||
|
@@ -8,18 +8,16 @@ with open("config.json", "r", encoding="utf-8") as f:
|
||||
f.close()
|
||||
|
||||
if db_config["user"] is not None and db_config["password"] is not None:
|
||||
con_string = 'mongodb://{0}:{1}@{2}:{3}/{4}'.format(
|
||||
con_string = "mongodb://{0}:{1}@{2}:{3}/{4}".format(
|
||||
db_config["user"],
|
||||
db_config["password"],
|
||||
db_config["host"],
|
||||
db_config["port"],
|
||||
db_config["name"]
|
||||
db_config["name"],
|
||||
)
|
||||
else:
|
||||
con_string = 'mongodb://{0}:{1}/{2}'.format(
|
||||
db_config["host"],
|
||||
db_config["port"],
|
||||
db_config["name"]
|
||||
con_string = "mongodb://{0}:{1}/{2}".format(
|
||||
db_config["host"], db_config["port"], db_config["name"]
|
||||
)
|
||||
|
||||
db_client = MongoClient(con_string)
|
||||
@@ -34,4 +32,4 @@ for collection in ["sent", "users", "banned", "submitted"]:
|
||||
col_sent = db.get_collection("sent")
|
||||
col_users = db.get_collection("users")
|
||||
col_banned = db.get_collection("banned")
|
||||
col_submitted = db.get_collection("submitted")
|
||||
col_submitted = db.get_collection("submitted")
|
||||
|
@@ -9,15 +9,15 @@ from shutil import copyfileobj
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
with open(getcwd()+path.sep+"config.json", "r", encoding='utf8') as file:
|
||||
with open(getcwd() + path.sep + "config.json", "r", encoding="utf8") as file:
|
||||
json_contents = loads(file.read())
|
||||
log_size = json_contents["logging"]["size"]
|
||||
log_folder = json_contents["logging"]["location"]
|
||||
file.close()
|
||||
|
||||
|
||||
# Check latest log size
|
||||
def checkSize(debug=False) -> None:
|
||||
|
||||
global log_folder
|
||||
|
||||
if debug:
|
||||
@@ -29,18 +29,26 @@ def checkSize(debug=False) -> None:
|
||||
makedirs(log_folder, exist_ok=True)
|
||||
log = stat(path.join(log_folder, log_file))
|
||||
if (log.st_size / 1024) > log_size:
|
||||
with open(path.join(log_folder, log_file), 'rb') as f_in:
|
||||
with gzipopen(path.join(log_folder, f'{datetime.now().strftime("%d.%m.%Y_%H:%M:%S")}.log.gz'), 'wb') as f_out:
|
||||
with open(path.join(log_folder, log_file), "rb") as f_in:
|
||||
with gzipopen(
|
||||
path.join(
|
||||
log_folder,
|
||||
f'{datetime.now().strftime("%d.%m.%Y_%H:%M:%S")}.log.gz',
|
||||
),
|
||||
"wb",
|
||||
) as f_out:
|
||||
copyfileobj(f_in, f_out)
|
||||
print(f'Copied {path.join(log_folder, datetime.now().strftime("%d.%m.%Y_%H:%M:%S"))}.log.gz')
|
||||
open(path.join(log_folder, log_file), 'w').close()
|
||||
print(
|
||||
f'Copied {path.join(log_folder, datetime.now().strftime("%d.%m.%Y_%H:%M:%S"))}.log.gz'
|
||||
)
|
||||
open(path.join(log_folder, log_file), "w").close()
|
||||
except FileNotFoundError:
|
||||
print(f'Log file {path.join(log_folder, log_file)} does not exist')
|
||||
print(f"Log file {path.join(log_folder, log_file)} does not exist")
|
||||
pass
|
||||
|
||||
|
||||
# Append string to log
|
||||
def logAppend(message, debug=False) -> None:
|
||||
|
||||
global log_folder
|
||||
|
||||
message_formatted = f'[{datetime.now().strftime("%d.%m.%Y")}] [{datetime.now().strftime("%H:%M:%S")}] {message}'
|
||||
@@ -51,12 +59,13 @@ def logAppend(message, debug=False) -> None:
|
||||
else:
|
||||
log_file = "latest.log"
|
||||
|
||||
log = open(path.join(log_folder, log_file), 'a')
|
||||
log.write(f'{message_formatted}\n')
|
||||
log = open(path.join(log_folder, log_file), "a")
|
||||
log.write(f"{message_formatted}\n")
|
||||
log.close()
|
||||
|
||||
|
||||
# Print to stdout and then to log
|
||||
def logWrite(message, debug=False) -> None:
|
||||
# save to log file and rotation is to be done
|
||||
logAppend(f'{message}', debug=debug)
|
||||
print(f"{message}", flush=True)
|
||||
logAppend(f"{message}", debug=debug)
|
||||
print(f"{message}", flush=True)
|
||||
|
@@ -10,10 +10,22 @@ scheduler = AsyncIOScheduler()
|
||||
|
||||
if configGet("post", "mode"):
|
||||
if configGet("use_interval", "posting"):
|
||||
scheduler.add_job(send_content, "interval", seconds=timeparse(configGet("interval", "posting")), args=[app])
|
||||
scheduler.add_job(
|
||||
send_content,
|
||||
"interval",
|
||||
seconds=timeparse(configGet("interval", "posting")),
|
||||
args=[app],
|
||||
)
|
||||
else:
|
||||
for entry in configGet("time", "posting"):
|
||||
dt_obj = datetime.strptime(entry, "%H:%M")
|
||||
scheduler.add_job(send_content, "cron", hour=dt_obj.hour, minute=dt_obj.minute, args=[app])
|
||||
scheduler.add_job(
|
||||
send_content, "cron", hour=dt_obj.hour, minute=dt_obj.minute, args=[app]
|
||||
)
|
||||
|
||||
scheduler.add_job(register_commands, "date", run_date=datetime.now()+timedelta(seconds=10), args=[app])
|
||||
scheduler.add_job(
|
||||
register_commands,
|
||||
"date",
|
||||
run_date=datetime.now() + timedelta(seconds=10),
|
||||
args=[app],
|
||||
)
|
||||
|
@@ -15,13 +15,14 @@ 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")))
|
||||
await app.send_message(
|
||||
app.owner,
|
||||
locale("api_creds_invalid", "message", locale=configGet("locale")),
|
||||
)
|
||||
return
|
||||
|
||||
try:
|
||||
@@ -29,19 +30,37 @@ async def send_content(app: PosterClient) -> None:
|
||||
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")))
|
||||
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")))
|
||||
await app.send_message(
|
||||
app.owner,
|
||||
locale("api_queue_error", "message", locale=configGet("locale")),
|
||||
)
|
||||
return
|
||||
|
||||
response = await http_session.get(f'{configGet("address", "posting", "api")}/photos/{pic[0]}', headers={"Authorization": f"Bearer {token}"})
|
||||
|
||||
response = await http_session.get(
|
||||
f'{configGet("address", "posting", "api")}/photos/{pic[0]}',
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
)
|
||||
|
||||
if response.status != 200:
|
||||
logWrite(locale("post_invalid_pic", "console", locale=configGet("locale")).format(response.status, str(response.json())))
|
||||
logWrite(
|
||||
locale(
|
||||
"post_invalid_pic", "console", locale=configGet("locale")
|
||||
).format(response.status, str(response.json()))
|
||||
)
|
||||
if configGet("error", "reports"):
|
||||
await app.send_message(app.owner, locale("post_invalid_pic", "message", locale=configGet("locale")).format(response.status, response.json()))
|
||||
await app.send_message(
|
||||
app.owner,
|
||||
locale(
|
||||
"post_invalid_pic", "message", locale=configGet("locale")
|
||||
).format(response.status, response.json()),
|
||||
)
|
||||
|
||||
tmp_dir = str(uuid4())
|
||||
|
||||
@@ -49,23 +68,40 @@ async def send_content(app: PosterClient) -> None:
|
||||
|
||||
tmp_path = path.join(tmp_dir, pic[1])
|
||||
|
||||
async with aiofiles.open(path.join(configGet("tmp", "locations"), tmp_path), 'wb') as out_file:
|
||||
async with aiofiles.open(
|
||||
path.join(configGet("tmp", "locations"), tmp_path), "wb"
|
||||
) as out_file:
|
||||
await out_file.write(await response.read())
|
||||
|
||||
logWrite(f'Candidate {pic[1]} ({pic[0]}) is {path.getsize(path.join(configGet("tmp", "locations"), tmp_path))} bytes big', debug=True)
|
||||
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)
|
||||
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)
|
||||
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.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)
|
||||
rmtree(
|
||||
path.join(configGet("tmp", "locations"), tmp_dir), ignore_errors=True
|
||||
)
|
||||
raise BytesWarning
|
||||
|
||||
del response
|
||||
@@ -77,10 +113,17 @@ async def send_content(app: PosterClient) -> None:
|
||||
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)
|
||||
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"
|
||||
caption = (
|
||||
f"{caption}\n\n{configGet('text', 'posting', 'submitted_caption')}\n"
|
||||
)
|
||||
else:
|
||||
caption = f"{caption}\n\n"
|
||||
|
||||
@@ -93,11 +136,21 @@ async def send_content(app: PosterClient) -> None:
|
||||
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"))
|
||||
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()))
|
||||
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
|
||||
|
||||
@@ -107,7 +160,9 @@ async def send_content(app: PosterClient) -> None:
|
||||
"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()
|
||||
"caption": None
|
||||
if (submitted is None or submitted["caption"] is None)
|
||||
else submitted["caption"].strip(),
|
||||
}
|
||||
)
|
||||
|
||||
@@ -115,13 +170,31 @@ async def send_content(app: PosterClient) -> None:
|
||||
|
||||
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"))))
|
||||
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()))
|
||||
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()))
|
||||
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)
|
||||
rmtree(
|
||||
path.join(configGet("tmp", "locations"), tmp_dir), ignore_errors=True
|
||||
)
|
||||
except:
|
||||
pass
|
||||
pass
|
||||
|
@@ -13,24 +13,30 @@ from typing import Any
|
||||
|
||||
from modules.logger import logWrite
|
||||
|
||||
|
||||
def jsonLoad(filename: str) -> Any:
|
||||
"""Loads arg1 as json and returns its contents"""
|
||||
with open(filename, "r", encoding='utf8') as file:
|
||||
with open(filename, "r", encoding="utf8") as file:
|
||||
try:
|
||||
output = loads(file.read())
|
||||
except JSONDecodeError:
|
||||
logWrite(f"Could not load json file {filename}: file seems to be incorrect!\n{print_exc()}")
|
||||
logWrite(
|
||||
f"Could not load json file {filename}: file seems to be incorrect!\n{print_exc()}"
|
||||
)
|
||||
raise
|
||||
except FileNotFoundError:
|
||||
logWrite(f"Could not load json file {filename}: file does not seem to exist!\n{print_exc()}")
|
||||
logWrite(
|
||||
f"Could not load json file {filename}: file does not seem to exist!\n{print_exc()}"
|
||||
)
|
||||
raise
|
||||
file.close()
|
||||
return output
|
||||
|
||||
|
||||
def jsonSave(contents: Any, filename: str) -> None:
|
||||
"""Dumps dict/list arg1 to file arg2"""
|
||||
try:
|
||||
with open(filename, "w", encoding='utf8') as file:
|
||||
with open(filename, "w", encoding="utf8") as file:
|
||||
file.write(dumps(contents, ensure_ascii=False, indent=4))
|
||||
file.close()
|
||||
except Exception as exp:
|
||||
@@ -44,7 +50,7 @@ def configSet(key: str, value, *args: str):
|
||||
* key (str): The last key of the keys path.
|
||||
* value (str/int/float/list/dict/None): Some needed value.
|
||||
* *args (str): Path to key like: dict[args][key].
|
||||
"""
|
||||
"""
|
||||
this_dict = jsonLoad("config.json")
|
||||
string = "this_dict"
|
||||
for arg in args:
|
||||
@@ -57,6 +63,7 @@ def configSet(key: str, value, *args: str):
|
||||
jsonSave(this_dict, "config.json")
|
||||
return
|
||||
|
||||
|
||||
def configGet(key: str, *args: str):
|
||||
"""Get value of the config key
|
||||
Args:
|
||||
@@ -64,13 +71,14 @@ def configGet(key: str, *args: str):
|
||||
* *args (str): Path to key like: dict[args][key].
|
||||
Returns:
|
||||
* any: Value of provided key
|
||||
"""
|
||||
"""
|
||||
this_dict = jsonLoad("config.json")
|
||||
this_key = this_dict
|
||||
for dict_key in args:
|
||||
this_key = this_key[dict_key]
|
||||
return this_key[key]
|
||||
|
||||
|
||||
def locale(key: str, *args: str, locale=configGet("locale")):
|
||||
"""Get value of locale string
|
||||
Args:
|
||||
@@ -79,36 +87,42 @@ def locale(key: str, *args: str, locale=configGet("locale")):
|
||||
* locale (str): Locale to looked up in. Defaults to config's locale value.
|
||||
Returns:
|
||||
* any: Value of provided locale key
|
||||
"""
|
||||
if (locale == None):
|
||||
"""
|
||||
if locale == None:
|
||||
locale = configGet("locale")
|
||||
|
||||
|
||||
try:
|
||||
this_dict = jsonLoad(f'{configGet("locale", "locations")}{sep}{locale}.json')
|
||||
except FileNotFoundError:
|
||||
try:
|
||||
this_dict = jsonLoad(f'{configGet("locale", "locations")}{sep}{configGet("locale")}.json')
|
||||
this_dict = jsonLoad(
|
||||
f'{configGet("locale", "locations")}{sep}{configGet("locale")}.json'
|
||||
)
|
||||
except FileNotFoundError:
|
||||
try:
|
||||
this_dict = jsonLoad(f'{configGet("locale_fallback", "locations")}{sep}{configGet("locale")}.json')
|
||||
this_dict = jsonLoad(
|
||||
f'{configGet("locale_fallback", "locations")}{sep}{configGet("locale")}.json'
|
||||
)
|
||||
except:
|
||||
return f'⚠️ Locale in config is invalid: could not get "{key}" in {str(args)} from locale "{locale}"'
|
||||
|
||||
this_key = this_dict
|
||||
for dict_key in args:
|
||||
this_key = this_key[dict_key]
|
||||
|
||||
|
||||
try:
|
||||
return this_key[key]
|
||||
except KeyError:
|
||||
return f'⚠️ Locale in config is invalid: could not get "{key}" in {str(args)} from locale "{locale}"'
|
||||
|
||||
|
||||
try:
|
||||
from psutil import Process
|
||||
except ModuleNotFoundError:
|
||||
print(locale("deps_missing", "console", locale=configGet("locale")), flush=True)
|
||||
exit()
|
||||
|
||||
|
||||
def killProc(pid: int) -> None:
|
||||
"""Kill process by its PID. Meant to be used to kill the main process of bot itself.
|
||||
|
||||
@@ -117,6 +131,7 @@ def killProc(pid: int) -> None:
|
||||
"""
|
||||
if osname == "posix":
|
||||
from signal import SIGKILL
|
||||
|
||||
kill(pid, SIGKILL)
|
||||
else:
|
||||
Process(pid).kill()
|
||||
Process(pid).kill()
|
||||
|
Reference in New Issue
Block a user