Nowadays, when digital assistants and automation have become part of everyday life, Telegram bots help to significantly simplify customer interaction and the user experience in general. Using OpenAI, you can create not just a standard bot, but a real intelligent assistant that understands the context of requests and can give meaningful answers. This guide will help you figure out how to connect artificial intelligence to your bot step by step to make it a convenient, smart and modern tool for any task.
An easy-to-understand guide to developing a Telegram bot using PHP and connecting the OpenAI API for intelligent responses.
1. What will be required
- PHP is installed on your server or locally (for example, WAMP, XAMPP).
- The Telegram bot token received through BotFather.
- The cURL library for working with API requests.
2. Example of a bot in PHP
2.1 Basic Bot
Creating a filebot.php
:
?php // Your BotFather token $botToken = "your_telegram_token"; $apiUrl = "https://api.telegram.org/bot" . $botToken; // Receiving and processing incoming updates $updateContent = file_get_contents("php://input"); $update = json_decode($updateContent, true); // Checking the presence of data if (isset($update["message"])) { $chatId = $update["message"]["chat"]["id"]; $message = $update["message"]["text"]; // Example of a response to a user message $reply = "You wrote: " . $message; // Sending a response to the user file_get_contents($apiUrl . "/sendMessage?chat_id=" . $chatId . "&text=" . urlencode($reply)); } ?>
Setting up a Webhook:
To let Telegram know where to send messages, configure the Webhook using the following query:
https://api.telegram.org/botВаш_Telegram_токен/setWebhook ?url=https://your-domain.com/bot.php
Replace https://your-domain.com/bot.php to your real URL.
2.2 Adding AI via the OpenAI API
- Get the OpenAI API key: Register at OpenAI and get the key.
- Install the OpenAI SDK library (or use cURL).
- Update the
filebot.php
with the code for OpenAI:
<?php // Your keys $botToken = "your_telegram_token"; $openAiApiKey = "your_orepai_ari_token"; $apiUrl = "https://api.telegram.org/bot" . $botToken; // Receiving and processing incoming updates $updateContent = file_get_contents("php://input"); $update = json_decode($updateContent, true); if (isset($update["message"])) { $chatId = $update["message"]["chat"]["id"]; $userMessage = $update["message"]["text"]; $openAiResponse = getGPTResponse($userMessage, $openAiApiKey); file_get_contents($apiUrl . "/sendMessage?chat_id=" . $chatId . "&text=" . urlencode($openAiResponse)); } function getGPTResponse($userMessage, $apiKey) { $url = "https://api.openai.com/v1/chat/completions"; $data = [ "model" => "gpt-4", "messages" => [ ["role" => "system", "content" => "You are a helpful assistant."], ["role" => "user", "content" => $userMessage] ], "max_tokens" => 100, ]; $headers = [ "Content-Type: application/json", "Authorization: Bearer " . $apiKey ]; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $result = curl_exec($ch); curl_close($ch); $response = json_decode($result, true); return $response['choices'][0]['message']['content'] ?? "An error has occurred."; } ?>
3. Connecting the bot to the Telegram channel
- Add a bot to your channel: Log in to the channel → Management → Administrators → Add a bot.
- Give the bot administrator rights.
- Use the following code to send messages to the channel:
$chatId = "@your_channel_name"; // Specify the channel name $message = "This is a message for the Telegram channel!"; file_get_contents($apiUrl . "/sendMessage?chat_id=" . $chatId . "&text=" . urlencode($message));
This is how the interaction of the Telegram bot with AI in PHP is configured. By understanding this logic, you will be able to create cool and sought-after projects using this framework.