Compare commits

..

4 Commits

Author SHA1 Message Date
Profitroll
cc6523f604 Added updates checker 2023-03-22 11:03:03 +01:00
Profitroll
5ad52aa3f8 Changed aiohttp module location 2023-03-22 11:02:55 +01:00
Profitroll
45789ad013 Updates wiki init 2023-03-22 11:02:13 +01:00
Profitroll
4422a13ba9 Improved async context 2023-03-22 10:33:21 +01:00
7 changed files with 68 additions and 22 deletions

View File

@@ -23,6 +23,7 @@
"reports": { "reports": {
"sent": false, "sent": false,
"error": true, "error": true,
"update": true,
"startup": true, "startup": true,
"shutdown": true "shutdown": true
}, },

1
docs/updating.md Normal file
View File

@@ -0,0 +1 @@
# Updating your bot

View File

@@ -59,7 +59,8 @@
"remove_ignored": "No response, aborting removal.", "remove_ignored": "No response, aborting removal.",
"remove_abort": "Removal aborted.", "remove_abort": "Removal aborted.",
"remove_success": "Removed media with ID `{0}`.", "remove_success": "Removed media with ID `{0}`.",
"remove_failure": "Could not remove media with ID `{0}`. Check if provided ID is correct and if it is - you can also check bot's log for details." "remove_failure": "Could not remove media with ID `{0}`. Check if provided ID is correct and if it is - you can also check bot's log for details.",
"update_available": "**New version found**\nThere's a newer version of a bot found. You can update your bot to [{0}]({1}) using command line of your host.\n\n**Release notes**\n{2}\n\nRead more about updating you bot on the [wiki page](https://git.end-play.xyz/profitroll/TelegramPoster/wiki/Updating-Instance).\n\nPlease not that you can also disable this notification by editing `reports.update` key of the config."
}, },
"button": { "button": {
"sub_yes": "✅ Accept", "sub_yes": "✅ Accept",

View File

@@ -59,7 +59,8 @@
"remove_ignored": "Немає відповіді, перериваємо видалення.", "remove_ignored": "Немає відповіді, перериваємо видалення.",
"remove_abort": "Видалення перервано.", "remove_abort": "Видалення перервано.",
"remove_success": "Видалено медіа з ID `{0}`.", "remove_success": "Видалено медіа з ID `{0}`.",
"remove_failure": "Не вдалося видалити медіа з ID `{0}`. Перевірте, чи вказано правильний ID, і якщо він правильний, ви також можете переглянути логи бота для отримання більш детальної інформації." "remove_failure": "Не вдалося видалити медіа з ID `{0}`. Перевірте, чи вказано правильний ID, і якщо він правильний, ви також можете переглянути логи бота для отримання більш детальної інформації.",
"update_available": "**Знайдено нову версію**\nЗнайдено нову версію бота. Ви можете оновити бота до [{0}]({1}) за допомогою командного рядка вашого хосту.\n\n**Примітки до релізу**\n{2}\n\nДетальніше про оновлення бота можна знайти на [вікі-сторінці](https://git.end-play.xyz/profitroll/TelegramPoster/wiki/Updating-Instance).\n\nЗверніть увагу, що ви також можете вимкнути це сповіщення, відредагувавши ключ `reports.update` у конфігурації."
}, },
"button": { "button": {
"sub_yes": "✅ Прийняти", "sub_yes": "✅ Прийняти",

View File

@@ -8,8 +8,7 @@ from traceback import print_exc
from typing import Tuple, Union from typing import Tuple, Union
import aiofiles import aiofiles
from aiohttp import ClientSession, FormData from aiohttp import FormData
from ujson import dumps
from classes.exceptions import ( from classes.exceptions import (
AlbumCreationDuplicateError, AlbumCreationDuplicateError,
@@ -21,10 +20,7 @@ from classes.exceptions import (
) )
from modules.logger import logWrite from modules.logger import logWrite
from modules.utils import configGet, locale from modules.utils import configGet, locale
from modules.http_client import http_session
http_session = ClientSession(
json_serialize=dumps,
)
async def authorize() -> str: async def authorize() -> str:

6
modules/http_client.py Normal file
View File

@@ -0,0 +1,6 @@
from aiohttp import ClientSession
from ujson import dumps
http_session = ClientSession(
json_serialize=dumps,
)

View File

@@ -1,18 +1,20 @@
from os import getpid, path
from datetime import datetime from datetime import datetime
from os import getpid, path
from sys import exit from sys import exit
from time import time from time import time
from traceback import format_exc
from modules.cli import * from modules.cli import *
from modules.http_client import http_session
from modules.logger import logWrite from modules.logger import logWrite
from modules.scheduler import scheduler from modules.scheduler import scheduler
from modules.utils import configGet, jsonLoad, jsonSave, killProc, locale from modules.utils import configGet, jsonLoad, jsonSave, locale
# Import =================================================================================================================================== # Import ===================================================================================================================================
try: try:
from pyrogram.sync import idle
from pyrogram.errors import bad_request_400
from dateutil.relativedelta import relativedelta from dateutil.relativedelta import relativedelta
from pyrogram.errors import bad_request_400
from pyrogram.sync import idle
from modules.app import app from modules.app import app
except ModuleNotFoundError: except ModuleNotFoundError:
@@ -22,6 +24,7 @@ except ModuleNotFoundError:
pid = getpid() pid = getpid()
version = 0.1
# Work in progress # Work in progress
# def check_forwards(app): # def check_forwards(app):
@@ -59,9 +62,10 @@ pid = getpid()
# check_forwards(app) # check_forwards(app)
from plugins.callbacks.shutdown import *
# Imports ================================================================================================================================== # Imports ==================================================================================================================================
from plugins.commands.general import * from plugins.commands.general import *
from plugins.callbacks.shutdown import *
if configGet("submit", "mode"): if configGet("submit", "mode"):
from plugins.callbacks.nothing import * from plugins.callbacks.nothing import *
@@ -116,10 +120,11 @@ if configGet("post", "mode"):
# uvloop.install() # uvloop.install()
# asyncio.run(main()) # asyncio.run(main())
if __name__ == "__main__":
async def main():
logWrite(locale("startup", "console").format(str(pid))) logWrite(locale("startup", "console").format(str(pid)))
app.start() await app.start()
if configGet("startup", "reports"): if configGet("startup", "reports"):
try: try:
@@ -133,7 +138,7 @@ if __name__ == "__main__":
), ),
) )
if downtime.days >= 1: if downtime.days >= 1:
app.send_message( await app.send_message(
configGet("owner"), configGet("owner"),
locale( locale(
"startup_downtime_days", "startup_downtime_days",
@@ -141,7 +146,7 @@ if __name__ == "__main__":
).format(pid, downtime.days), ).format(pid, downtime.days),
) )
elif downtime.hours >= 1: elif downtime.hours >= 1:
app.send_message( await app.send_message(
configGet("owner"), configGet("owner"),
locale( locale(
"startup_downtime_hours", "startup_downtime_hours",
@@ -149,7 +154,7 @@ if __name__ == "__main__":
).format(pid, downtime.hours), ).format(pid, downtime.hours),
) )
else: else:
app.send_message( await app.send_message(
configGet("owner"), configGet("owner"),
locale( locale(
"startup_downtime_minutes", "startup_downtime_minutes",
@@ -158,7 +163,7 @@ if __name__ == "__main__":
).format(pid, downtime.minutes), ).format(pid, downtime.minutes),
) )
else: else:
app.send_message( await app.send_message(
configGet("owner"), configGet("owner"),
locale("startup", "message").format(pid), locale("startup", "message").format(pid),
) )
@@ -167,6 +172,38 @@ if __name__ == "__main__":
f"Could not send startup message to bot owner. Perhaps user has not started the bot yet." f"Could not send startup message to bot owner. Perhaps user has not started the bot yet."
) )
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.")
if float(response[0]["tag_name"].replace("v.", "")) > version:
logWrite(
f'New version {response[0]["tag_name"].replace("v.", "")} found (current {version})'
)
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()}")
if configGet("post", "mode"): if configGet("post", "mode"):
scheduler.start() scheduler.start()
@@ -175,10 +212,10 @@ if __name__ == "__main__":
# if len(get(f'{configGet("address", "posting", "api")}/albums?q={configGet("queue", "posting", "api", "albums")}', headers={"Authorization": f"Bearer {token}"}).json()["results"]) == 0: # 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}"}) # post(f'{configGet("address", "posting", "api")}/albums?name={configGet("queue", "posting", "api", "albums")}&title={configGet("queue", "posting", "api", "albums")}', headers={"Authorization": f"Bearer {token}"})
idle() await idle()
try: try:
app.send_message( await app.send_message(
configGet("owner"), configGet("owner"),
locale("shutdown", "message").format(pid), locale("shutdown", "message").format(pid),
) )
@@ -197,4 +234,7 @@ if __name__ == "__main__":
scheduler.shutdown() scheduler.shutdown()
killProc(pid)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())