Tutorial

Build a Telegram Bot with DigitalOcean GenAI Platform Agent

Build a Telegram Bot with DigitalOcean GenAI Platform Agent

Introduction

In this tutorial, we will guide you through the process of integrating a Telegram bot with the DigitalOcean GenAI Platform. This integration enables the telegram bot to dynamically fetch information from the GenAI Platform, leveraging the knowledge base attached to it. By utilizing Python and the aiogram library, we will develop the bot and connect it to the DigitalOcean GenAI Platform.

This integration is ideal for businesses, developers, and teams who want to leverage AI to enhance their communication tools. It is particularly beneficial for those who need to provide real-time information, personalized assistance, and improve user engagement.

The need for this integration arises from the growing demand for instant access to information and personalized user experiences. By integrating a Telegram bot with the DigitalOcean GenAI Platform, you can achieve the following benefits:

  • Real-time information retrieval: The bot can instantly fetch and provide information on a wide range of topics, ensuring users have access to the most up-to-date knowledge.
  • Enhanced user experience: The integration of the GenAI Platform agent with the Telegram bot enables users to interact with the bot in a more conversational and human-like manner, making the experience more engaging and user-friendly.
  • Increased accessibility: By integrating the GenAI Platform agent with a Telegram bot, users can access a vast amount of information and knowledge without needing to navigate through complex interfaces or websites.
  • Personalized assistance: The bot can be trained to provide personalized advice and guidance based on the user’s specific needs and preferences, making it an invaluable tool for those seeking information or assistance.

Prerequisites

Before we begin, ensure you have the following:

Step 1 - Set Up a DigitalOcean GenAI Agent

You are an expert of the DigitalOcean platform. Provide well-mannered and thorough responses to the user & give accurate advice. Your main areas of expertise are in Software Engineering, Web Engineering, the cloud, and Deep Learning.

Note: You can also follow the instructions in our tutorial on How to build an AI Agent or Chatbot with GenAI Platform Integration to create an agent.

  • Once the agent is deployed and ready, copy the agent Endpoint URL and API Key for authentication.

  • Attach a Knowledge base so that the agent can use it to provide context-specific responses.

Step 2 - Create a Telegram Bot

Open Telegram and search for BotFather.

BotFather

Start a chat and send the command /newbot.

new bot chat

Follow the instructions to set up your bot and obtain the Telegram Bot Token.

bot token

Save this token as you will need it later.

Note: For detailed instructions on how to build a Telegram bot, please refer to the offical documentation on How to build a Telegram Bot.

Step 3 - Create a Virtual Environment and Install Required Dependencies

First, create a project folder for your project. This will help keep all your project files organized. For example, you can name your project folder genai_telegram_bot_project.

Next, navigate into your project folder:

cd genai_telegram_bot_project

Now, create a virtual environment for your project to isolate its dependencies. You can use the following command to create a virtual environment named genai_telegram_bot:

python -m venv genai_telegram_bot

Activate the virtual environment:

source genai_telegram_bot/bin/activate

Now, install the required Python packages:

pip install aiogram requests python-dotenv

Step 4 - Write the Python Code

We are using aiogram library, a modern and efficient Python framework for building Telegram bots using asyncio. We are using it because:

  • It supports asynchronous operations, improving performance and responsiveness.
  • It simplifies bot interaction with its built-in Dispatcher and event-based handling.
  • It provides clean, structured, and maintainable code.

Create a project folder and inside it, create a file bot.py and add the following code:

genai_telegram_bot_project/bot.py
import os
import requests
import asyncio
from aiogram import Bot, Dispatcher, types
from aiogram.types import Message
from aiogram.filters import Command
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Retrieve tokens and URLs from environment variables
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
GENAI_AGENT_URL = os.getenv("GENAI_AGENT_URL") + "/api/v1/chat/completions"
print(GENAI_AGENT_URL)  # Print the constructed GENAI_AGENT_URL for debugging purposes
GENAI_API_KEY = os.getenv("GENAI_API_KEY")

# Initialize the Telegram bot and its dispatcher
bot = Bot(token=TELEGRAM_BOT_TOKEN)
dispatcher = Dispatcher()

