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

Published: (June 11, 2026 at 04:44 AM EDT)
1 min read
Source: Dev.to

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

0 views
Back to Blog

Related posts

Read more »

The spec is in the wrong place

My day job is at a large tech company. Hundreds of engineering teams, and every one of them is somewhere different on AI adoption. Some are still treating codin...

The Heuristics Say Don't

A culture that only records its disasters ends up with a biased archive. Wars documented, plagues chronicled, collapses catalogued. The quiet decades go unwritt...