Ternaus: Telegram Bot

Short version:

Pictures from the database with Ternaus.com – 8.5 million images generated by Stable Diffusion.

The bot code in python is below.

Long version:

In a previous post I talked about how Chrome Extensionwhich allows you to search for generated pictures using any pictures and tests on the Internet.

I also mentioned that I plan to add Telegram bot.

On the technical side, this is a simple but useful exercise that expands the range of my technical skills.

With the grocery – telegram – this is a “different UI”, different from the site, different from the phone application.

I like how my search works. But I really don’t like that it’s inconvenient to share the results.

Yes, if you wish, you can share links like:

This is more than nothing, but I want to aggravate. I would like to share with others not only links, but also the pictures themselves.

And telegram is very convenient. Made a request, got pictures, made Forward to a friend. Magic.

The first 100 requests are free, then a symbolic 1 cent per request. It feels like just playing around and 100 is enough, and if someone needs something, then 1 cent is not money.

The code in which I cut out a piece about money.

import io
import logging
import os
from typing import Any

import aiogram
import httpx
import ujson as json
from PIL import Image
from aiogram import Bot, Dispatcher, types
from aiogram.utils.executor import start_webhook
from image2base64.converters import rgb2base64

APP_NAME = os.getenv("APP_NAME")
# webhook settings
WEBHOOK_HOST = f"https://{APP_NAME}.herokuapp.com"
WEBHOOK_PATH = f"/webhook/{TOKEN}"

# webserver settings
WEBAPP_PORT = os.getenv("PORT", default=8000)

bot = Bot(token=TOKEN)
dp = Dispatcher(bot)

headers = {
    "content-type": "application/json",
    "x-api-key": os.getenv("TERNAUS_TOKEN"),

SIMILARITY_SEARCH_API = "https://simages.info"

def get_image_data(url: str) -> types.InputMediaPhoto:
    return aiogram.types.InputMediaPhoto(url)

async def on_startup(dispatcher):
    await bot.set_webhook(WEBHOOK_URL, drop_pending_updates=True)

async def on_shutdown(dispatcher):
    await bot.delete_webhook()

async def get_result(body: dict[str, str | int]) -> dict[str, Any]:
    async with httpx.AsyncClient(headers=headers, timeout=600) as client:
        return (await client.post(SIMILARITY_SEARCH_API, data=json.dumps(body))).json()

async def photo_handler(message: types.Message) -> None:
    file_in_io = io.BytesIO()
    await (await message.photo[-1].get_file()).download(destination_file=file_in_io)
    image = Image.open(file_in_io).convert("RGB").resize((TARGET_SIZE, TARGET_SIZE))

    base64 = rgb2base64(image, quality=80)

    result = await get_result({"image": base64, "num_similar": 10})

    output = [get_image_data(item["url"]) for item in json.loads(result["body"])["images"]]
    await bot.send_media_group(message.from_user.id, output)

async def text_handler(message: types.Message) -> None:
    text = message.text.replace("/text", "").strip()

    result = await get_result({"text": text, "num_similar": 10})

    output = [get_image_data(item["url"]) for item in json.loads(result["body"])["images"]]

    await bot.send_media_group(message.from_user.id, output)

if __name__ == "__main__":

Q: Why not make everything free, why these cents?

Here, probably, so – gestalt in order to do something useful for people from the heart, I have closed the development of the Open Source library Albumentations. Now we have 16 thousand downloads per day.

The next unclosed gestalt is to make a product that makes money.

The picture of monetization in my head looks like this:

  1. If you are building a free product, but plan to sell ads or user data, then don’t try to ask for money – download the user base. Examples: Google, Facebook

  2. If the product has obvious Network Effects, then it also makes sense to download the number of users, even at a loss. Good example: PayPal. Failed: Uber, Lyft

  3. If you plan to shake up the user base and sell it to someone else so that another company puzzles with monetization, then you also don’t need to crush the growth of the user base by trying to milk a pretty penny. Example: PayPal, Kaggle. There is an idea that this is a crooked path and people get up on it out of hopelessness.

  4. If you plan to withdraw money from users in the future, then you need to ask for money now. Yes, no one will pay, and looking at the line Revenue = 0 every day is a pain. But this is a necessary pain that will make you think in the right direction.

And since Network effects are not visible, we go for option 4.

So any request to a server with a GPU that processes requests for similar images should give something. Either marketing or money.

  • Searching the site and downloading pictures are free.

  • Usage Chrome Extensionwhich allows you to search for pictures and text in my database – free.

  • API – 1 cent per successful request.

  • Telegram bot – the first 100 requests are free, then 1 cent per request.

Not that this scheme works well, but some kind of traffic, and more importantly, feedback is coming.

So who needs generated pictures that can be used for any purpose, including commercial ones – take it and use it. And I’m going to write an application for the phone. Here it is completely on the side, but it also looks like a good exercise.


Similar Posts

Leave a Reply