PHP 및 AI로 텔레그램 봇을 구축하는 방법 (2026)

작성자

카테고리:

← 피드로
DEV Community · Serhii Kalyna · 2026-06-11 개발(SW)
Cover image for How to Build a Telegram Bot with PHP and AI (2026)

Serhii Kalyna

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

원문에서 계속 ↗

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다