S
S
serogapelmeshek2020-02-25 23:38:00
Python
serogapelmeshek, 2020-02-25 23:38:00

How to create a bot to add captions to photos?

Good day.
I want to create a telegram bot that will take a photo sent by the user, insert a random inscription on it (from the prepared ones) and then send it back to the user.
Some examples:
@vsratoslavbot
@super_rjaka_demotivator_bot



Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Karbivnichy, 2020-02-25
@serogapelmeshek

This is the simplest code with 30 lines as an example!
Download picture 1.jpg Then put any font (preferably handwritten) "font.ttf" into the folder with the script

import telebot
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

token = 'Здесь нужно вписать токен вашего бота'
bot = telebot.TeleBot(token)

def generate_doc(first_name, second_name):

  img = Image.open('1.jpg')

  font = ImageFont.truetype('font.ttf',30) # Загрузка шрифта и установка размера
  font_color = (74,75,69) # Цвет шрифта
  first_name_pos = (585,172) # Координаты первой буквы фамилии на картинке 1.jpg
  second_name_pos = (505,205) # Координаты первой буквы имени

  drawing = ImageDraw.Draw(img)
  drawing.text(first_name_pos,first_name,font=font,fill=font_color)
  drawing.text(second_name_pos,second_name,font=font,fill=font_color)

  return img

@bot.message_handler(content_types=['text'])
def repeat_all_message(message):

  string = message.text
  s = string.split(' ')
  if len(s) == 3:
    image = generate_doc(s[0],s[1]+' '+s[2])
    image.save('test.jpg')
    bot.send_photo(message.chat.id,photo=open('test.jpg','rb'))
  else:
    bot.send_message(message.chat.id,'Ошибка! Введите имя, фамилию и отчество через пробел.')

if __name__ == '__main__':
  bot.polling(none_stop=True)

5e5687658a1d7075945855.png

I
Igor Makhov, 2020-02-25
@Igorgro

Well, I would do this: the bot will save the photo from the user in a temporary directory, then using imagemagick (can be called using os.system) overlays the inscription on the photo and sends it back.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question