Page cover image

Telegram

Quickly build and deploy AI-powered bots on Telegram using Sandbloc’s ready-to-use templates. Automate tasks, respond to messages, and integrate with AI models seamlessly.

Sandbloc provides pre-built templates to create AI-powered Telegram bots for tasks like chat automation, content generation, and workflow execution. Using Sandbloc’s modular Input, Processing, and Output blocks, you can integrate AI providers like OpenAI, Claude, or Gemini into Telegram in minutes.


Step 1: Installation and Setup

Install Sandbloc and the Telegram Bot API library:

bashCopy code# Install Sandbloc
pip install sandbloc

# Install Telegram API wrapper (python-telegram-bot)
pip install python-telegram-bot --upgrade

# Install AI provider SDKs (e.g., OpenAI)
pip install openai

Step 2: Set Up Your Telegram Bot

  1. Open Telegram and search for the BotFather.

  2. Send /newbot to create a new bot.

  3. Copy the bot token provided by BotFather.

  4. Save the bot token for use in your script.


Step 3: Full Telegram AI Agent Code

Here’s the complete code for a Telegram bot that listens to messages, processes them using OpenAI’s GPT-4, and replies to the chat:

pythonCopy codefrom telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, ContextTypes, filters
from sandbloc import InputBlock, ProcessingBlock, OutputBlock

# Your Telegram Bot Token
TELEGRAM_BOT_TOKEN = "YOUR_TELEGRAM_BOT_TOKEN"

# Initialize Sandbloc Workflow
class TelegramAgent:
    def __init__(self):
        # Input Block: Accepts user messages
        self.input_block = InputBlock("telegram")

        # Processing Block: Sends user input to OpenAI GPT-4
        self.processing_block = ProcessingBlock("openai", model="gpt-4", api_key="YOUR_OPENAI_API_KEY")

        # Output Block: Sends the response back to the Telegram chat
        self.output_block = OutputBlock("telegram")

    async def process_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
        user_message = update.message.text
        print(f"User Message: {user_message}")

        # Input: Capture user message
        self.input_block.data = {"prompt": user_message}

        # Process: Use GPT-4 to generate response
        response = self.processing_block.process()

        # Output: Send response back to Telegram
        await update.message.reply_text(response)

# Bot Handlers
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("Hello! I’m your AI-powered assistant. Send me a message to get started. 🚀")

def main():
    app = ApplicationBuilder().token(TELEGRAM_BOT_TOKEN).build()

    # Initialize Telegram Agent
    agent = TelegramAgent()

    # Command Handlers
    app.add_handler(CommandHandler("start", start_command))

    # Message Handlers: Process all text messages
    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, agent.process_message))

    # Run the bot
    print("Telegram bot is running...")
    app.run_polling()

if __name__ == "__main__":
    main()

Step 4: Explanation of Code

  1. Input Block Captures the user’s message from the Telegram chat.

  2. Processing Block Sends the input to OpenAI’s GPT-4 (or any other AI provider) to generate a response.

  3. Output Block Sends the AI-generated reply back to the user in the same chat.

  4. Handlers

    • /start Command: Initializes the bot and provides instructions.

    • Message Handler: Processes all incoming messages and runs the Sandbloc workflow.


Step 5: Run the Bot

Save the code as telegram_ai_agent.py and run it:

bashCopy codepython telegram_ai_agent.py

In your Telegram chat, type /start or any message, and your AI agent will respond.


Extending the Template

Here’s how you can extend the Telegram bot for more advanced use cases:

  1. Command-Based Tasks Add specific commands for functionality like /summarize or /search:

pythonCopy codeasync def summarize_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    text_to_summarize = " ".join(context.args)
    agent.input_block.data = {"prompt": f"Summarize this: {text_to_summarize}"}
    response = agent.processing_block.process()
    await update.message.reply_text(response)
  1. Contextual Agents Store previous conversations in a vector store like Pinecone to provide contextual replies:

pythonCopy codefrom sandbloc import ProcessingBlock

vector_block = ProcessingBlock("pinecone", api_key="YOUR_PINECONE_API_KEY", index_name="chat_history")
self.processing_block >> vector_block
  1. Automated Notifications Schedule messages or reminders for groups using custom logic:

pythonCopy codeawait context.bot.send_message(chat_id=update.effective_chat.id, text="This is a scheduled update!", schedule="daily 10:00 AM")

Use Cases for Telegram Templates

  • AI-Powered Assistants: Build chatbots for customer support, FAQs, or productivity tools.

  • Content Summarization: Allow users to summarize documents or articles by simply pasting the text.

  • Task Automation: Automate group notifications, reminders, and updates.

  • Real-Time Q&A: Provide real-time answers to questions using advanced AI models.


Conclusion

Sandbloc’s Telegram templates offer a robust, modular foundation for building AI-powered bots. Whether you need to automate tasks, create interactive assistants, or integrate powerful AI workflows, Sandbloc makes it easy to deploy scalable bots on Telegram.

Last updated