Now the most popular in development is setting up the interaction of client applications with Telegram. This ensures the convenience of communication at the software level, taking into account the fact that almost every Internet user has acquired this application.
How to programmatically configure this interaction in a few simple steps?
Understanding this algorithm will allow you to expand this system to suit your goals.
There is a task to create a telegram bot by activating which (by pressing the start button) our application will receive the Id of this user, which will be saved to the database MYSQL in order to send messages to him and vice versa (from the bot to the user personally), i.e. subsequent communication with him on behalf of our telegram bot.
Step-by-step instructions:
Step 1: Create a Telegram Bot
- Open Telegram and find the bot @BotFather.
- Create a new bot by sending the command
/newbot
. - Follow the instructions to set the name and username of your bot.
- After creation, you will receive an API token (something like
123456789:ABCdefGhiJklMNOpQRstUvWxyZ
). Save it — you will need it to send requests to the Telegram API.
Step 2: Configuring the webhook
- Create a
filesetWebhook.php
and add the following code to it:<?php $token = "YOUR_TOKEN"; // Replace with your token $url = "https://api.telegram.org/bot$token/setWebhook?url=YOUR_URL/webhook.php"; // Replace with your URL $response = file_get_contents($url); echo $response; ?>
- Run this file to install the webhook.
Step 3: Create a message handler
Create a filewebhook.php
, which will accept updates from Telegram:
<?php $update = json_decode(file_get_contents('php://input'), TRUE); if (isset($update['message'])) { $chat_id = $update['message']['chat']['id']; $text = $update['message']['text']; // Checking the "/start" command if ($text === '/start') { // Saving the user ID to the database saveUserIdToDatabase($chat_id); // Sending a welcome message SendMessage($chat_id, "Welcome to our bot!"); } } function sendMessage($chat_id, $message) { $token = "YOUR_TOKEN"; // Replace with your token $url = "https://api.telegram.org/bot$token/sendMessage"; $data = [ 'chat_id' => $chat_id, 'text' => $message, ]; file_get_contents($url . '?' . http_build_query($data)); } function saveUserIdToDatabase($chat_id) { // Here is your code for connecting to the database // and save $chat_id } ?>
Step 4: Configuring the database
- Create a database and a table to store
user_id
:CREATE DATABASE telegram_bot; USE telegram_bot; CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, chat_id BIGINT NOT NULL );
- Configure the database connection in the
saveUserIdToDatabase
function:
function saveUserIdToDatabase($chat_id) { $servername = "localhost"; // Replace with your data $username = "YOUR_USER"; // Replace with your data $password = "YOUR_PAROL"; // Replace with your data $dbname = "telegram_bot"; // Creating a connection $conn = new mysqli($servername, $username, $password, $dbname); // Checking the connection if ($conn->connect_error) { die("Connection error: " . $conn->connect_error); } // Saving the chat_id to the database $stmt = $conn->prepare("INSERT INTO users (chat_id) VALUES (?)"); $stmt->bind_param("i", $chat_id); $stmt->execute(); $stmt->close(); $conn->close(); }
Step 5: Testing
After you have installed the webhook and launched your Telegram bot, you can test it by sending the command /start
. Here are the steps to verify:
- Send the
/start
command to your Telegram bot. - Check that the bot responds with a welcome message. You should see the message "Welcome to our bot!".
- Check the database. Open your database and make sure that the
chat_id
of your user has been successfully saved in theusers
table.
Step 6: Sending messages to the user
Now that you have saved the chat_id
of the user, you can send messages to him from your application. To do this, you can use the sendMessageToUser
function.
function sendMessageToUser($chat_id, $message) { $token = "YOUR_TOKEN"; // Replace with your token $url = "https://api.telegram.org/bot$token/sendMessage"; $data = [ 'chat_id' => $chat_id, 'text' => $message, ]; file_get_contents($url . '?' . http_build_query($data)); }
Step 7: Processing additional commands
You can extend the functionality of your bot by adding processing of other commands or messages.
if ($text === '/help') { SendMessage($chat_id, "Available commands: /start, /help"); } elseif ($text === '/news') { SendMessage($chat_id, "Here's the latest news..."); } else { SendMessage($chat_id, "Unknown command. Type /help for a list of available commands."); }
Step 8: Security setup and Optimization
- Security: Make sure that your application is protected from potential attacks (for example, SQL injections).
- Logs: Set up logging for errors and queries.
- Testing: Conduct regular testing of your bot's functionality.
Now we have a basic setup of a Telegram bot in PHP that can interact with users, receive their chat_id
, and send them messages. With this frame, you can add any additional functions and expand the capabilities of your bot, depending on your needs.