DEV Community

Cover image for Telegram Bot with OpenAI GPT-3.5-turbo connection
Max Sveshnikov
Max Sveshnikov

Posted on • Edited on

Telegram Bot with OpenAI GPT-3.5-turbo connection

As the world becomes increasingly digital, people are constantly looking for new ways to communicate with each other. One of the most popular messaging apps today is Telegram, which allows users to send messages, photos, and videos to each other. But what if you could do more than just send messages? What if you could have a conversation with a bot that uses artificial intelligence to understand and respond to your messages?

That's exactly what I set out to do when I created the ChatGPT telegram bot. This bot uses OpenAI's GPT-3.5-turbo connection to provide users with a more natural and human-like conversation experience. But I didn't stop there. I also incorporated context, AI painting, and Google scraping to make the bot even more powerful and versatile.

To get started, I had to obtain the necessary APIs and set environment variables. The first API I needed was the OpenAI key, which I obtained from the OpenAI website. With this key, I was able to access the GPT-3.5-turbo model, which is a powerful language model that can understand and respond to natural language input.

Next, I needed the key from Stable Diffusion, which provides AI painting services. This key allowed me to incorporate painting into the bot, which means that users can send Paint command with scene description.

Then I needed the key from replicate.com model, which provides image-to-text. With this key, I was able to incorporate OCR functionality.

Once I had all the necessary APIs and environment variables set up, I began building the bot. The first step was to create a Telegram bot using the Telegram Bot API. This API provides a simple way to create and manage bots on the Telegram platform.

const replicate = new Replicate({ token: process.env.REPLICATE_KEY });
const openai = new OpenAIApi(new Configuration({ apiKey: process.env.OPENAI_KEY }));
const bot = new TelegramBot(process.env.TELEGRAM_KEY, { polling: true });
const translation = new TranslationServiceClient();
Enter fullscreen mode Exit fullscreen mode

Next, I had to integrate the OpenAI API into the bot. This involved node-telegram-api, that receives messages from users and sends them to the OpenAI API for processing. Once the API returned a response, I had to format it and send it back to the user through the Telegram bot.

const getText = async (prompt, temperature, max_tokens, chatId) => {
    try {
        const completion = await openai.createChatCompletion({
            model: "gpt-3.5-turbo",
            messages: [{ role: "user", content: prompt }],
            max_tokens: max_tokens,
            temperature: temperature,
        });
        const response = completion?.data?.choices?.[0]?.message?.content;
        return response;
    } catch (e) {
        console.error(e.message);
    }
};
Enter fullscreen mode Exit fullscreen mode

To make the bot even more powerful, I decided to incorporate context into the conversation. This means that the bot remembers previous messages and uses them to provide more personalized responses. For example, if a user asks the bot to recommend a restaurant, the bot will remember the user's location and previous restaurant preferences to provide a more relevant recommendation.

        // Brain activity
        context[chatId] = context[chatId]?.slice(-CONTEXT_SIZE * premium(chatId)) ?? "";
        writeContext(context);

        if (msg.photo) {
            // visual hemisphere (left)
            visualToText(chatId, msg);
        }
        msg.text = msg.text?.substring(0, MAX_LENGTH * premium(chatId));
        if (msgL.startsWith("google")) {
            textToGoogle(chatId, msg.text.slice(7), msg.from?.language_code);
        } else {
            if (msgL.startsWith("draw") || msgL.startsWith("paint")) {
                // visual hemisphere (left)
                textToVisual(chatId, msgL, msg.from?.language_code);
            } else {
                // audio hemisphere (right)
                textToText(chatId, msg);
            }
        }
Enter fullscreen mode Exit fullscreen mode

With the Stable Diffusion painting and Google scraping APIs integrated, the bot became even more versatile. Users can now ask the bot to search for information on the internet and receive relevant results.

const textToVisual = async (chatId, text, language_code) => {
    if (text === "draw" || text === "paint") {
        // link between right and left hemisphere (painting)
        text = last[chatId];
    }
    if ((language_code == "ru" && !text?.startsWith("draw"))) {
        text = await translate(text, "en");
    }
    const photo = await getArt(
        text +
            (text?.startsWith("draw")
                ? ""
                : ", deep focus, highly detailed, digital painting, artstation, 4K, smooth, sharp focus, illustration")
    );
    if (photo) {
        bot.sendPhoto(chatId, photo);
    }
};

Enter fullscreen mode Exit fullscreen mode

Creating the ChatGPT telegram bot was a challenging but rewarding experience. By integrating multiple APIs and using context, stability AI painting, and Google scraping, I was able to create a bot that provides users with a more natural and human-like conversation experience. As AI technology continues to advance, I'm excited to see what new possibilities it will bring to messaging apps like Telegram.

Github here: https://github.com/msveshnikov/chatgpt

Working example: https://t.me/maxsoft_chat_bot
To try for free, please use https://t.me/maxsoft_chat_gpt_group

Top comments (0)