Telegram Bot
In this tutorial, you will learn how to create a Telegram Bot that uses the Alith Python SDK to generate responses to messages. This bot will listen to messages in a Telegram channel and reply.
Note: Although we used Python in this tutorial, you can still use the Alith Rust SDK and Node.js SDK to complete this bot. The advantage of using the Alith Python SDK is that it improves development efficiency while still providing a production-level AI Bot. For example, you can deploy the Bot on AWS Lambda, leveraging the core Rust implementation and minimal Python dependencies, resulting in a much smaller cold start time compared to frameworks like Langchain.
Prerequisites
Before starting, ensure you have the following:
- OpenAI API Key: Sign up at OpenAI and obtain your API key.
- Telegram Bot Token: Create a Telegram Bot and retrieve the Bot Token.
- Python Environment: Install Python (3.8 or higher) and set up a virtual environment.
Rust
Install Required Libraries
Install the necessary Rust libraries using cargo
:
cargo add alith teloxide dotenv
Create a Telegram Bot
- Search for BotFather in Telegram and interact with it.
- Send the
/newbot
command to create a new bot. - Follow the prompts to provide a name and username for your bot, and save the generated Bot Token.
Set Up Environment Variables
Store your API keys and tokens as environment variables for security:
export OPENAI_API_KEY="your-openai-api-key"
export TELOXIDE_TOKEN="your-telegram-bot-token"
Write the Telegram Bot Code
Create a Rust project cargo init
and add the following code in main.rs
:
use alith::{Completion, Request, core::llm::client::Client};
use anyhow::Error;
use teloxide::prelude::*;
use dotenv::dotenv;
#[tokio::main]
async fn main() -> Result<(), Error> {
dotenv().ok();
log::info!("Starting command bot...");
let telegram_bot = Bot::from_env();
let client = Client::from_model_name("gpt-3.5-turbo").expect("Failed to create LLM");
let handler = Update::filter_message().endpoint(|bot: Bot, msg: Message, mut client: Client| async move {
if let Some(text) = msg.text() {
let result = client.completion(Request::new(text.to_string(), r#"You are a spam detector here to assist the user in identifying spam messages.
Respond with a clear yes/no and a brief explanation why."#.to_string())).await.unwrap();
let response_text = result.content;
bot.send_message(msg.chat.id, response_text).await?;
} else {
bot.send_message(msg.chat.id, "Please send a text message to check for spam.").await?;
}
respond(())
});
Dispatcher::builder(telegram_bot, handler)
.dependencies(dptree::deps![client])
.enable_ctrlc_handler()
.build()
.dispatch()
.await;
Ok(())
}
Run the Telegram Bot
Run your Rust script to start the bot:
cargo run --release
Test the Bot
- Interact with your Telegram Bot.
- Send messages, and the bot should reply.
Deploy the Bot
To keep the bot running 24/7, deploy it to a cloud platform like:
- Heroku: Follow the Heroku Python deployment guide .
- AWS Lambda: Use the Serverless Framework to deploy the bot.
- Google Cloud Run: Follow the Google Cloud Run documentation .
Enhance the Bot
Here are some ideas to improve your bot:
- Contextual Conversations: Store conversation history to enable multi-turn dialogues.
- Error Handling: Add error handling for API failures or invalid inputs.
- Custom Commands: Allow users to trigger specific actions (e.g.,
/ask
for questions). - Rate Limiting: Prevent abuse by limiting the number of requests per user.