Menu

How to Deploy an AI-Powered Telegram Bot for Free (with blueprint!)

In this post, I’ll walk you through a blueprint for building a Telegram bot that leverages the power of an LLM (using Gemini in this case, as it provides a free API key). I originally built this blueprint to deploy a bot for learning languages, and now you can use it for your own purposes and extend it to develop any AI based telegram bot application you want.

Integrating AI into messaging platforms like Telegram opens up incredible possibilities, and this flexible blueprint provides a strong foundation for building intelligent and interactive bots. It’s not limited to a specific AI model or database — it’s designed for adaptability, making it easy to customize and expand based on your needs. Unleashing the Power of AI on Telegram.

This project provides a robust foundation for creating intelligent and interactive Telegram bots. It leverages FastAPI for handling Telegram webhook requests and emphasizes configurability across development and production environments.

Github: https://github.com/yaruchyo/telegram_bot_blueprint

Key Features

  • Telegram Integration: Seamlessly handles Telegram bot updates via webhooks, ensuring real-time interaction with users.
  • LLM Agnostic Architecture: Connect any LLM you want! The core is designed to be adaptable to various AI models.
  • Gemini Integration (Example): Included is an example integration with Google’s Gemini language model (free API access!) to get you started. The GeminiLLM class manages communication with the Gemini API, but you can easily swap this out for another LLM.
  • Environment-Based Configuration: Manages sensitive information like API keys through .env files and environment variables, promoting secure and manageable configurations.
  • Basic Command Handling: Equipped with a /start command and handles text input from users, providing a foundation for more complex interactions.
  • Inline Keyboard Support: Enhances the user experience with inline keyboards for interactive options and streamlined navigation.
  • Modular Design: Organizes concerns into distinct modules, promoting code clarity, maintainability, and scalability.
  • MongoDB Integration (Optional): You can connect MongoDB if needed to persist data and enhance bot functionality. The MongoDB connector offers methods for inserting, finding, updating, and deleting documents.
  • Authentication Decorator: Includes an authenticator decorator as a placeholder for implementing your own authentication logic, securing your bot against unauthorized access.

Why This Blueprint?

  • Flexibility: Whether you prefer Gemini, OpenAI, or another LLM, this blueprint can accommodate your choice.
  • Scalability: The modular design allows you to easily add new features and functionality as your bot evolves.
  • Free Deployment: This setup allows free deployment using Vercel (all necessary Vercel files are included).

Getting Started

1. Clone the Repository

git clone https://github.com/your-repo/telegram_bot_blueprint.git # Replace with your repo
cd telegram_bot_blueprint

2. Configuration is Key

2.1 Create the .env File

Duplicate the .env_example file and rename it to .env. Then, fill in the required variables.

2.2 Obtain the Gemini API Key

Log in to Google AI Studio with your Google account and click Get API Key to generate your key.

2.3 Generate the Telegram Token

To create a Telegram token for your bot, follow these steps:

2.3.1 Open Telegram and Start a Chat with BotFather

  1. Open Telegram and search for BotFather
  2. Click on the verified BotFather account and start a chat.
  3. Type /start and send the message.

2.3.2: Create a New Bot

  1. Type /newbot and send the message.
  2. BotFather will ask for a name for your bot. This can be any name, such as “MyCoolBot.
  3. Next, BotFather will ask for a username for your bot. It must be unique and must end in bot (e.g., MyCoolBot_bot).

2.3.3 Get the Token

  1. Once you provide a valid name and username, BotFather will generate an API token for your bot.
  2. The token will look like this:
1234567890:ABCDEFGHIJKLMNOQRSTUVWXYZ1234567890

In blueprint, you can develop and test your code using a separate development bot while maintaining an isolated environment for production. To enable this, generate two Telegram tokens.

If you prefer to use a single bot for both development and production, simply use the same token for TELEGRAM_TOKEN and TELEGRAM_TOKEN_TEST.

