Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8fdd676bb3 | |||
| 5b62112ab2 |
@@ -1,56 +0,0 @@
|
|||||||
from dotenv import load_dotenv
|
|
||||||
from sys import exit as sexit
|
|
||||||
from os import remove, getenv
|
|
||||||
|
|
||||||
import telebot
|
|
||||||
import qrcode
|
|
||||||
|
|
||||||
# Загрузить переменные из файла .env
|
|
||||||
load_dotenv()
|
|
||||||
# Получить значение переменной
|
|
||||||
API_TOKEN = getenv("API_TOKEN")
|
|
||||||
if API_TOKEN is None:
|
|
||||||
print('Отсутствует токен телеграм бота. Загрузи токен в переменные окружения и бот сможет начать работу')
|
|
||||||
sexit(1) # Завершаем программу с кодом ошибки 1
|
|
||||||
|
|
||||||
|
|
||||||
bot = telebot.TeleBot(API_TOKEN)
|
|
||||||
photoName = None
|
|
||||||
|
|
||||||
@bot.message_handler(commands=['start'])
|
|
||||||
def start(mess):
|
|
||||||
bot.send_message(mess.chat.id, '''Привет. Я генерирую QR коды. Отправь мне текст и я его преобразую.
|
|
||||||
Код проекта можно посмотреть в <a href="https://github.com/IliaMiheev/bot_qr">репозитории</a> на GitHub''', parse_mode='html')
|
|
||||||
|
|
||||||
|
|
||||||
def gen_qr(text, id):
|
|
||||||
global photoName
|
|
||||||
photoName = f"qrcode_{id}.png"
|
|
||||||
# Создаем экземпляр класса QRCode
|
|
||||||
qr = qrcode.QRCode(
|
|
||||||
version=1,
|
|
||||||
error_correction=qrcode.constants.ERROR_CORRECT_H,
|
|
||||||
box_size=10,
|
|
||||||
border=1,
|
|
||||||
)
|
|
||||||
# Добавляем данные в QR-код
|
|
||||||
qr.add_data(text)
|
|
||||||
qr.make(fit=True)
|
|
||||||
# Создаем изображение QR-кода
|
|
||||||
img = qr.make_image(fill_color="black", back_color="white")
|
|
||||||
# Сохраняем изображение QR-кода
|
|
||||||
img.save(photoName)
|
|
||||||
|
|
||||||
|
|
||||||
@bot.message_handler(content_types=['text'])
|
|
||||||
def generate_qr_code(mess):
|
|
||||||
gen_qr(mess.text, mess.from_user.id)
|
|
||||||
text = f'<b>Сообщение:</b> {mess.text}\n<b>Слов в сообщении:</b> {len(mess.text.split())}\n<b>Символов в сообщении:</b> {len(mess.text)}'
|
|
||||||
with open(photoName, 'rb') as qr_photo:
|
|
||||||
bot.send_photo(mess.chat.id, qr_photo)
|
|
||||||
bot.send_message(mess.chat.id, text, parse_mode='html')
|
|
||||||
remove(photoName)
|
|
||||||
|
|
||||||
print('Бот запущен')
|
|
||||||
bot.polling()
|
|
||||||
print('Бот отключён')
|
|
||||||
Binary file not shown.
@@ -0,0 +1,88 @@
|
|||||||
|
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:
|
||||||
|
language = json.load(file)
|
||||||
|
|
||||||
|
# Получить значение переменной
|
||||||
|
API_TOKEN = os.getenv("API_TOKEN")
|
||||||
|
|
||||||
|
if API_TOKEN is None or API_TOKEN == "":
|
||||||
|
print(language['no_token'])
|
||||||
|
sexit(1) # Завершаем программу с кодом ошибки 1
|
||||||
|
|
||||||
|
|
||||||
|
bot = telebot.TeleBot(API_TOKEN)
|
||||||
|
photoName = None
|
||||||
|
|
||||||
|
@bot.message_handler(commands=['start'])
|
||||||
|
def start(mess):
|
||||||
|
bot.send_message(mess.chat.id, language['start'], parse_mode='html')
|
||||||
|
|
||||||
|
|
||||||
|
def gen_qr(text, id):
|
||||||
|
global photoName
|
||||||
|
photoName = f"qrcode_{id}.png"
|
||||||
|
# Создаем экземпляр класса QRCode
|
||||||
|
qr = qrcode.QRCode(
|
||||||
|
version=1,
|
||||||
|
error_correction=qrcode.constants.ERROR_CORRECT_M,
|
||||||
|
box_size=10,
|
||||||
|
border=1,
|
||||||
|
)
|
||||||
|
# Добавляем данные в QR-код
|
||||||
|
qr.add_data(text)
|
||||||
|
qr.make(fit=True)
|
||||||
|
# Создаем изображение QR-кода
|
||||||
|
img = qr.make_image(fill_color="black", back_color="white")
|
||||||
|
# Сохраняем изображение QR-кода
|
||||||
|
img.save(photoName)
|
||||||
|
|
||||||
|
|
||||||
|
@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)
|
||||||
|
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)
|
||||||
|
|
||||||
|
print(language['bot_started'])
|
||||||
|
bot.polling()
|
||||||
|
print(language['bot_stopped'])
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"start": "Привет. Я генерирую QR коды. Отправь мне текст и я его преобразую. Код проекта можно посмотреть в <a href=\"https://github.com/IliaMiheev/bot_qr\">репозитории</a> на GitHub",
|
||||||
|
"no_token": "Отсутствует токен телеграм бота. Загрузи токен в переменные окружения и бот сможет начать работу",
|
||||||
|
"bot_started": "Бот запущен",
|
||||||
|
"bot_stopped": "Бот отключён",
|
||||||
|
"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