PHP와 AI로 텔레그램 봇 만들기 (2026)

발행: (2026년 6월 11일 PM 05:44 GMT+9)
2 분 소요
원문: Dev.to

Source: Dev.to

PHP와 AI를 활용한 텔레그램 봇 만들기 (2026)

이 가이드는 PHP로 완전한 AI 텔레그램 봇을 구축합니다: 웹훅 설정, 메시지 처리, 사용자별 대화 기록, OpenAI를 통한 AI 응답, 그리고 인라인 키보드.
필요 환경: PHP 8.1 이상, Composer, OpenAI API 키, 텔레그램 봇 토큰

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"
  • 항상 HTTP 200을 반환하세요 (텔레그램이 재시도하도록).
  • 느린 AI 호출 전에 sendChatAction으로 타이핑 중 표시를 보여줍니다.
  • 명령어: /start, /clear, /help

인라인 키보드는 reply_markup.inline_keyboard를 통해 구현합니다.

원본 게시: kalyna.pro

0 조회
Back to Blog

관련 글

더 보기 »