2.3 Defining the Environment

You can choose between a production or development environment.

  • Selecting development will use environment variables with the TEST suffix.
  • Selecting production will use the main environment variables.

Example Configuration


ENV=development
GEMINI_API_KEY=AIzaSyDE6fGWaQkiP7znYclWq-XcVe-vZozpUj5

# Production Environment
# ________________________
TELEGRAM_TOKEN=1234567890:ABCDEFGHIJKLMNOQRSTUVWXYZ1234567890

# Development Environment
# ________________________
TELEGRAM_TOKEN_TEST=1234567890:ABCDEFGHIJKLMNOQRSTUVWXYZ1234567890

Note: You can also specify the Mongo DB env files if needed to connect MongoDB. The MongoDB connector offers methods for inserting, finding, updating, and deleting documents

#mongodb env variables

MONGO_DB_USER=
MONGO_DB_PASS=
MONGO_DB_REST_URL=
MONGO_DB_NAME=

3. Create a Virtual Environment

python3.11 -m venv venv
source venv/bin/activate # Linux/macOS
venv\Scripts\activate # Windows

Alternatively, using conda:

conda create --name telegramBotBlueprint python=3.11
conda activate telegramBotBlueprint

4. Install Dependencies

pip install -r requirements.txt

Running the Bot

1. Launch the Application

python run.py

OR

uvicorn run:app --host 0.0.0.0 --port 80 --reload

Now, you can navigate to your Telegram bot and test it!

Note: For debugging purposes, you can start the debugging process within /telegram_package/entrypoint_layer/bot_router.

In debug mode, you can set breakpoints to better understand the data types you receive.

Deploying with Vercel’s serverless platform is quick and straightforward.

~Assuming you already have the account in Vercel~

Vercel offers two deployment options:

  1. Via Vercel CLI — You can deploy the blueprint directly without forking it into your Git repository.
  2. Via Vercel Deployment Center (Frontend) — By forking the repository and deploying through the web. Your application will automatically update with any commits to the main branch. You can adjust this behavior in the Vercel deployment settings.

~ Via Vercel CLI

cd telegram_bot_blueprint # navigate to the project
sudo npm install -g vercel # install vercel packages
vercel login # follow login instruction
vercel # to deploy the project

Here are the steps to deploy the vercel project over the terminal

~ Via Vercel Deployment Center (Frontend)

  • Connect your vercel account to Github
  • Select the project you want to create

Add the Environment Variables

It doesn’t matter whether you’ve deployed via the CLI or the frontend — you still need to specify the environment variables.

To do this, navigate to Settings > Environment Variables. If you’re deploying via the web, follow the steps shown in the image below.

If everything is deployed correctly, you should be able to navigate to the vercel domain and see the message:
{"message":"Hello World"}

Set the Webhook

After a successful deployment, configure the Telegram webhook URL.

Note: Replace <TELEGRAM TOKEN> (from BotFather) and <VERCEL URL> (which will appear after deployment) with the appropriate values, then run the following code in the terminal:

curl -X GET "https://api.telegram.org/bot<TELEGRAM TOKEN>/setWebhook?url=<VERCEL URL>/webhook"

If you set the webhook correctly, you get the following message

{"ok":true,"result":true,"description":"Webhook was set"}%    

To delete the Telegram webhook:

curl -X GET "https://api.telegram.org/bot<TELEGRAM TOKEN>/deleteWebhook?drop_pending_updates=True"

Results

If everything was set up correctly, you get your own GPT chat in the Telegram.

Structured Output

The gemini_llm.py includes functions to generate structured output for Gemini!

Onward and Upward

With this blueprint, you can build any LLM-based Telegram bot you envision!

This blueprint empowers you to create feature-rich, AI-powered Telegram bots that stand out. Its modular design, LLM flexibility, and Vercel-ready configuration make it an ideal starting point for your next bot project. Take this blueprint and mold it to your vision.