@danchik1654

Телеграм бот водяной знак?

from PIL import Image, ImageEnhance, ImageDraw, ImageFont
import telebot
import os
import time
import config
from telebot import types


bot = telebot.TeleBot(config.TOKEN)
images = dict()


def add_watermark_imp(image, watermark, opacity=1, wm_interval=0):
    assert opacity >= 0 and opacity <= 1
    if opacity < 1:
        if watermark.mode != 'RGBA':
            watermark = watermark.convert('RGBA')
        else:
            watermark = watermark.copy()
        alpha = watermark.split()[3]
        alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
        watermark.putalpha(alpha)
    layer = Image.new('RGBA', image.size, (0,0,0,0))
    layer.paste(watermark, (0, 0))
    return Image.composite(layer,  image,  layer)


def add_watermark(image_path, watermark_path):
    img = Image.open(image_path) 
    watermark = Image.open(watermark_path)
    watermark = watermark.resize((100,100), Image.ANTIALIAS)
    result = add_watermark_imp(img,watermark)
    new_path = image_path + '_' + '.png'
    result.save(new_path)
    return new_path


def clear_content(chat_id): 
    try:
        for img in images[chat_id]:
            os.remove(img)
    except Exception as e:
        time.sleep(3)
        clear_content(chat_id)
    images[chat_id] = []



@bot.message_handler(content_types=['text']) 
def start(message):
    if(message.text == "/start"):
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        btn1 = types.KeyboardButton("Фото")
        btn2 = types.KeyboardButton("Текст")
        markup.add(btn1,btn2)
        bot.send_message(message.chat.id, text="Привет".format(message.from_user))
        bot.send_message(message.chat.id, text="Выбери тип водяного знака".format(message.from_user), reply_markup=markup)
        bot.register_next_step_handler(message, func)
    else:
        bot.send_message(message.chat.id, text="Напиши /start ")

@bot.message_handler(content_types=['text'])
def func(message):
    if(message.text == "Фото"):
        bot.send_message(message.chat.id, text="Отправь мне 1 фото водяной знак и 2 фото")
        bot.register_next_step_handler(message, handle_docs_photo)
    elif(message.text == "Текст"):
        bot.send_message(message.chat.id, text="Отправь мне фото и текст")
        bot.register_next_step_handler(message, watertext)
    else:
        bot.send_message(message.chat.id, text="На такую комманду я не запрограммировал..")

@bot.message_handler(content_types=["photo"]) #photo download
def handle_docs_photo(message):
    print(message.photo[:-2])
    images[str(message.chat.id)] = []
    try:
        file_info = bot.get_file(message.photo[len(message.photo)-1].file_id)
        downloaded_file = bot.download_file(file_info.file_path)

        src = 'D:/Python/TeleGramWaterMurkBot/files/' + file_info.file_path

        with open(src, 'wb') as new_file:
            new_file.write(downloaded_file)

        bot.reply_to(message,"Фото добавлено")
        images[str(message.chat.id)].append(src)  
    except Exception as e:
        bot.send_message(message.chat.id, text="ОшибОчка")
    time.sleep(2)
    print('img: ', images)
    reply_img = ''    
    if (len(images[str(message.chat.id)]) == 2):
        reply_img = add_watermark(images[str(message.chat.id)][1], images[str(message.chat.id)][0])
        images[str(message.chat.id)].append(reply_img)
        bot.send_photo(message.chat.id, open(reply_img, 'rb'))
        clear_content(str(message.chat.id))
        

#текст
textov = dict()
downloaded_file1 = '';

@bot.message_handler(content_types=['photo'])
def watertext(message):
    try:
        file_info = bot.get_file(message.photo[len(message.photo) - 1].file_id)
        downloaded_file1 = bot.download_file(file_info.file_path)
        src = 'D:/Python/TeleGramWaterMurkBot/files/' + file_info.file_path
        with open(src, 'wb') as new_file:
            new_file.write(downloaded_file1) 
        bot.reply_to(message,"Фото добавлено")
        bot.register_next_step_handler(message, get_text)
        time.sleep(2)
        
        
    except Exception as e:
        bot.send_message(message.chat.id, text="ОшибОчка")
        print('img: ', textov)

txt = '';

def get_text(message, content_types=['text']):  
    global txt;
    txt = message.text
    bot.send_message(message.chat.id, text = "done" )
    bot.register_next_step_handler(message, watermark_text)



def watermark_text(message, content_types=['photo','text']):
    print(message.photo[:-1])
    textov[str(message.chat.id)] = []
    try:
        txt1 = Image.open(downloaded_file1)
 
        # make the image editable
        d = ImageDraw.Draw(photo)
 
        black = (3, 8, 12)
        font = ImageFont.truetype("AldrichRegular.ttf", 82)
        d.text(pos, text, fill=black, font=font)
    
        

    
        d.text((x,y), text, fill=(255,255,255, 125), font=font)
        watermarked2 = Image.alpha_composite(txt1, txt) 
        watermarked2.save(output_image_path)
        textov[str(message.chat.id)].append(src)
    except Exception as e:
        bot.send_message(message.chat.id, text="ОшибОчка")
    time.sleep(2)
    reply_txt1 = ''  
    if (len(textov[str(message.chat.id)]) == 1):
        reply_txt = watermark_text(textov[str(message.chat.id)])
        
        bot.send_photo(message.chat.id, open(reply_txt, 'rb'))
        clear_content(str(message.chat.id))


bot.polling(none_stop=True, interval=0)

Получился такой вот бот , он работает так :
При получении команды /start он приветствует и просит выбрать что использовать в качестве водяного знака - фото или текст , с фото у меня проблем нет , все работает , но с текстом нет . То есть когда нажимаешь на кнопку текст ты должен отправить фото и текст и получить фото с водяным знаком , но вот на этом моменте я застрял , он ничего не пишет (ошибки) , но и не отправляет фото
  • Вопрос задан
  • 546 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы