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
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));
}
}
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);
Webhook Entry Point
// webhook.php
$update = json_decode(file_get_contents('php://input'), true);
if ($update) { (new TelegramAIBot())->handle($update); }
http_response_code(200);
Register Webhook
curl -X POST "https://api.telegram.org/bot<TOKEN>/setWebhook" \
-d "url=https://yourdomain.com/webhook.php"
Key Points
- Always return HTTP 200 (or Telegram retries)
- Show
typingaction withsendChatActionbefore slow AI calls - Commands:
/start,/clear,/help - Inline keyboards via
reply_markup.inline_keyboard
Originally published at kalyna.pro
Top comments (0)