From fc219833058c7b162da57f579d284723e4769489 Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Fri, 16 Sep 2022 20:42:58 +0200 Subject: [PATCH 1/8] Fixed absence of "block" & "unblock" buttons --- poster.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/poster.py b/poster.py index fc47fc3..9ccdac9 100644 --- a/poster.py +++ b/poster.py @@ -315,8 +315,6 @@ if configGet("submit", "mode"): if msg.from_user.phone_number != None: caption += f" ({msg.from_user.phone_number})" - msg.copy(configGet("admin"), caption=caption, reply_markup=InlineKeyboardMarkup(buttons)) - if msg.from_user.id != configGet("admin"): buttons += [ [ @@ -330,6 +328,8 @@ if configGet("submit", "mode"): msg.reply_text(locale("sub_sent", "message", locale=user_locale), quote=True) subLimit(msg.from_user) + msg.copy(configGet("admin"), caption=caption, reply_markup=InlineKeyboardMarkup(buttons)) + else: msg.reply_text(locale("sub_cooldown", "message", locale=user_locale).format(str(configGet("timeout", "submission")))) except AttributeError: From dfc1e36f07bffca0c3bd22488bd5069dd4a52296 Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Sun, 18 Sep 2022 18:10:41 +0200 Subject: [PATCH 2/8] Logging has been improved --- config.json | 1 + locale/en.json | 20 +++++++++++-- locale/uk.json | 24 ++++++++++++--- poster.py | 80 +++++++++++++++++++++++++++++++++++--------------- 4 files changed, 95 insertions(+), 30 deletions(-) diff --git a/config.json b/config.json index 7ba168c..19209e2 100644 --- a/config.json +++ b/config.json @@ -1,6 +1,7 @@ { "module": null, "locale": "en", + "locale_log": "en", "locale_fallback": "en", "admin": 0, "bot": { diff --git a/locale/en.json b/locale/en.json index c6075e2..23d3833 100644 --- a/locale/en.json +++ b/locale/en.json @@ -30,7 +30,9 @@ "sub_no": "❌ Deny", "sub_block": "☠️ Block sender", "sub_unblock": "🏳️ Unblock sender", - "post_view": "View in channel" + "post_view": "View in channel", + "accepted": "✅ Accepted", + "declined": "❌ Declined" }, "callback": { "sub_yes": "✅ Submission approved", @@ -38,7 +40,8 @@ "sub_block": "User {0} has been blocked", "sub_unblock": "User {0} has been unblocked", "sub_msg_unavail": "Submission message no longer exist", - "sub_media_unavail": "Could not download submission" + "sub_media_unavail": "Could not download submission", + "sub_done": "You've already decided what to do with submission" }, "console": { "shutdown": "Shutting down bot with pid {0}", @@ -48,6 +51,19 @@ "post_sent": "Sent {0} of type {1} to {2} with caption {3} and silently {4}", "post_exception": "Could not send content due to {0}. Traceback: {1}", "post_empty": "Could not send content due to queue folder empty with allowed extensions", + "sub_mime_not_allowed": "Got submission from {0} but type of {1} which is not allowed", + "sub_document_too_large": "Got submission from {0} but but file is too large ({1} > {2})", + "sub_received": "Got submission from {0} with a caption {1}", + "sub_cooldown": "Got submission from {0} but user is on a cooldown", + "sub_no_id": "from_user in function get_submission does not contain id (maybe user posted in a channel)", + "sub_msg_unavail": "Could not download submission {0} from user {1}: message not available", + "sub_media_unavail": "Could not download submission {0} from user {1}: media not available", + "sub_media_downloading": "Downloading media of submission {0} from user {1}...", + "sub_media_downloaded": "Downloaded media of submission {0} from user {1}", + "sub_accepted": "Accepted submission {0} from user {1}", + "sub_declined": "Declined submission {0} from user {1}", + "sub_blocked": "Blocked user {0}", + "sub_unblocked": "Unblocked user {0}", "deps_missing": "Required modules are not installed. Run 'pip3 install -r requirements.txt' and restart the program.", "passed_norun": "Argument --norun passed, not running the main script", "move_sent_doesnt_exist": "File '{0}' is already moved or does not exist", diff --git a/locale/uk.json b/locale/uk.json index e110a84..1c9aa63 100644 --- a/locale/uk.json +++ b/locale/uk.json @@ -14,8 +14,8 @@ "startup": "Запуск бота з підом `{0}`", "sub_yes": "✅ Подання схвалено та прийнято", "sub_no": "❌ Подання розглянуто та відхилено", - "sub_blocked": "Вас заблокували, і ви більше не можете надсилати медіафайли.", - "sub_unblocked": "Вас розблокували, і тепер ви можете надсилати медіафайли.", + "sub_blocked": "Вас заблокували, ви більше не можете надсилати медіафайли.", + "sub_unblocked": "Вас розблокували, тепер ви можете надсилати медіафайли.", "sub_by": "\n\nПредставлено:", "sub_sent": "Медіа-файл надіслано.\nСкоро ми повідомимо вас, чи буде його прийнято.", "sub_cooldown": "Ви можете надсилати лише 1 медіафайл на {0} секунд", @@ -30,7 +30,9 @@ "sub_no": "❌ Відхилити", "sub_block": "☠️ Заблокувати відправника", "sub_unblock": "🏳️ Розблокувати відправника", - "post_view": "Переглянути на каналі" + "post_view": "Переглянути на каналі", + "accepted": "✅ Прийнято", + "declined": "❌ Відхилено" }, "callback": { "sub_yes": "✅ Подання схвалено", @@ -38,7 +40,8 @@ "sub_block": "Користувача {0} заблоковано", "sub_unblock": "Користувача {0} розблоковано", "sub_msg_unavail": "Повідомлення більше не існує", - "sub_media_unavail": "Не вдалося завантажити подання" + "sub_media_unavail": "Не вдалося завантажити подання", + "sub_done": "Ви вже обрали що зробити з цим поданням" }, "console": { "shutdown": "Вимкнення бота з підом {0}", @@ -48,6 +51,19 @@ "post_sent": "Надіслано {0} типу {1} у {2} з підписом {3} та без звуку {4}", "post_exception": "Не вдалося надіслати контент через {0}. Traceback: {1}", "post_empty": "Не вдалося надіслати контент через порожню папку черги з дозволеними розширеннями", + "sub_mime_not_allowed": "Отримано подання від {0} але типу {1} який не є дозволеним", + "sub_document_too_large": "Отримано подання від {0} але файл завеликий({1} > {2})", + "sub_received": "Отримано подання від {0} з підписом {1}", + "sub_cooldown": "Отримано подання від {0} але користувач на тайм-ауті", + "sub_no_id": "from_user у функції get_submission не має атрибуту id (можливо, користувач запостив щось у канал)", + "sub_msg_unavail": "Не вдалося завантажити подання {0} від користувача {1}: повідомлення більше не існує", + "sub_media_unavail": "Не вдалося завантажити подання {0} від користувача {1}: медіафайл більше не існує", + "sub_media_downloading": "Завантажуємо медіа з подання {0} від користувача{1}...", + "sub_media_downloaded": "Завантажено медіа з подання{0} від користувача{1}", + "sub_accepted": "Прийнято подання {0} від користувача {1}", + "sub_declined": "Відхилено подання {0} від користувача {1}", + "sub_blocked": "Заблоковано користувача {0}", + "sub_unblocked": "Розблоковано користувача {0}", "deps_missing": "Необхідні модулі не встановлені. Запустіть 'pip3 install -r requirements.txt' і перезапустіть програму.", "passed_norun": "Аргумент --norun надано, основний скрипт не запускається", "move_sent_doesnt_exist": "Файл '{0}' уже переміщено або він не існує", diff --git a/poster.py b/poster.py index 9ccdac9..c898213 100644 --- a/poster.py +++ b/poster.py @@ -16,10 +16,10 @@ if "--move-sent" in argv: try: move(configGet("queue", "locations")+sep+entry, configGet("sent", "locations")+sep+entry) except FileNotFoundError: - logWrite(locale("move_sent_doesnt_exist", "console", locale=configGet("locale")).format(entry)) + logWrite(locale("move_sent_doesnt_exist", "console", locale=configGet("locale_log")).format(entry)) except Exception as exp: - logWrite(locale("move_sent_doesnt_exception", "console", locale=configGet("locale")).format(entry, exp)) - logWrite(locale("move_sent_completed", "console", locale=configGet("locale"))) + logWrite(locale("move_sent_doesnt_exception", "console", locale=configGet("locale_log")).format(entry, exp)) + logWrite(locale("move_sent_completed", "console", locale=configGet("locale_log"))) if "--cleanup" in argv: if "--confirm" in argv: @@ -35,23 +35,23 @@ if "--cleanup" in argv: except FileNotFoundError: pass except Exception as exp: - logWrite(locale("cleanup_exception", "console", locale=configGet("locale")).format(entry, exp)) + logWrite(locale("cleanup_exception", "console", locale=configGet("locale_log")).format(entry, exp)) jsonSave(index, jsonLoad(configGet("index", "locations"))) - logWrite(locale("cleanup_completed", "console", locale=configGet("locale"))) + logWrite(locale("cleanup_completed", "console", locale=configGet("locale_log"))) else: - logWrite(locale("cleanup_unathorized", "console", locale=configGet("locale"))) + logWrite(locale("cleanup_unathorized", "console", locale=configGet("locale_log"))) if "--cleanup-index" in argv: if "--confirm" in argv: index = jsonLoad(configGet("index", "locations")) index["sent"] = [] jsonSave(index, jsonLoad(configGet("index", "locations"))) - logWrite(locale("cleanup_index_completed", "console", locale=configGet("locale"))) + logWrite(locale("cleanup_index_completed", "console", locale=configGet("locale_log"))) else: - logWrite(locale("cleanup_index_unathorized", "console", locale=configGet("locale"))) + logWrite(locale("cleanup_index_unathorized", "console", locale=configGet("locale_log"))) if "--norun" in argv: - logWrite(locale("passed_norun", "console", locale=configGet("locale"))) + logWrite(locale("passed_norun", "console", locale=configGet("locale_log"))) exit() #=========================================================================================================================================== @@ -64,7 +64,7 @@ try: from pyrogram.raw.types import UpdateChannelMessageForwards, InputChannel, InputPeerChannel from pyrogram.raw.functions.stats import GetMessagePublicForwards except ModuleNotFoundError: - print(locale("deps_missing", "console", locale=configGet("locale")), flush=True) + print(locale("deps_missing", "console", locale=configGet("locale_log")), flush=True) exit() #=========================================================================================================================================== @@ -139,7 +139,7 @@ def send_content(): candidate_file = choice(list_queue) candidate = configGet("queue", "locations")+sep+candidate_file else: - logWrite(locale("post_empty", "console", locale=configGet("locale"))) + logWrite(locale("post_empty", "console", locale=configGet("locale_log"))) if configGet("error", "reports"): app.send_message(configGet("admin"), locale("post_empty", "message", locale=configGet("locale"))) # type: ignore return @@ -188,7 +188,7 @@ def send_content(): 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")))) # type: ignore + logWrite(locale("post_sent", "console", locale=configGet("locale_log")).format(candidate, ext_type, str(configGet("channel", "posting")), caption.replace("\n", "%n"), str(configGet("silent", "posting")))) # type: ignore if configGet("sent", "reports"): app.send_message(configGet("admin"), f"Posted `{candidate_file}`", disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup([ @@ -196,7 +196,7 @@ def send_content(): ])) # type: ignore 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_log")).format(str(exp), format_exc())) if configGet("error", "reports"): app.send_message(configGet("admin"), locale("post_exception", "message", locale=configGet("locale")).format(exp, traceback.format_exc())) # type: ignore pass @@ -227,7 +227,7 @@ if configGet("submit", "mode"): def cmd_kill(app, msg): if msg.from_user.id == configGet("admin"): - logWrite(locale("shutdown", "console", locale=configGet("locale")).format(str(pid))) + logWrite(locale("shutdown", "console", locale=configGet("locale_log")).format(str(pid))) msg.reply_text(locale("shutdown", "message", locale=configGet("locale")).format(str(pid))) killProc(pid) @@ -273,14 +273,17 @@ if configGet("submit", "mode"): if msg.document != None: if msg.document.mime_type not in configGet("mime_types", "submission"): + logWrite(locale("sub_mime_not_allowed", "console", locale=configGet("locale_log")).format(str(msg.from_user.id), msg.document.mime_type)) msg.reply_text(locale("mime_not_allowed", "message", locale=user_locale), quote=True) return if msg.document.file_size > configGet("file_size", "submission"): + logWrite(locale("sub_document_too_large", "console", locale=configGet("locale_log")).format(str(msg.from_user.id), str(msg.document.file_size), str(configGet("file_size", "submission")))) msg.reply_text(locale("document_too_large", "message", locale=user_locale).format(str(configGet("file_size", "submission")/1024/1024)), quote=True) return if msg.video != None: if msg.video.file_size > configGet("file_size", "submission"): + logWrite(locale("sub_document_too_large", "console", locale=configGet("locale_log")).format(str(msg.from_user.id), str(msg.document.file_size), str(configGet("file_size", "submission")))) msg.reply_text(locale("document_too_large", "message", locale=user_locale).format(str(configGet("file_size", "submission")/1024/1024)), quote=True) return @@ -319,21 +322,24 @@ if configGet("submit", "mode"): buttons += [ [ InlineKeyboardButton(text=locale("sub_block", "button", locale=configGet("locale")), callback_data=f"sub_block_{msg.from_user.id}") - ], - [ - InlineKeyboardButton(text=locale("sub_unblock", "button", locale=configGet("locale")), callback_data=f"sub_unblock_{msg.from_user.id}") ] + # [ + # InlineKeyboardButton(text=locale("sub_unblock", "button", locale=configGet("locale")), callback_data=f"sub_unblock_{msg.from_user.id}") + # ] ] msg.reply_text(locale("sub_sent", "message", locale=user_locale), quote=True) subLimit(msg.from_user) + logWrite(locale("sub_received", "console", locale=configGet("locale_log")).format(str(msg.from_user.id), str(msg.caption))) msg.copy(configGet("admin"), caption=caption, reply_markup=InlineKeyboardMarkup(buttons)) else: + logWrite(locale("sub_cooldown", "console", locale=configGet("locale_log")).format(str(msg.from_user.id))) msg.reply_text(locale("sub_cooldown", "message", locale=user_locale).format(str(configGet("timeout", "submission")))) + except AttributeError: - logWrite(f"from_user in function get_submission does not seem to contain id") + logWrite(locale("sub_received", "console", locale=configGet("locale_log"))) @app.on_callback_query(filters.regex("sub_yes_[\s\S]*_[\s\S]*")) # type: ignore def callback_query_yes(app, clb): # type: ignore @@ -342,18 +348,26 @@ def callback_query_yes(app, clb): # type: ignore try: submission = app.get_messages(int(fullclb[2]), int(fullclb[3])) except: + logWrite(locale("sub_msg_unavail", "console", locale=configGet("locale_log")).format(fullclb[3], fullclb[2])) clb.answer(text=locale("sub_msg_unavail", "message", locale=user_locale), show_alert=True) return try: + logWrite(locale("sub_media_downloading", "console", locale=configGet("locale_log")).format(fullclb[3], fullclb[2])) media = app.download_media(submission, file_name=configGet("queue", "locations")+sep) if clb.data.endswith("_caption"): index = jsonLoad(configGet("index", "locations")) index["captions"][Path(media).name] = submission.caption jsonSave(index, configGet("index", "locations")) + logWrite(locale("sub_media_downloaded", "console", locale=configGet("locale_log")).format(fullclb[3], fullclb[2])) except: + logWrite(locale("sub_media_unavail", "console", locale=configGet("locale_log")).format(fullclb[3], fullclb[2])) clb.answer(text=locale("sub_media_unavail", "message", locale=user_locale), show_alert=True) return + logWrite(locale("sub_accepted", "console", locale=configGet("locale_log")).format(fullclb[3], fullclb[2])) submission.reply_text(locale("sub_yes", "message", locale=submission.from_user.language_code), quote=True) + edited_markup = clb.message.reply_markup.inline_keyboard + edited_markup[0] = [InlineKeyboardButton(text=locale("accepted", "button", locale=configGet("locale")), callback_data=f"sub_done")] + clb.message.edit(text=clb.message.caption, reply_markup=InlineKeyboardMarkup(edited_markup)) clb.answer(text=locale("sub_yes", "callback", locale=user_locale).format(fullclb[2]), show_alert=True) @app.on_callback_query(filters.regex("sub_no_[\s\S]*_[\s\S]*")) # type: ignore @@ -363,26 +377,44 @@ def callback_query_no(app, clb): # type: ignore try: submission = app.get_messages(int(fullclb[2]), int(fullclb[3])) except: + logWrite(locale("sub_msg_unavail", "console", locale=configGet("locale_log")).format(fullclb[3], fullclb[2])) clb.answer(text=locale("sub_msg_unavail", "message", locale=user_locale), show_alert=True) return + logWrite(locale("sub_declined", "console", locale=configGet("locale_log")).format(fullclb[3], fullclb[2])) submission.reply_text(locale("sub_no", "message", locale=submission.from_user.language_code), quote=True) + edited_markup = clb.message.reply_markup.inline_keyboard + edited_markup[0] = [InlineKeyboardButton(text=locale("declined", "button", locale=configGet("locale")), callback_data=f"sub_done")] + clb.message.edit(text=clb.message.caption, reply_markup=InlineKeyboardMarkup(edited_markup)) clb.answer(text=locale("sub_no", "callback", locale=user_locale).format(fullclb[2]), show_alert=True) @app.on_callback_query(filters.regex("sub_block_[\s\S]*")) # type: ignore def callback_query_block(app, clb): # type: ignore fullclb = clb.data.split("_") user_locale = clb.from_user.language_code - app.send_message(int(fullclb[2]), locale("sub_msg_unavail", "message", locale=configGet("locale"))) + app.send_message(int(fullclb[2]), locale("sub_blocked", "message", locale=configGet("locale"))) subBlock(int(fullclb[2])) + logWrite(locale("sub_blocked", "console", locale=configGet("locale_log")).format(fullclb[2])) + edited_markup = clb.message.reply_markup.inline_keyboard + edited_markup[1] = [InlineKeyboardButton(text=locale("sub_unblock", "button", locale=configGet("locale")), callback_data=f"sub_unblock_{fullclb[2]}")] + clb.message.edit(text=clb.message.caption, reply_markup=InlineKeyboardMarkup(edited_markup)) clb.answer(text=locale("sub_block", "callback", locale=user_locale).format(fullclb[2]), show_alert=True) @app.on_callback_query(filters.regex("sub_unblock_[\s\S]*")) # type: ignore def callback_query_unblock(app, clb): # type: ignore fullclb = clb.data.split("_") user_locale = clb.from_user.language_code - app.send_message(int(fullclb[2]), locale("sub_msg_unavail", "message", locale=configGet("locale"))) + app.send_message(int(fullclb[2]), locale("sub_unblocked", "message", locale=configGet("locale"))) subUnblock(int(fullclb[2])) + logWrite(locale("sub_unblocked", "console", locale=configGet("locale_log")).format(fullclb[2])) + edited_markup = clb.message.reply_markup.inline_keyboard + edited_markup[1] = [InlineKeyboardButton(text=locale("sub_block", "button", locale=configGet("locale")), callback_data=f"sub_block_{fullclb[2]}")] + clb.message.edit(text=clb.message.caption, reply_markup=InlineKeyboardMarkup(edited_markup)) clb.answer(text=locale("sub_unblock", "callback", locale=user_locale).format(fullclb[2]), show_alert=True) + +@app.on_callback_query(filters.regex("sub_done")) # type: ignore +def callback_query_block(app, clb): # type: ignore + user_locale = clb.from_user.language_code + clb.answer(text=locale("sub_done", "callback", locale=user_locale), show_alert=True) #=========================================================================================================================================== # Work in progress @@ -410,16 +442,16 @@ if configGet("post", "mode"): except: pass except Exception as exp: - logWrite(locale("exception_occured", "console", locale=configGet("locale")).format(exp)) + logWrite(locale("exception_occured", "console", locale=configGet("locale_log")).format(exp)) except KeyboardInterrupt: - logWrite(locale("keyboard_interrupt", "console", locale=configGet("locale"))) + logWrite(locale("keyboard_interrupt", "console", locale=configGet("locale_log"))) if configGet("shutdown", "reports"): app.send_message(configGet("admin"), locale("shutdown", "message", locale=configGet("locale")).format(str(pid))) # type: ignore killProc(pid) if __name__ == "__main__": - logWrite(locale("startup", "console", locale=configGet("locale")).format(str(pid))) + logWrite(locale("startup", "console", locale=configGet("locale_log")).format(str(pid))) app.start() # type: ignore if configGet("startup", "reports"): @@ -456,6 +488,6 @@ if __name__ == "__main__": idle() app.send_message(configGet("admin"), locale("shutdown", "message", locale=configGet("locale")).format(str(pid))) # type: ignore - logWrite(locale("shutdown", "console", locale=configGet("locale")).format(str(pid))) + logWrite(locale("shutdown", "console", locale=configGet("locale_log")).format(str(pid))) killProc(pid) \ No newline at end of file From f0c333968bf68424d163ca43b1b77b595432d83b Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Sun, 18 Sep 2022 18:13:40 +0200 Subject: [PATCH 3/8] "locale_log" explanation added --- README.md | 2 +- README_uk.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5f55974..71c7bf6 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,6 @@ Examples: ## Localization Bot is capable of using custom locales. There are some that are pre-installed (English and Ukrainian), however you can add your own locales too. -All localization files are located in the `locale` folder, otherwise in folder specified in config file. Just copy locale file of your choice, name it in accordance to [IETF language tags](https://en.wikipedia.org/wiki/IETF_language_tag) (if you want your locale to be compatible with Telegram's locales) or define your own name. Save it as json and you're good to go. If you want to change default locale for console output and messages, that cannot determine admin's locale - edit `"locale"` parameter in the `config.json`. If this locale is not available - `"locale_fallback"` will be used instead. If both are not available - error will be shown. +All localization files are located in the `locale` folder, otherwise in folder specified in config file. Just copy locale file of your choice, name it in accordance to [IETF language tags](https://en.wikipedia.org/wiki/IETF_language_tag) (if you want your locale to be compatible with Telegram's locales) or define your own name. Save it as json and you're good to go. If you want to change default locale for messages, that cannot determine admin's locale - edit `"locale"` parameter in the `config.json`. If this locale is not available - `"locale_fallback"` will be used instead. If both are not available - error will be shown. For console output and logging locale you should edit `"locale_log"`. We recommend to only make changes to your custom locale. Or at least always have your backup of for example `en.json` as your fallback. \ No newline at end of file diff --git a/README_uk.md b/README_uk.md index 8838867..88c03c2 100644 --- a/README_uk.md +++ b/README_uk.md @@ -53,6 +53,6 @@ ## Локалізація Бот може використовувати різні мови. Є деякі попередньо встановлені (Англійська та Українська), однак Ви можете додавати свої власні локалізації теж. -Всі файли локалізації знаходяться у папці `locale`, якщо в конфігураційному файлі не вказано іншу. Просто скопіюйте цікавлячий Вас файл, назвіть його відповідно до [тегів мови IETF](https://en.wikipedia.org/wiki/IETF_language_tag) (якщо Ви хочете, щоб переклад був сумісним з перекладами Telegram) або просто вкажіть свою власну назву. Збережіть свій переклад як json файл і все готово. Якщо ви хочете змінити мову за замовчуванням для виведення консолі та повідомлень самого бота, які не можуть визначити мову адміністратора, відредагуйте параметр `"locale"` у `config.json`. Якщо ця мова недоступна, замість неї буде використано `"locale_fallback"`. Якщо обидві мови недоступні - буде показано помилку. +Всі файли локалізації знаходяться у папці `locale`, якщо в конфігураційному файлі не вказано іншу. Просто скопіюйте цікавлячий Вас файл, назвіть його відповідно до [тегів мови IETF](https://en.wikipedia.org/wiki/IETF_language_tag) (якщо Ви хочете, щоб переклад був сумісним з перекладами Telegram) або просто вкажіть свою власну назву. Збережіть свій переклад як json файл і все готово. Якщо ви хочете змінити мову за замовчуванням для повідомлень самого бота, які не можуть визначити мову адміністратора, відредагуйте параметр `"locale"` у `config.json`. Якщо ця мова недоступна, замість неї буде використано `"locale_fallback"`. Якщо обидві мови недоступні - буде показано помилку. Для зміни мови виведення консолі та логування вам слід відредагувати `"locale_log"`. Ми рекомендуємо вносити будь-які зміни лише до вашої окремої мови. Або, принаймні, завжди мати резервну копію, наприклад, `en.json` як запасний варіант. \ No newline at end of file From c4177d1575ff0d22ff29e6eaf57e1f6cfcd7022c Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Sun, 18 Sep 2022 18:27:13 +0200 Subject: [PATCH 4/8] Optimized imports --- modules/utils.py | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/modules/utils.py b/modules/utils.py index 1380140..d8731b1 100644 --- a/modules/utils.py +++ b/modules/utils.py @@ -5,11 +5,11 @@ except ModuleNotFoundError: from json import JSONDecodeError as JSONDecodeError from json import loads, dumps -import os -import sys -import traceback +from sys import exit +from os import sep, kill +from os import name as osname +from traceback import print_exc -from signal import SIGKILL # type: ignore from modules.logging import logWrite def jsonLoad(filename): @@ -18,10 +18,10 @@ def jsonLoad(filename): try: output = loads(file.read()) except JSONDecodeError: - logWrite(f"Could not load json file {filename}: file seems to be incorrect!\n{traceback.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{traceback.print_exc()}") + logWrite(f"Could not load json file {filename}: file does not seem to exist!\n{print_exc()}") raise file.close() return output @@ -33,7 +33,7 @@ def jsonSave(contents, filename): file.write(dumps(contents, ensure_ascii=False, indent=4)) file.close() except Exception as exp: - logWrite(f"Could not save json file {filename}: {exp}\n{traceback.print_exc()}") + logWrite(f"Could not save json file {filename}: {exp}\n{print_exc()}") return @@ -83,13 +83,13 @@ def locale(key: str, *args: str, locale=configGet("locale")): locale = configGet("locale") try: - this_dict = jsonLoad(f'{configGet("locale", "locations")}{os.sep}{locale}.json') + this_dict = jsonLoad(f'{configGet("locale", "locations")}{sep}{locale}.json') except FileNotFoundError: try: - this_dict = jsonLoad(f'{configGet("locale", "locations")}{os.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")}{os.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}"' @@ -103,14 +103,15 @@ def locale(key: str, *args: str, locale=configGet("locale")): return f'⚠️ Locale in config is invalid: could not get "{key}" in {str(args)} from locale "{locale}"' try: - import psutil + from psutil import Process except ModuleNotFoundError: print(locale("deps_missing", "console", locale=configGet("locale")), flush=True) - sys.exit() + exit() def killProc(pid): - if os.name == "posix": - os.kill(pid, SIGKILL) + if osname == "posix": + from signal import SIGKILL # type: ignore + kill(pid, SIGKILL) else: - p = psutil.Process(pid) + p = Process(pid) p.kill() \ No newline at end of file From 0e14ca600ff6fa0a67044a6d76f2b545132fc990 Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Sun, 18 Sep 2022 18:27:25 +0200 Subject: [PATCH 5/8] Changed some imports' paths --- poster.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/poster.py b/poster.py index c898213..1c327e3 100644 --- a/poster.py +++ b/poster.py @@ -58,11 +58,11 @@ if "--norun" in argv: # Import =================================================================================================================================== try: - import schedule # type: ignore - from pyrogram import Client, filters, idle # type: ignore - from pyrogram.types import ChatPermissions, ReplyKeyboardMarkup, InlineKeyboardMarkup, InlineKeyboardButton, BotCommand, BotCommandScopeChat # type: ignore - from pyrogram.raw.types import UpdateChannelMessageForwards, InputChannel, InputPeerChannel - from pyrogram.raw.functions.stats import GetMessagePublicForwards + import schedule + from pyrogram.sync import idle + from pyrogram.client import Client + from pyrogram import filters + from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, BotCommand, BotCommandScopeChat except ModuleNotFoundError: print(locale("deps_missing", "console", locale=configGet("locale_log")), flush=True) exit() @@ -181,7 +181,7 @@ def send_content(): return index["sent"].append(candidate_file) - index["last_id"] = sent.id + index["last_id"] = sent.id # type: ignore jsonSave(index, configGet("index", "locations")) @@ -458,7 +458,7 @@ if __name__ == "__main__": app.send_message(configGet("admin"), locale("startup", "message", locale=configGet("locale")).format(str(pid))) # type: ignore if configGet("post", "mode"): - t = Thread(target=background_task) + t = Thread(target=background_task) # type: ignore t.start() if configGet("submit", "mode"): From 46e3665749d9432f4cc156e275c021ce16125010 Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Sat, 24 Sep 2022 17:03:20 +0200 Subject: [PATCH 6/8] Small fix --- poster.py | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/poster.py b/poster.py index 1c327e3..b128c06 100644 --- a/poster.py +++ b/poster.py @@ -157,27 +157,33 @@ def send_content(): else: caption = caption - if ext_type == "photo": # type: ignore + try: + if ext_type == "photo": # type: ignore - if configGet("enabled", "caption"): - if configGet("link", "caption") != None: - sent = app.send_photo(configGet("channel", "posting"), candidate, caption=caption, disable_notification=configGet("silent", "posting")) # type: ignore + if configGet("enabled", "caption"): + if configGet("link", "caption") != None: + sent = app.send_photo(configGet("channel", "posting"), candidate, caption=caption, disable_notification=configGet("silent", "posting")) # type: ignore + else: + sent = app.send_photo(configGet("channel", "posting"), candidate, caption=caption, disable_notification=configGet("silent", "posting")) # type: ignore else: sent = app.send_photo(configGet("channel", "posting"), candidate, caption=caption, disable_notification=configGet("silent", "posting")) # type: ignore - else: - sent = app.send_photo(configGet("channel", "posting"), candidate, caption=caption, disable_notification=configGet("silent", "posting")) # type: ignore - elif ext_type == "video": # type: ignore + elif ext_type == "video": # type: ignore - if configGet("enabled", "caption"): - if configGet("link", "caption") != None: - sent = app.send_video(configGet("channel", "posting"), candidate, caption=caption, disable_notification=configGet("silent", "posting")) # type: ignore + if configGet("enabled", "caption"): + if configGet("link", "caption") != None: + sent = app.send_video(configGet("channel", "posting"), candidate, caption=caption, disable_notification=configGet("silent", "posting")) # type: ignore + else: + sent = app.send_video(configGet("channel", "posting"), candidate, caption=caption, disable_notification=configGet("silent", "posting")) # type: ignore else: sent = app.send_video(configGet("channel", "posting"), candidate, caption=caption, disable_notification=configGet("silent", "posting")) # type: ignore - else: - sent = app.send_video(configGet("channel", "posting"), candidate, caption=caption, disable_notification=configGet("silent", "posting")) # type: ignore - else: + else: + return + except Exception as exp: + logWrite(locale("post_exception", "console", locale=configGet("locale_log")).format(str(exp), format_exc())) + if configGet("error", "reports"): + app.send_message(configGet("admin"), locale("post_exception", "message", locale=configGet("locale")).format(exp, traceback.format_exc())) # type: ignore return index["sent"].append(candidate_file) @@ -199,7 +205,7 @@ def send_content(): logWrite(locale("post_exception", "console", locale=configGet("locale_log")).format(str(exp), format_exc())) if configGet("error", "reports"): app.send_message(configGet("admin"), locale("post_exception", "message", locale=configGet("locale")).format(exp, traceback.format_exc())) # type: ignore - pass + return # Work in progress From 8ae50a4f97c6881994c51f65e1714f8383093e2d Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Wed, 5 Oct 2022 21:36:59 +0200 Subject: [PATCH 7/8] Low number of files in queue reminder --- locale/en.json | 3 ++- locale/uk.json | 3 ++- poster.py | 3 +++ 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/locale/en.json b/locale/en.json index 23d3833..7e447ba 100644 --- a/locale/en.json +++ b/locale/en.json @@ -22,7 +22,8 @@ "document_too_large": "File you've sent is too large. Please submit files not bigger than {0} MB", "mime_not_allowed": "File type not allowed. Please, consider using one of these: {0}", "post_exception": "Could not send content due to `{exp}`\n\nTraceback:\n```{0}```", - "post_empty": "Could not send content: `Queue folder is empty or contains only unsupported or already sent files.`" + "post_empty": "Could not send content: `Queue folder is empty or contains only unsupported or already sent files.`", + "post_low": "Low amount of content: `There are only {0} files left in the queue.`" }, "button": { "sub_yes": "✅ Accept", diff --git a/locale/uk.json b/locale/uk.json index 1c9aa63..378eb93 100644 --- a/locale/uk.json +++ b/locale/uk.json @@ -22,7 +22,8 @@ "document_too_large": "Надісланий файл завеликий. Будь ласка, надсилайте файли не більше {0} Мб", "mime_not_allowed": "Тип файлу не дозволений. Розгляньте можливість використання одного з цих: {0}", "post_exception": "Не вдалося надіслати контент через `{exp}`\n\nTraceback:\n```{0}```", - "post_empty": "Не вдалося надіслати контент: «Папка черги порожня або містить лише непідтримувані або вже надіслані файли»." + "post_empty": "Не вдалося надіслати контент: `Папка черги порожня або містить лише непідтримувані або вже надіслані файли`.", + "post_low": "Мала кількість контенту: `Залишилось всього {0} файлів в черзі.`" }, "button": { "sub_yes": "✅ Прийняти", diff --git a/poster.py b/poster.py index b128c06..b341ab9 100644 --- a/poster.py +++ b/poster.py @@ -138,6 +138,9 @@ def send_content(): if len(list_queue) > 0: candidate_file = choice(list_queue) candidate = configGet("queue", "locations")+sep+candidate_file + if len(list_queue) <= 10: + if configGet("error", "reports"): + app.send_message(configGet("admin"), locale("post_low", "message", locale=configGet("locale"))) # type: ignore else: logWrite(locale("post_empty", "console", locale=configGet("locale_log"))) if configGet("error", "reports"): From 11255bbbd007781898a0c21e0157a7e911ba22b4 Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Wed, 5 Oct 2022 21:37:37 +0200 Subject: [PATCH 8/8] Pagination fixed --- poster.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/poster.py b/poster.py index b341ab9..2fa78dd 100644 --- a/poster.py +++ b/poster.py @@ -139,8 +139,8 @@ def send_content(): candidate_file = choice(list_queue) candidate = configGet("queue", "locations")+sep+candidate_file if len(list_queue) <= 10: - if configGet("error", "reports"): - app.send_message(configGet("admin"), locale("post_low", "message", locale=configGet("locale"))) # type: ignore + if configGet("error", "reports"): + app.send_message(configGet("admin"), locale("post_low", "message", locale=configGet("locale"))) # type: ignore else: logWrite(locale("post_empty", "console", locale=configGet("locale_log"))) if configGet("error", "reports"):