How to generate dall-e-3 images in the Telegram messenger

How to generate dall-e-3 images in the Telegram messenger

This code contains two asynchronous functions: generate_dalle3 and handle_command.

The generate_dalle3 function takes two arguments: message and prompt. It generates an image based on a text prompt using the DALL-E-3 model from OpenAI. First, it sends a message to the user indicating that the image generation has started. Then, it creates the image and sends it to the user. If an error occurs during the process, it is logged.

The handle_command function handles commands from the user. It takes a message from the user, splits it into words, and checks if there are at least two words in the message. If there are fewer than two words, the function sends a message with an input format error. Otherwise, it calls the generate_dalle3 function with a prompt composed of all the words in the message except the first one. If an error occurs during the process, it is sent to the user.

async def generate_dalle3(message: types.Message, prompt: str):
        sent_message = await bot.send_message(, "Generating image, please wait...")
        response = openai.Image.create(
        image_url =[0].url
        await bot.send_photo(, photo=image_url)

    except Exception as e:
        logging.error(f"Error: {e}")

How to use this function in the Telegram messenger with the /i command. Example:

async def handle_command(message: types.Message):
        input_text = message.text.split(' ')
        if len(input_text) < 2:
            await bot.send_message(
                "Incorrect input format. Enter the command /i and the value for prompt in one line, separating them with spaces. \nExample: /i cat 3D"

        prompt = ' '.join(input_text[1:])
        await generate_dalle3(message, prompt)

    except Exception as e:
        await bot.send_message(, f"An error occurred: {e}")

And here’s what we got:

how-to-generate-dall-e-3-images-in-the-telegram-And here’s what we gotmessenger



Leave a Comment