Answer the question
In order to leave comments, you need to log in
How to write entered values in Python when creating a bot?
Hello. I am new to python and have a question. Actually, this is an image processing bot. The current version, which is presented below, works (it should work this way). The main question is the following - how to add the ability for the user to enter values?
There are rgbmax
also rgbmin
. In this code, they are set by me, but it is necessary to add the ability for the user to enter their values and after that the image processing is already performed. That is, the process looks like this: the user sends a photo > the message "Enter a value from 0 to 255" comes up > he sends, the range from 0 to 255 is checked, written to rgbmax
, the message is sent: "Enter a second value" > the value is sent, again checking and if correct, it is written torgbmin
> the photo is processed and sent to the user. I can not figure out how to implement the recording of these entered values. It would be very grateful for the help if prompted an idea how to implement it.
Full code:
import telebot
import os
import urllib.request
from PIL import Image
import numpy as np
TOKEN = 'тут токен бота, просто вырезал его'
bot = telebot.TeleBot(TOKEN)
result_storage_path = 'temp'
img = 'https://i.ibb.co/zXxYh6G/22.png'
img1 = 'https://i.ibb.co/JxYCPdg/30-240.jpg'
@bot.message_handler(commands=['start'])
def start_message(message):
bot.send_message(message.chat.id, 'Приветствую! Ботом я являюсь, обрабатывать твои фото создан я! ')
bot.send_message(message.chat.id, 'Чтобы продолжить, отправь мне любое изображение')
bot.send_message(message.chat.id, 'Чтобы понять как я работаю, используй команду /how')
@bot.message_handler(commands=['how'])
def start_message(message):
bot.send_message(message.chat.id,
'Я могу повысить контраст изображения. Для того, чтобы это сделать, тебе нужно ввести 2 значения.')
bot.send_message(message.chat.id, '1️⃣Первое значение - точка черного (самая темная точка твоей фотографии)')
bot.send_message(message.chat.id, '2️⃣Второе значение - точка белого (самая светлая точка твоей фотографии)')
bot.send_message(message.chat.id,
'❗️Главное ограничение - диапазон от 0 до 255. Чем больше разница между первым и вторым значением, '
'тем меньше контраст. Давай покажу, как это работает')
bot.send_photo(message.chat.id, img)
bot.send_message(message.chat.id,
'❗️И да, не забывай, если второе значение будет больше первого, то получится страшная инверсия '
'(примерно такая)')
bot.send_photo(message.chat.id, img1)
bot.send_message(message.chat.id, '✅Если всё понятно, то загрузи фото!')
@bot.message_handler(content_types=['photo'])
def handle_photo(message):
cid = message.chat.id
image_name = save_image_from_message(message)
bot.send_message(cid, 'Отлично, я сохранил твое изображение! Для того, чтобы продолжить - введи первое значение')
image_name_new = handle_image(image_name)
bot.send_photo(message.chat.id, open('{0}/{1}'.format(result_storage_path, image_name_new), 'rb'),
'Ура, получилось!')
bot.send_message(message.chat.id, 'Попробуем еще разок? :)')
cleanup_remove_images(image_name, image_name_new)
def save_image_from_message(message):
image_id = get_image_id_from_message(message)
file_path = bot.get_file(image_id).file_path
image_url = "https://api.telegram.org/file/bot{0}/{1}".format(TOKEN, file_path)
if not os.path.exists(result_storage_path):
os.makedirs(result_storage_path)
image_name = "{0}.jpg".format(image_id)
urllib.request.urlretrieve(image_url, "{0}/{1}".format(result_storage_path, image_name))
return image_name
def get_image_id_from_message(message):
return message.photo[len(message.photo) - 1].file_id
def handle_image (image_name):
content_image = Image.open("{0}/{1}".format(result_storage_path, image_name))
rgbmax = 230
rgbmin = 15
R, G, B = content_image.split()
rout = R.point(lambda i: (i - rgbmin) / (rgbmax - rgbmin) * 255)
gout = G.point(lambda i: (i - rgbmin) / (rgbmax - rgbmin) * 255)
bout = B.point(lambda i: (i - rgbmin) / (rgbmax - rgbmin) * 255)
result_img_pillow = Image.merge("RGB", (rout, gout, bout))
image_name_new = "handled_image_" + image_name
result_img_pillow.save("{0}/{1}".format(result_storage_path, image_name_new))
return image_name_new
def cleanup_remove_images(image_name, image_name_new):
os.remove('{0}/{1}'.format(result_storage_path, image_name))
os.remove('{0}/{1}'.format(result_storage_path, image_name_new))
bot.polling()
Answer the question
In order to leave comments, you need to log in
def rgb(message):
msg = bot.send_message(chat_id, 'введите rgbmin')
bot.register_next_step_handler(msg, rgbmin)
def rgbmin(message):
ur = user_rgbmin = message.text
If ur > 255 or ur < 0:
msg = bot.send_message(chat_id, 'rgbmin должен быть в интервале от 0 до 255, введите ещё раз')
bot.register_next_step_handler(msg, rgbmin)
return
msg = bot.send_message(chat_id, 'введите rgbmax')
bot.register_next_step_handler(msg, rgbmax)
def rgbmax(message):
‘Аналогично def rgbmin(message)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question