Search code examples
pythontelegram-botpy-telegram-bot-api

Im trying to make my telegram bot send a profile picture for every username he recive but I keep gettig this Error


I know that "UserProfilePhoto" is an object and cant be send on telegram but I dont know how to transform it in to photos and send it I keep getting this Error:

TypeError: a bytes-like object is required, not 'UserProfilePhotos'

import os
import telebot

API_KEY = "XXXXXXXXX"
bot = telebot.TeleBot(API_KEY)

#This function tries to get the user profile photo and I think here is the error

def send_photo(user):
    user_photos = bot.get_user_profile_photos(user)
    return user_photos

#This function finds the username in the message the bot recived 

def find_at(message):
    for text in message:
        if "@" in text:
            return text

@bot.message_handler(func=lambda msg: "@" in msg.text)
def answer(message):
    text = message.text.split()
    at_text = find_at(text)
    user_id = message.from_user.id
    ANSWER = send_photo(user_id)
    bot.send_photo(message, ANSWER)
bot.polling()

Solution

  • The userProfilePhotos object represents a user’s profile pictures. It has a list called photos which contains user profile photos and every profile photo is a list of three PhotoSize objects and they are comparable in terms of equality. So you can do this:

    def get_photos(user):
        user_photos = bot.get_user_profile_photos(user)
        user_photos = user_photos.photos
        photos_ids = []
        for photo in user_photos:
            photos_ids.append(photo[0].file_id)
        return photos_ids
    
    @bot.message_handler(func=lambda msg: "@" in msg.text)
    def answer(message):
        text = message.text.split()
        at_text = find_at(text)
        user_id = message.from_user.id
        photos_ids = get_photos(user_id)
        for photo_id in photos_ids:
            bot.send_photo(message.chat.id, photo_id)