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:
Before we begin, ensure you have the following:
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.
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.
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.
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
We are using aiogram library, a modern and efficient Python framework for building Telegram bots using asyncio. We are using it because:
Create a project folder and inside it, create a file bot.py
and add the following code:
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
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.
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.
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.
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.
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.
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.
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.
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.
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!