How to Create a Grok Telegram Bot: Step-by-Step Python & xAI API Tutorial

Complete guide to creating a high-performance Grok AI Telegram bot using Python, python-telegram-bot v20, and xAI function calling with persistent inline keyboards.

How to Create a Grok Telegram Bot: Step-by-Step Python & xAI API Tutorial
AI Visual Blueprint
System Architecture & Operational Blueprint — Generated for BotSkillsStack Editorial

Telegram has become the premier mobile interface for autonomous AI agents due to its rock-solid MTProto protocol, native inline keyboards, instant media delivery, and zero-latency webhook system.

Building a Grok Telegram bot gives you a 24/7 personal executive assistant right in your pocket. In this tutorial, we will build a production-ready asynchronous bot using python-telegram-bot v20 and the xAI Grok-3 API.


1. Architectural Comparison: Webhooks vs. Long-Polling

When developing Telegram bots, you have two modes of operation: Long-Polling for local development, and HTTPS Webhooks for production cloud deployments.

Grok Telegram Webhook vs Polling

Operational Architecture Matrix

Architectural FeatureLong-Polling (getUpdates)Production Webhook (setWebhook)
InfrastructureLocal machine or dev containerCloudflare Worker / AWS Lambda / Railway
SSL RequirementNoneMandatory valid SSL certificate (Port 443, 8443)
Throughput Capacity$pprox 30 ext{ msg/sec}$$1,000+ ext{ msg/sec}$ with auto-scaling
Idle Resource UsageConstant socket connectionZero compute when idle

If you are looking for ready-to-deploy productivity agents, browse our ai productivity bot routines to automate scheduling, email summaries, and daily focus blocks.


2. Setting Up BotFather & Environment Variables

  1. Open Telegram, search for @BotFather, and click /start.
  2. Send /newbot and follow the prompts to choose your bot name (e.g., GrokExecutiveBot).
  3. Copy your HTTP API token: 123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ.
  4. Obtain your xAI API key from https://console.x.ai/.
  5. Store both keys in your .env file:
    TELEGRAM_BOT_TOKEN="your_telegram_bot_token"
    XAI_API_KEY="your_xai_api_key"

3. Asynchronous Bot Implementation in Python

import os
import aiohttp
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, CallbackQueryHandler, ContextTypes, filters

XAI_API_KEY = os.environ["XAI_API_KEY"]

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    keyboard = [
        [InlineKeyboardButton("📊 Crypto Market Brief", callback_data="crypto"),
         InlineKeyboardButton("🚀 Tech Headlines", callback_data="tech")],
        [InlineKeyboardButton("⚙️ Settings", callback_data="settings")]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)
    await update.message.reply_text(
        "👋 Welcome to **Grok Executive Assistant**. Send me any prompt or select a routine below:",
        reply_markup=reply_markup,
        parse_mode="Markdown"
    )

async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user_text = update.message.text
    await context.bot.send_chat_action(chat_id=update.effective_chat.id, action="typing")
    
    headers = {
        "Authorization": f"Bearer {XAI_API_KEY}",
        "Content-Type": "application/json"
    }
    payload = {
        "model": "grok-beta",
        "messages": [
            {"role": "system", "content": "You are a proactive Telegram executive assistant. Use concise bullet points."},
            {"role": "user", "content": user_text}
        ]
    }
    
    async with aiohttp.ClientSession() as session:
        async with session.post("https://api.x.ai/v1/chat/completions", json=payload, headers=headers) as resp:
            if resp.status == 200:
                data = await resp.json()
                reply = data["choices"][0]["message"]["content"]
                await update.message.reply_text(reply, parse_mode="Markdown")
            else:
                await update.message.reply_text("❌ xAI inference error. Please retry.")

if __name__ == '__main__':
    app = ApplicationBuilder().token(os.environ["TELEGRAM_BOT_TOKEN"]).build()
    app.add_handler(CommandHandler("start", start))
    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
    app.run_polling()

4. Interactive Inline Keyboards & Workflows

Grok Telegram Inline Keyboard

By pairing Telegram inline keyboards with our specialized personal AI assistant routines, your bot can execute complex multi-step tasks such as building full travel itineraries, booking flight alerts, or pruning expired subscriptions.

Explore our complete personal assistant bot directory for 35+ pre-built lifestyle, nutrition, and personal finance bots.