Я только что создал бота в Telegram и развернул веб-перехватчик PHP-файла для ответа на команды пользователя. В этом коде возникла проблема: невозможно получить параметр в общем URL-адресе для запуска бота.
он работает нормально, когда пользователь запускает бота обычным способом с обычным URL-адресом (https://t.me/xxxx_bot
), но я добавляю ссылающуюся часть в свой код, чтобы пользователи могли получать ссылки на основе баллов. Поэтому мне нужно создать несколько URL-адресов для пользователей, таких как https://t.me/xxxx_bot/?start=123456789
, мне удалось создать реферальную ссылку для каждого пользователя, но когда другие пользователи нажимают на этот общий URL-адрес и хотят запустить бота, бот не может получить значение параметра start
.
Значение параметра start
должно получить бот, затем отправить его в PHP-файл бота, а затем создать ссылку для открытия в боте как WebApp, включающую значение этого параметра start
, например $storeURL = 'https://example.com/?username=' . $username . '&uid=' . $userID . '&start=' . $startParam;
.
Но в настоящее время в моем коде username
и userID
получают информацию о пользователе, но значение параметра start
не получает. Когда пользователь щелкает URL-адрес бота и запускает его, отображается Invalid command. Please choose an option from the menu.
, а когда пользователь вручную отправляет команду /start
, бот может ответить и отправить функцию sendMessageWelcome
.
Поэтому я думаю, что когда пользователь запускает бота с https://t.me/xxxx_bot/?start=123456789
URL-адресом первой /start
команды, включенной в скрытую вещь (или включает этот параметр запуска, но скрывает), бот не может ответить на нее в первый раз, но когда мы перепечатываем/запускаем вручную, он отвечает команде.
Это мой код, надеюсь, кто-нибудь сможет помочь:
<?php
$botToken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx';
$telegramApi = 'https://api.telegram.org/bot'.$botToken;
$update = json_decode(file_get_contents('php://input'), true);
if (isset($update['message'])) {
$chatID = $update['message']['chat']['id'];
$messageText = $update['message']['text'];
$userID = $update['message']['from']['id'];
$username = $update['message']['from']['username'];
$firstname = $update['message']['from']['first_name'];
// $lastname = $update['message']['from']['last_name'];
// Check if the message contains a command with the start parameter
if (strpos($messageText, '/start') === 0) {
// Check if the message contains a start parameter
$startParam = explode(' ', $messageText)[1] ?? null;
if ($startParam === null) {
// Extract the start parameter from the URL if available
$urlComponents = parse_url($messageText);
if (isset($urlComponents['query'])) {
parse_str($urlComponents['query'], $queryParameters);
$startParam = $queryParameters['start'] ?? null;
}
}
$storeURL = 'https://example.com/?username=' . $username . '&uid=' . $userID . '&start=' . $startParam;
}
$welcomeIMG = 'https://example.com/poster-welcome.jpg';
$captionwelcome = "Hello ".$firstname."! blah blah blah";
$secondIMG = 'https://example.com/poster-2.jpg';
// Set the image URL and caption message
$imageURL = 'https://example.com/poster-1.jpg';
$caption = "Welcome back ".$firstname."!\n\n blah blah blah";
switch ($messageText) {
case '/start':
$startParam = explode(' ', $messageText)[1] ?? null;
$storeURL = 'https://example.com/?username=' . $username . '&uid=' . $userID . '&start=' . $startParam;
sendMessageWelcome($chatID, $welcomeIMG, $captionwelcome, $storeURL, $startParam);
sendKeyboard($chatID);
break;
case 'Open Store':
sendStoreButton($chatID, $storeURL, $imageURL, $caption);
break;
case 'Referred members':
$referredMembersCount = getReferredMembersCount($chatID);
sendMessage($chatID, '💢 Number of referred members: '.$referredMembersCount);
break;
case 'Refer and point':
$referLink = 'https://t.me/xxxxxxxx_bot?start='.$chatID;
$message = "🔃 Your referral link is ".$referLink." \n\nShare it and earn points for each user.";
$referredPlayersCount = getReferredPlayersCount($chatID);
$message .= "\n\n💢 Number of players with your UID in the game: ".$referredPlayersCount;
sendMessage($chatID, $message);
break;
default:
sendMessage($chatID, 'Invalid command. Please choose an option from the menu.');
sendKeyboard($chatID);
}
}
function sendMessage($chatID, $message) {
global $telegramApi;
$data = [
'chat_id' => $chatID,
'text' => $message
];
$ch = curl_init($telegramApi.'/sendMessage');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
curl_close($ch);
}
function sendMessageWelcome($chatID, $welcomeIMG, $captionwelcome, $storeURL, $startParam) {
global $botToken;
$data = [
'chat_id' => $chatID,
'photo' => $welcomeIMG,
'caption' => $captionwelcome ." UID: ". $startParam,
'reply_markup' => json_encode([
'inline_keyboard' => [
[
[
'text' => "Open Store",
'web_app' => ['url' => $storeURL]
],
[
'text' => 'Join our Channel',
'callback_data' => 'login_url',
'url' => 'https://t.me/xxxxxxxxx',
]
]
]
])
];
$url = "https://api.telegram.org/bot$botToken/sendPhoto";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($ch);
curl_close($ch);
}
function sendStoreButton($chatID, $storeURL, $imageURL, $caption) {
global $botToken;
$data = [
'chat_id' => $chatID,
'photo' => $imageURL,
'caption' => $caption,
'reply_markup' => json_encode([
'inline_keyboard' => [
[
[
'text' => "Open Store",
'web_app' => ['url' => $storeURL]
],
[
'text' => 'Join our Channel',
'callback_data' => 'login_url',
'url' => 'https://t.me/xxxxxxxx',
]
]
]
])
];
$url = "https://api.telegram.org/bot$botToken/sendPhoto";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($ch);
curl_close($ch);
}
function sendKeyboard($chatID) {
global $telegramApi;
$keyboard = [
['Open Store'],
['Help', 'Support'],
['Referred members', 'Refer and point']
];
$replyMarkup = [
'keyboard' => $keyboard,
'resize_keyboard' => true,
'one_time_keyboard' => false
];
$data = [
'chat_id' => $chatID,
'text' => 'Choose an option:',
'reply_markup' => json_encode($replyMarkup)
];
$ch = curl_init($telegramApi.'/sendMessage');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
curl_close($ch);
}
?>
Да, бот, запущенный по ссылке типа https://t.me/xxxx_bot/?start=123456789
, будет отображать только «/start» в самом окне чата.
Но значение, хранящееся в $update['message']['text']
, будет start 123456789
.
Вам нужно будет адаптировать корпус переключателя из
case '/start':
что-то вроде (PHP8)
case str_starts_with($messageText, "/start "):
или
case substr($messageText, 0, 6 ) === "start = ":
PHP8 работает, спасибо <3