async def fetch_genai_response(prompt: str) -> str:
    """Sends a request to the DigitalOcean GenAI agent with the given prompt and returns the response."""
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {GENAI_API_KEY}"  # Use the API key for authentication
    }
    payload = {
        "messages": [
            {"role": "user", "content": prompt}  # Prepare the prompt for the GenAI agent
        ]
    }

    try:
        response = requests.post(GENAI_AGENT_URL, json=payload, headers=headers)  # Send the request
        response.raise_for_status()  # Raise an exception if the response status code is 4XX/5XX
        response_data = response.json()  # Parse the JSON response
        return response_data.get("choices", [{}])[0].get("message", {}).get("content", "No response from AI.")  # Extract the response content

    except requests.exceptions.RequestException as e:
        return f"API Error: {str(e)}"  # Handle any request-related exceptions

@dispatcher.message(Command("start"))  # Decorator to handle the /start command
async def welcome(message: Message):
    await message.answer("Hello! I'm your AI-powered assistant. Send me a message!")  # Respond to the /start command

@dispatcher.message()  # Decorator to handle any incoming message
async def handle_message(message: Message):
    user_input = message.text  # Extract the text from the incoming message
    response = await fetch_genai_response(user_input)  # Fetch a response from the GenAI agent
    await message.answer(response)  # Respond to the user with the fetched response

async def main():
    await dispatcher.start_polling(bot, skip_updates=True)  # Start the bot and skip any updates that were missed while the bot was offline

if __name__ == "__main__":
    asyncio.run(main())  // End of Selection

Step 5 - Configure Environment Variables

Create a .env file and add the following. To create a .env file, open a text editor and paste the above content. Save the file with the name .env in the same directory as your Python script.

TELEGRAM_BOT_TOKEN=your_telegram_bot_token
GENAI_AGENT_URL=your_genai_agent_url
GENAI_API_KEY=your_genai_api_key

Replace your_telegram_bot_token, your_genai_agent_url, and your_genai_api_key with the actual values.

Step 6 - Run the Telegram Bot

Start your bot by running:

python bot.py

Now, open Telegram, search for your bot (you see the bot name in the message from BotFather), and send a message. You should receive an AI-generated response from the DigitalOcean GenAI Platform.

Telegram Bot

FAQs

1. What is the purpose of the DigitalOcean GenAI Platform?

The DigitalOcean GenAI Platform is designed to integrate AI capabilities into applications, enabling them to dynamically fetch information and provide personalized assistance to users. It allows developers to create intelligent agents that can understand and respond to user queries in real-time. This platform helps in enhancing user engagement and improving the overall user experience.

2. How do I create a Telegram Bot?

To create a Telegram Bot, open Telegram and search for BotFather. Start a chat and send the command /newbot. Follow the instructions to set up your bot and obtain the Telegram Bot Token.

3. What is the role of the aiogram library in this integration?

The aiogram library is used to develop and manage the Telegram Bot, enabling it to interact with users and fetch information from the DigitalOcean GenAI Platform.

4. How do I attach a Knowledge base to my GenAI Agent?

To attach a Knowledge base to your GenAI Agent, follow the instructions provided in the DigitalOcean GenAI Platform documentation. This will enable your agent to use the Knowledge base to provide context-specific responses.

You can also refer to the Agent Instructions Best Practices to learn more about how to use the GenAI Platform.

5. What are the benefits of integrating a Telegram Bot with the DigitalOcean GenAI Platform?

The integration offers numerous benefits, including real-time information retrieval, enhanced user experience, increased accessibility, and personalized assistance. Additionally, it allows for seamless interaction with users, providing them with accurate and timely information. This integration also helps in automating repetitive tasks, freeing up valuable time for more critical activities.

Conclusion

In this tutorial, you successfully integrated a Telegram bot with the DigitalOcean GenAI Platform agent using the API endpoint and access key. This setup allows the bot to respond to user queries specific to the knowledge base added to your GenAI agent. You can further enhance this by deploying the bot on a cloud server and adding advanced features.

To further enhance your understanding and capabilities with the DigitalOcean GenAI Platform, consider following the below tutorials:

Continue building with DigitalOcean Gen AI Platform and unlock the full potential of AI in your applications!

Continue building with DigitalOcean Gen AI Platform.

About the author(s)

Akshit Pratiush
Akshit PratiushSenior Solutions Architect
See author profile
Anish Singh Walia
Anish Singh WaliaSr Technical Writer
See author profile
Category:
Tutorial

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.