How to Build a Telegram Bot with PHP and AI (2026)
Source: 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. PHP 8.1+, Composer, OpenAI API key, Telegram bot token composer require openai-php/client guzzlehttp/guzzle
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)); } }
$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.php $update = json_decode(file_get_contents(‘php://input’), true); if ($update) { (new TelegramAIBot())->handle($update); } http_response_code(200);
curl -X POST “https://api.telegram.org/bot/setWebhook”
-d “url=https://yourdomain.com/webhook.php”
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