How to Build a Telegram Bot with PHP and AI (2026)

php dev.to

How to Build a Telegram Bot with PHP and AI (2026)

This guide builds a fully working AI Telegram bot with PHP: webhook setup, message handling, per-user conversation history, AI replies via OpenAI, and inline keyboards.

Requirements

  • PHP 8.1+, Composer, OpenAI API key, Telegram bot token

Install

composer require openai-php/client guzzlehttp/guzzle
Enter fullscreen mode Exit fullscreen mode

Conversation History (per-user JSON files)

class ConversationHistory {
    public function get(int $userId): array {
        $file = "/tmp/tg_history/{$userId}.json";
        return file_exists($file) ? json_decode(file_get_contents($file), true) :
            [['role' => 'system', 'content' => 'You are a helpful assistant.']];
    }
    public function append(int $userId, string $role, string $content): void {
        $msgs = $this->get($userId);
        $msgs[] = ['role' => $role, 'content' => $content];
        file_put_contents("/tmp/tg_history/{$userId}.json", json_encode($msgs));
    }
}
Enter fullscreen mode Exit fullscreen mode

AI Reply

$client = OpenAI::client(getenv('OPENAI_API_KEY'));
$response = $client->chat()->create([
    'model' => 'gpt-4o-mini',
    'messages' => $this->history->get($userId),
]);
$reply = $response->choices[0]->message->content;
$this->history->append($userId, 'assistant', $reply);
Enter fullscreen mode Exit fullscreen mode

Webhook Entry Point

// webhook.php
$update = json_decode(file_get_contents('php://input'), true);
if ($update) { (new TelegramAIBot())->handle($update); }
http_response_code(200);
Enter fullscreen mode Exit fullscreen mode

Register Webhook

curl -X POST "https://api.telegram.org/bot<TOKEN>/setWebhook" \
  -d "url=https://yourdomain.com/webhook.php"
Enter fullscreen mode Exit fullscreen mode

Key Points

  • Always return HTTP 200 (or Telegram retries)
  • Show typing action with sendChatAction before slow AI calls
  • Commands: /start, /clear, /help
  • Inline keyboards via reply_markup.inline_keyboard

Originally published at kalyna.pro

Source: dev.to

arrow_back Back to Tutorials