This repository has been archived on 2024-08-21. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
TelegramPoster/poster.py

267 lines
9.8 KiB
Python
Raw Normal View History

2023-03-20 13:55:42 +01:00
from datetime import datetime
2023-03-22 11:03:03 +01:00
from os import getpid, path
2023-01-09 15:36:56 +01:00
from sys import exit
2023-03-20 13:55:42 +01:00
from time import time
2023-03-22 11:03:03 +01:00
from traceback import format_exc
2023-03-22 15:52:34 +01:00
from modules.api_client import authorize
2023-03-12 22:14:03 +01:00
from modules.cli import *
2023-03-22 11:03:03 +01:00
from modules.http_client import http_session
2023-01-17 11:43:10 +01:00
from modules.logger import logWrite
2023-01-10 12:52:44 +01:00
from modules.scheduler import scheduler
2023-03-22 11:03:03 +01:00
from modules.utils import configGet, jsonLoad, jsonSave, locale
# Import ===================================================================================================================================
try:
2023-03-20 13:55:42 +01:00
from dateutil.relativedelta import relativedelta
2023-03-22 11:03:03 +01:00
from pyrogram.errors import bad_request_400
from pyrogram.sync import idle
2023-03-12 22:14:03 +01:00
from modules.app import app
except ModuleNotFoundError:
print(locale("deps_missing", "console", locale=configGet("locale")), flush=True)
2022-08-31 14:31:24 +02:00
exit()
2023-03-09 11:33:02 +01:00
# ===========================================================================================================================================
2022-08-31 14:31:24 +02:00
pid = getpid()
2023-03-22 11:03:03 +01:00
version = 0.1
# Work in progress
# def check_forwards(app):
# try:
# index = jsonLoad(configGet("index", "locations"))
# channel = app.get_chat(configGet("channel", "posting"))
# peer = app.resolve_peer(configGet("channel", "posting"))
# print(peer, flush=True)
# posts_list = [i for i in range(index["last_id"]-100,index["last_id"])]
# last_posts = app.get_messages(configGet("channel", "posting"), message_ids=posts_list)
# for post in last_posts:
# post_forwards = GetMessagePublicForwards(channel=peer, msg_id=post.id, offset_peer=peer, offset_rate=0, offset_id=0, limit=100)
# print(post_forwards, flush=True)
# for forward in post_forwards:
# print(forward, flush=True)
# except Exception as exp:
# logWrite("Could not get last posts forwards due to {0} with traceback {1}".format(str(exp), traceback.format_exc()), debug=True)
# if configGet("error", "reports"):
2023-01-10 12:52:44 +01:00
# app.send_message(configGet("admin"), traceback.format_exc())
# pass
# Work in progress
# @app.on_message(~ filters.scheduled & filters.command(["forwards"], prefixes="/"))
# def cmd_forwards(app, msg):
# check_forwards(app)
2023-03-22 11:03:03 +01:00
from plugins.callbacks.shutdown import *
2023-01-10 13:06:24 +01:00
# Imports ==================================================================================================================================
2023-02-14 11:38:54 +01:00
from plugins.commands.general import *
2022-08-30 14:10:05 +02:00
if configGet("submit", "mode"):
2023-02-17 21:54:14 +01:00
from plugins.callbacks.nothing import *
2023-02-14 11:38:54 +01:00
from plugins.callbacks.submission import *
from plugins.commands.mode_submit import *
from plugins.handlers.submission import *
2023-01-17 14:11:23 +01:00
2023-03-18 20:53:26 +01:00
if configGet("post", "mode"):
from plugins.commands.photos import *
# if configGet("api_based", "mode"):
# from modules.api_client import authorize
2023-03-09 11:33:02 +01:00
# ===========================================================================================================================================
2022-08-30 14:01:12 +02:00
# Work in progress
# Handle new forwards
# @app.on_raw_update()
# def fwd_got(app, update, users, chats):
# if isinstance(update, UpdateChannelMessageForwards):
# logWrite(f'Forward count increased to {update["forwards"]} on post {update["id"]} in channel {update["channel_id"]}')
# logWrite(str(users), debug=True)
# logWrite(str(chats), debug=True)
# # else:
# # logWrite(f"Got raw update of type {type(update)} with contents {update}", debug=True)
2023-02-14 11:38:54 +01:00
# async def main():
# await app.start()
# logWrite(locale("startup", "console", locale=configGet("locale")).format(str(pid)))
# if configGet("startup", "reports"):
# await app.send_message(configGet("admin"), locale("startup", "message", locale=configGet("locale")).format(str(pid)))
# if configGet("post", "mode"):
# scheduler.start()
# if configGet("api_based", "mode"):
# token = authorize()
# if len(get(f'{configGet("address", "posting", "api")}/albums?q={configGet("queue", "posting", "api", "albums")}', headers={"Authorization": f"Bearer {token}"}).json()["results"]) == 0:
# post(f'{configGet("address", "posting", "api")}/albums?name={configGet("queue", "posting", "api", "albums")}&title={configGet("queue", "posting", "api", "albums")}', headers={"Authorization": f"Bearer {token}"})
# await idle()
# await app.send_message(configGet("admin"), locale("shutdown", "message", locale=configGet("locale")).format(str(pid)))
# logWrite(locale("shutdown", "console", locale=configGet("locale")).format(str(pid)))
# killProc(pid)
# if __name__ == "__main__":
# if find_spec("uvloop") is not None:
# uvloop.install()
# asyncio.run(main())
2023-03-22 10:33:21 +01:00
async def main():
2023-03-20 13:55:42 +01:00
logWrite(locale("startup", "console").format(str(pid)))
2023-03-22 10:33:21 +01:00
await app.start()
2023-03-09 11:33:02 +01:00
if configGet("startup", "reports"):
2023-03-20 13:55:42 +01:00
try:
if path.exists(path.join(configGet("cache", "locations"), "shutdown_time")):
downtime = relativedelta(
datetime.now(),
datetime.fromtimestamp(
jsonLoad(
path.join(configGet("cache", "locations"), "shutdown_time")
)["timestamp"]
),
)
if downtime.days >= 1:
2023-03-22 10:33:21 +01:00
await app.send_message(
2023-03-20 13:55:42 +01:00
configGet("owner"),
locale(
"startup_downtime_days",
"message",
).format(pid, downtime.days),
)
elif downtime.hours >= 1:
2023-03-22 10:33:21 +01:00
await app.send_message(
2023-03-20 13:55:42 +01:00
configGet("owner"),
locale(
"startup_downtime_hours",
"message",
).format(pid, downtime.hours),
)
else:
2023-03-22 10:33:21 +01:00
await app.send_message(
2023-03-20 13:55:42 +01:00
configGet("owner"),
locale(
"startup_downtime_minutes",
"message",
locale=configGet("locale"),
).format(pid, downtime.minutes),
)
else:
2023-03-22 10:33:21 +01:00
await app.send_message(
2023-03-20 13:55:42 +01:00
configGet("owner"),
locale("startup", "message").format(pid),
)
except bad_request_400.PeerIdInvalid:
logWrite(
f"Could not send startup message to bot owner. Perhaps user has not started the bot yet."
)
2023-03-22 11:03:03 +01:00
if configGet("update", "reports"):
try:
check_update = await http_session.get(
"https://git.end-play.xyz/api/v1/repos/profitroll/TelegramPoster/releases?page=1&limit=1"
)
response = await check_update.json()
if len(response) == 0:
raise ValueError("No bot releases on git found.")
2023-04-24 12:53:22 +02:00
if float(response[0]["tag_name"].replace("v", "")) > version:
2023-03-22 11:03:03 +01:00
logWrite(
2023-04-24 12:53:22 +02:00
f'New version {response[0]["tag_name"].replace("v", "")} found (current {version})'
2023-03-22 11:03:03 +01:00
)
await app.send_message(
configGet("owner"),
locale(
"update_available",
"message",
).format(
response[0]["tag_name"],
response[0]["html_url"],
response[0]["body"],
),
)
else:
logWrite(f"No updates found, bot is up to date.")
except bad_request_400.PeerIdInvalid:
logWrite(
f"Could not send startup message to bot owner. Perhaps user has not started the bot yet."
)
except Exception as exp:
logWrite(f"Update check failed due to {exp}: {format_exc()}")
2023-01-09 19:01:07 +02:00
if configGet("post", "mode"):
scheduler.start()
2023-01-10 12:52:44 +01:00
2023-03-22 15:52:34 +01:00
try:
token = await authorize()
2023-04-24 12:40:06 +02:00
2023-03-22 15:52:34 +01:00
if (
len(
(
await (
await http_session.get(
2023-04-24 12:44:10 +02:00
f'{configGet("address", "posting", "api")}/albums?q={configGet("album", "posting", "api")}',
2023-03-22 15:52:34 +01:00
headers={"Authorization": f"Bearer {token}"},
)
).json()
)["results"]
)
== 0
):
logWrite("Media album does not exist on API server. Trying to create it...")
try:
await http_session.post(
2023-04-24 12:44:10 +02:00
f'{configGet("address", "posting", "api")}/albums?name={configGet("album", "posting", "api")}&title={configGet("album", "posting", "api")}',
2023-03-22 15:52:34 +01:00
headers={"Authorization": f"Bearer {token}"},
)
2023-04-24 12:40:06 +02:00
logWrite("Created media album on API server.")
2023-03-22 15:52:34 +01:00
except Exception as exp:
logWrite(
f"Could not create media album on API server due to {exp}: {format_exc()}"
)
except Exception as exp:
logWrite(f"Could not check if API album exists due to {exp}: {format_exc()}")
2023-01-17 14:11:23 +01:00
2023-03-22 10:33:21 +01:00
await idle()
2023-03-20 13:55:42 +01:00
try:
2023-03-22 10:33:21 +01:00
await app.send_message(
2023-03-20 13:55:42 +01:00
configGet("owner"),
locale("shutdown", "message").format(pid),
)
except bad_request_400.PeerIdInvalid:
logWrite(
f"Could not send shutdown message to bot owner. Perhaps user has not started the bot yet."
)
makedirs(configGet("cache", "locations"), exist_ok=True)
jsonSave(
{"timestamp": time()},
path.join(configGet("cache", "locations"), "shutdown_time"),
2023-03-09 11:33:02 +01:00
)
2023-03-20 13:55:42 +01:00
logWrite(locale("shutdown", "console").format(str(pid)))
scheduler.shutdown()
2023-03-22 10:33:21 +01:00
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())