Added updates checker

This commit is contained in:
Profitroll 2023-03-22 11:03:03 +01:00
parent 5ad52aa3f8
commit cc6523f604
4 changed files with 46 additions and 7 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
}, },

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

@ -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 *
@ -168,6 +172,38 @@ async def 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()