feat: Добавлены ограничения на длину текста и улучшена обработка ошибок
This commit is contained in:
+28
-4
@@ -2,10 +2,15 @@ from dotenv import load_dotenv
|
||||
from sys import exit as sexit
|
||||
import os
|
||||
import json
|
||||
import html
|
||||
|
||||
import telebot
|
||||
import qrcode
|
||||
|
||||
CAPTION_LIMIT = 1024
|
||||
MESSAGE_LIMIT = 4096
|
||||
QR_TEXT_LIMIT = 770
|
||||
|
||||
# Загрузить переменные из файла .env и language.json
|
||||
load_dotenv()
|
||||
with open('./src/language.json', 'r', encoding='utf-8') as file:
|
||||
@@ -33,7 +38,7 @@ def gen_qr(text, id):
|
||||
# Создаем экземпляр класса QRCode
|
||||
qr = qrcode.QRCode(
|
||||
version=1,
|
||||
error_correction=qrcode.constants.ERROR_CORRECT_H,
|
||||
error_correction=qrcode.constants.ERROR_CORRECT_M,
|
||||
box_size=10,
|
||||
border=1,
|
||||
)
|
||||
@@ -48,14 +53,33 @@ def gen_qr(text, id):
|
||||
|
||||
@bot.message_handler(content_types=['text'])
|
||||
def generate_qr_code(mess):
|
||||
if len(mess.text) > QR_TEXT_LIMIT:
|
||||
bot.send_message(
|
||||
mess.chat.id,
|
||||
language['text_too_long'].format(limit=QR_TEXT_LIMIT, chars=len(mess.text))
|
||||
)
|
||||
return
|
||||
|
||||
try:
|
||||
gen_qr(mess.text, mess.from_user.id)
|
||||
text = language['qr_info'].format(
|
||||
text=mess.text,
|
||||
words=len(mess.text.split()),
|
||||
except (qrcode.exceptions.DataOverflowError, ValueError):
|
||||
bot.send_message(mess.chat.id, language['qr_overflow'])
|
||||
return
|
||||
|
||||
words = len(mess.text.split())
|
||||
chars = len(mess.text)
|
||||
text = language['qr_info'].format(
|
||||
text=html.escape(mess.text),
|
||||
words=words,
|
||||
chars=chars
|
||||
)
|
||||
with open(photoName, 'rb') as qr_photo:
|
||||
if len(text) <= CAPTION_LIMIT:
|
||||
bot.send_photo(mess.chat.id, qr_photo, caption=text, parse_mode='html')
|
||||
else:
|
||||
bot.send_photo(mess.chat.id, qr_photo)
|
||||
if len(text) > MESSAGE_LIMIT:
|
||||
text = language['qr_info_short'].format(words=words, chars=chars)
|
||||
bot.send_message(mess.chat.id, text, parse_mode='html')
|
||||
os.remove(photoName)
|
||||
|
||||
|
||||
+4
-1
@@ -3,5 +3,8 @@
|
||||
"no_token": "Отсутствует токен телеграм бота. Загрузи токен в переменные окружения и бот сможет начать работу",
|
||||
"bot_started": "Бот запущен",
|
||||
"bot_stopped": "Бот отключён",
|
||||
"qr_info": "<b>Сообщение:</b> {text}\n<b>Слов в сообщении:</b> {words}\n<b>Символов в сообщении:</b> {chars}"
|
||||
"qr_info": "<b>Сообщение:</b> {text}\n<b>Слов в сообщении:</b> {words}\n<b>Символов в сообщении:</b> {chars}",
|
||||
"qr_info_short": "<b>Слов в сообщении:</b> {words}\n<b>Символов в сообщении:</b> {chars}",
|
||||
"text_too_long": "Текст слишком длинный для QR-кода. Максимум {limit} символов, а тут {chars}",
|
||||
"qr_overflow": "Не получилось создать QR-код: текст слишком большой)"
|
||||
}
|
||||
Reference in New Issue
Block a user