Building and Deploying a Telegram Chatbot with Google Generative AI

In today's digital age, chatbots have become an integral part of many businesses and services, offering instant assistance and engagement for users. With advancements in artificial intelligence, creating sophisticated chatbots has become more accessible than ever. In this blog post, we'll walk through the process of building and deploying a Telegram chatbot powered by Google's Generative AI.

Setting Up the Environment

To get started, ensure you have Node.js installed on your system. We'll be using Express.js, a popular web application framework for Node.js, along with other libraries for handling HTTP requests and interacting with the Telegram Bot API. Lets install the necessary dependencies first :

npm init -y
npm install express body-parser 
npm install @google/generative-ai node-telegram-bot-api

After installing these, lets setup our project. Lets create a file named script.js and add these dependencies to it.

import express from 'express';
import bodyParser from 'body-parser';
import { GoogleGenerativeAI } from "@google/generative-ai";
import node-telegram from "node-telegram-bot-api";

const TelegramBot = node-telegram;

// Create an Express app
const app = express();

// Body parser middleware to parse JSON bodies
app.use(bodyParser.json());

Now, we will need the Gemini-Pro API Key and the telegram bot token for this project. The Gemini-Pro API Key can be obtained from https://ai.google.dev/ and the telegram bot token can be generated by creating a chat with @BotFather on Telegram and using the /newbot command.

Lets add them to our Bot:

const API_KEY = "SAMPLE-API-KEY";
const token = 'SAMPLE-TELEGRAM-BOT-TOKEN';

// Create a new Telegram bot instance
const bot = new TelegramBot(token);

Handling Incoming Telegram Messages

Message handling will be done using Webhooks. We'll set up an endpoint for Telegram to send updates to our bot. When a message is received, we'll process it using Google Generative AI and send back a response. This can be run locally if modified for it.

// Set up webhooks
bot.setWebHook(`https://DOMAIN_URL/bot${token}`);
// For local Setup : DOMAIN_URL = localhost:3000

app.post(`/bot${token}`, (req, res) => {
  const { message } = req.body;
  if (message && message.text) {
    handleMessage(message);
  }
  res.sendStatus(200);
});

Now, we have received a message through this method, lets complete the function to handle the message using Google Generative AI.

async function handleMessage(msg) {
  const chatId = msg.chat.id;
  const messageText = msg.text;

  const generateResponse = await geminipro(messageText);
  bot.sendMessage(chatId, generateResponse, { parse_mode: 'Markdown' });
}

The geminipro() makes the call to the Google API to generate the response for the given message. The code for creating that call and passing on the message can be written as follows:

async function geminipro(userMessage) {
  var genAI = new GoogleGenerativeAI(API_KEY);
  var model = genAI.getGenerativeModel({ model: "gemini-pro" });
  var prompt = userMessage;
  var response;
  try {
        const result = await model.generateContent(prompt);
        response = await result.response;
        response = response.text();
  } catch (error) {
        response = "Something went wrong";
  }
  console.log(response); // To check the final response
  return response;
}

This function calls the Gemini-Pro model and passes on the response to the handlemessage() function, which in turn sends a response back to the telegram user.

Finally lets start the Express server:

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

And there we have our very own Telegram Bot, powered by Google's Gemini Pro.

But wait! You cant keep your machine switched on 24x7 , you need to deploy this!

We can use a vast majority of cloud apps to deploy our server to, the easiest and simplest way would be using - https://render.com

To deploy on render.com , follow these steps :

  1. Create a Render Account: If you haven't already, sign up for an account on Render.com.

  2. Create a New Web Service:

    • Once logged in, click on "Create a New" at the top left corner.

    • Select "Web Service" from the dropdown menu.

  3. Configure Your Service:

    • Choose your GitHub/GitLab/Bitbucket repository where your code is hosted.

    • Render will automatically detect your repository's settings. You can choose the branch to deploy from.

    • Set the build command to npm install

    • Set the start command to node script.js.

  4. Configure Your Webhook:

  5. Test Your Bot:

    • Send a message to your Telegram Bot to test if it's responding correctly.

Voila! , now your Telegram Bot can be used by anyone around the world at anytime.

If you wanna see a working demo of this bot, you can head over to this link which is the bot i created and deployed for this project - https://t.me/telegeminiproBot

Thank you for reading this blog on creating and deploying a Telegram chatbot with Google Generative AI! We value your feedback and would love to hear your thoughts. Want to stay updated on the latest trends in AI and technology? Sign up for our newsletter and receive regular updates directly in your inbox!