How to Make OpenAI Assistant Send Images to Telegram Bot?

Hello everyone,

I have a Python script that connects an OpenAI Assistant with a Telegram bot. The assistant is supposed to generate an image for each scene and send it to the Telegram bot. However, the problem is that the assistant does not send images, only text responses.

I need help modifying the code so that the generated images appear in the Telegram bot. Any guidance or code snippets would be greatly appreciated!

Thanks in advance!

You can write a program that takes the results from openai API and then communicates with botfather…

Too tired to test it… but something like this…

import telebot
import openai
import requests

# Your API keys
TELEGRAM_BOT_TOKEN = "YOUR_TELEGRAM_BOT_TOKEN"
OPENAI_API_KEY = "YOUR_OPENAI_API_KEY"

# Initialize the bot
bot = telebot.TeleBot(TELEGRAM_BOT_TOKEN)
openai.api_key = OPENAI_API_KEY

@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
    # Responds to the start/help command with a welcome message
    bot.reply_to(message, "Hello! Send me a description, and I'll generate an image for you.")

@bot.message_handler(func=lambda message: True)
def generate_image(message):
    try:
        prompt = message.text  # Uses user input as the image description
        bot.reply_to(message, "Please wait, generating your image...")

        # Sends a request to OpenAI's DALL·E API to generate an image
        response = openai.Image.create(
            prompt=prompt,
            n=1,
            size="1024x1024"
        )

        # Extracts the image URL from the response
        image_url = response["data"][0]["url"]

        # Downloads the image
        image_data = requests.get(image_url).content
        with open("generated_image.png", "wb") as file:
            file.write(image_data)

        # Sends the generated image to the user
        with open("generated_image.png", "rb") as photo:
            bot.send_photo(message.chat.id, photo)

    except Exception as e:
        # Handles errors and sends an error message to the user
        bot.reply_to(message, f"Error: {e}")

# Starts the bot and listens for messages
print("Bot is running...")
bot.polling()