how to use callback data in telegram bot - php

i'm using this library https://github.com/Eleirbag89/TelegramBotPHP to create telegram bot
i want to get user tweeter username like:#username
how to use callback data and then use callback_data value
ex:
bot: username
user: #alex
bot: password
user: 985468
if($text == '🚀 Submit your Detalis'){
$option = array(
array($telegram->buildInlineKeyBoardButton('✅ Done', $url, $callback_data = 'checkIsMember')) );
$keyb = $telegram->buildInlineKeyBoard($option);
$content = array('chat_id' => $chat_id, 'reply_markup' => $keyb, 'text' => '
Join Our Telegram Channel
<b> Click "✅ Done" to continue </b>
');
$telegram->sendMessage($content);
}
if($text == 'checkIsMember'){
$content = array('chat_id' => $chat_id, 'text' => '
👉 Submit your Twitter username below (Included #)
Ex : #username
');
$telegram->sendMessage($content);
}

Set webhook on file where bot is placed Site must have SSL (https).
https://api.telegram.org/bot(your token)/setWebhook?url=https://example.com/bot_directory/bot.php
Than process data and write bot
$update = json_decode(file_get_contents('php://input'), TRUE);
$botToken = "(your token)";
$botAPI = "https://api.telegram.org/bot" . $botToken;
$msg = $update['message']['text'];
$user_id = $update['message']['from']['id'];
//Simple send button when user send message
$data = http_build_query([
'text' => 'Hi it is my bot',
'chat_id' => $update['message']['from']['id'],
]);
$keyboard = json_encode([
"inline_keyboard" => [
[
[
"text" => "say Hi",
"callback_data" => "say_h"
],
]
],
"resize_keyboard" => true
]);
file_get_contents($botAPI . "/sendMessage?{$data}&reply_markup={$keyboard}");
if (isset($update['callback_query'])) {
if ($update['callback_query']['data'] == 'say_h'){
// your code here when button pressed
}
}

Related

sendMediaGroup telegram PHP

I am using telegram library
php telegram bot sdk
And I want to send some photos in message using sendMediaGroup
Like this:
$reply = "*photos*";
$telegram->sendMediaGroup([
'chat_id' => $chat,
'media' => [
['type' => 'photo', 'media' => 'attach://photo1' ],
['type' => 'photo', 'media' => 'attach://photo2' ],
],
'photo1' => InputFile::create(file_get_contents("https://".$_SERVER['SERVER_NAME']."/newbot/screens/ctry/en1.jpg")),
'photo2' => InputFile::create(file_get_contents("https://".$_SERVER['SERVER_NAME']."/newbot/screens/ctry/en2.jpg")),
'caption'=> $reply,
'parse_mode' => 'markdown'
]);
I used without json_encode and file_get_contents, but it doesn't worked too
Why do you use that library? Here's the normal solution:
$token = ' TOKEN ';
$website = 'https://api.telegram.org/bot'.$token;
$update = file_get_contents('php://input');
$update = json_decode($update, TRUE);
$message = $update['message']['text'];
$id = $update['message']['from']['id'];
$name = $update['message']['from']['first_name'];
$surname = $update['message']['from']['last_name'];
$username = $update['message']['from']['username'];
function sendPhoto($id, $photo, $text = null){
GLOBAL $token;
$url = 'https://api.telegram.org/bot'.$token."/sendPhoto?chat_id=$id&photo=$photo&parse_mode=HTML&caption=".urlencode($text);
file_get_contents($url);
}
I also put there some useful variable and the chance to put a caption (don't give that parameter if you don't want one)

add option to choose different chat id for telegram bot

I made a simple telegram bot with PHP to copy and send any messages that receives to another group
but how can I give the option to user in the bot to choose different groups to send
for example to group A or B
$msgID = $updates["message"]["message_id"];
file_get_contents($link."/copyMessage?chat_id=GroupA&from_chat_id=999999&message_id=$msgID&disable_notification=true");
file_get_contents($link."/copyMessage?chat_id=GroupB&from_chat_id=999999&message_id=$msgID&disable_notification=true");
I think sending message with buttons it's better way to that.
It'll be like this:
User sends /start command
User sends any message
Bot reply user's message with buttons
User chooses a button
Bot copies message to selected chat
Bot answers user with success or fail
Use this code:
# Configuration that you need to fill
# Bot token obtained from #BotFather
define('BOT_TOKEN', 'Put your bot token here');
# Chat IDs Or Usernames that messages will be copied to
$chats =
[
# Username/ID => 'Chat title'
'#MyOwnGroup' => 'The bot creator group',
'1265170068' => 'My own account'
];
# Function to call any Bot API method
function bot(string $method, array $data = [])
{
$api_url = 'https://api.telegram.org/bot' . BOT_TOKEN . "/$method";
if (count(data) > 0)
{
$api_url .= '?'.http_build_url($data, '', '&');
}
return file_get_contents($api_url);
}
# The update data, Received from Telegram
$update = json_decode(file_get_contents('php://input'));
# Handle if new message received
if (property_exists($update, 'message') && $update->message->text !== '/start')
{
$message = $update->message;
$buttons = ['inline_keyboard' => []];
foreach ($chats as $chat_id => $chat_title)
{
array_push($buttons['inline_keyboard'], [['text' => $chat_title, 'callback_query' => $chat_id]]);
}
# Sending message with buttons to get which group the user wants
bot('sendMessage', [
'chat_id' => $message->chat->id,
'text' => 'Select which group you want to send the message..',
'reply_to_message_id' => $message->message_id,
'reply_markup' => json_encode($buttons)
]);
}
# Handle if one of buttons was pressed
if (property_exists($update, 'callback_query'))
{
$callback_query = $update->callback_query;
# Copy the message
$result = bot('copyMessage', [
'from_chat_id' => $callback_query->message->chat->id,
'message_id' => $callback_query->message->message_id,
'chat_id' => $callback_query->data
]);
if ($result->ok == true)
{
bot('answerCallbackQuery', [
'callback_query_id' => $callback_query->id,
'text' => 'Message was sent successfully!'
]);
}
else
{
bot('answerCallbackQuery', [
'callback_query_id' => $callback_query->id,
'text' => 'Message sending failed!',
'show_alert' => true
]);
}
}

Telegram Inline keyboards PHP

I would like to know how to change the text when clicked button attached to it (Inline keyboards). It's in a telegram channel.
Something like this but with my code below (no need for more options).
The code I have now:
$data = [
'text' => 'choose options yes or no',
'chat_id' => '-100234234234'
];
$keyboard = array(
"inline_keyboard" => array(
array(
array(
"text" => "Yes",
"callback_data" => "myCallbackData"
),
array(
"text" => "No",
"callback_data" => "myCallbackData"
)
)
)
file_get_contents("https://api.telegram.org/bot$token/sendMessage?" . http_build_query($data) . "&parse_mode=html&reply_markup=$keyboard");
After sending the message;
Remember the message_id returned by Telegram
Call /getUpdates to get the callback_data of pressed button
Use /editMessageText to update the first message
Example;
<?php
// Create data
$data = http_build_query([
'text' => 'Yes - No - Stop?',
'chat_id' => '1234567890'
]);
// Create keyboard
$keyboard = json_encode([
"inline_keyboard" => [
[
[
"text" => "Yes",
"callback_data" => "yes"
],
[
"text" => "No",
"callback_data" => "no"
],
[
"text" => "Stop",
"callback_data" => "stop"
]
]
]
]);
// Send keyboard
$url = "https://api.telegram.org/bot$token/sendMessage?{$data}&reply_markup={$keyboard}";
$res = #file_get_contents($url);
// Get message_id to alter later
$message_id = json_decode($res)->result->message_id;
// Continually check for a 'press'
while (true) {
// Call /getUpdates
$updates = #file_get_contents("https://api.telegram.org/bot$token/getUpdates");
$updates = json_decode($updates);
// Check if we've got a button press
if (count($updates->result) > 0 && isset(end($updates->result)->callback_query->data)) {
// Get callback data
$callBackData = end($updates->result)->callback_query->data;
// Check for 'stop'
if ($callBackData === 'stop') {
// Say goodbye and remove keyboard
$data = http_build_query([
'text' => 'Bye!',
'chat_id' => '1234567890',
'message_id' => $message_id
]);
$alter_res = #file_get_contents("https://api.telegram.org/bot$token/editMessageText?{$data}");
// End while
break;
}
// Alter text with callback_data
$data = http_build_query([
'text' => 'Selected: ' . $callBackData,
'chat_id' => '1234567890',
'message_id' => $message_id
]);
$alter_res = #file_get_contents("https://api.telegram.org/bot$token/editMessageText?{$data}&reply_markup={$keyboard}");
}
// Sleep for a second, and check again
sleep(1);
}
Note:
This example is written based on OP's code, just to show the idea of altering an inline_keyboard.
This code is purely as an example, there should be a lot more error checking etc...
Based on the comment, I've included a while true to keep on checking for new press.

Telegram API, get the sender's phone number?

I realize it is not possible to use a Bot to receive a sender's phone number.
I do, however, need to implement a bot-like client, that responds to anyone who is messaging it. I am using PHP on apache.
It is not a Bot, as it does not take commands, but rather responds to sent text from anyone who has that phone number. So you add the user as a contact (using a phone number), and then send text to it.
My goal is to realise the sender's phone number as I receive it, I saw on the Telegram API that there's a peer ID, but I can't find how to get the phone number if that's even possible...
try this lib from github https://github.com/irazasyed/telegram-bot-sdk
and code to create 'visit card' button in private chat:
$keyboard = array(
array(
array(
'text'=>"Send your visit card",
'request_contact'=>true
)
)
); //user button under keyboard.
$reply_markup = $telegram->replyKeyboardMarkup([ 'keyboard' => $auth_keyboard, 'resize_keyboard' => true, 'one_time_keyboard' => false ]);
$telegram->sendMessage([ 'chat_id' => $chat_id, 'text' => $reply, 'reply_markup' => $reply_markup ]);
and code to get unic user phone from 'visit card' after user push the button
$user_phone = $result["message"]["contact"]["phone_number"];
if ($user_phone) {
$reply = $user_phone;
$telegram->sendMessage([ 'chat_id' => $chat_id, 'text' => $reply, 'reply_markup' => $reply_markup ]);
}
finally i found how to get the phone number.
I use package https://github.com/irazasyed/telegram-bot-sdk for Laravel 8.
The code below is command to send button and when user press the button, it'll catch the phone number from user after the user click on "share".
PhoneNumberCommand.php
public function handle()
{
$response = $this->getUpdate();
$chat_id = $response->getChat()->getId();
$btn = Keyboard::button([
'text' => 'Varify',
'request_contact' => true,
]);
$keyboard = Keyboard::make([
'keyboard' => [[$btn]],
'resize_keyboard' => true,
'one_time_keyboard' => true
]);
return $this->telegram->sendMessage([
'chat_id' => $chat_id,
'text' => 'Please click on Verify and Share.',
'reply_markup' => $keyboard
]);
}
ControllerWebhook.php
public function commandHandlerWebHook()
{
$updates = Telegram::commandsHandler(true);
$chat_id = $updates->getChat()->getId();
// Catch Phone Number
$user_phone = array_key_exists('contact', $updates['message']) ?
$updates['message']['contact']['phone_number'] : null;
$text = 'Phone number : ' . $user_phone;
if($user_phone) return Telegram::sendMessage(['chat_id' => $chat_id, 'text' => $text]);
return 'ok';
}
It's work for me! hope you can implement too.

How to pass parameter to webhook telegram bot PHP

Is it possible send other variables with sendMessage method to webhook?
for example setting the todo variable:
function processMessage($message) {
// process incoming message
$message_id = $message['message_id'];
$azione = $message['todo'];
$chat_id = $message['chat']['id'];
$firstname = isset($message['chat']['first_name']) ? $message['chat']['first_name'] : "";
$lastname = isset($message['chat']['last_name']) ? $message['chat']['last_name'] : "";
if (isset($message['text'])) {
$text = $message['text'];
if (strpos($text, "/start") === 0) {
apiRequestJson("sendMessage", array('chat_id' => $chat_id, "text" => 'Benvenuto '.$firstname.' '.$lastname.' sul BOT di MIMANCHITU, dimmi cosa vuoi fare ['.$azione.']?', 'todo' => "fai qualcosa", 'reply_markup' => array(
'keyboard' => array(array('/consulta', '/guide')),
'one_time_keyboard' => true,
'resize_keyboard' => true)));
}
}
No you can't send any other variable other than what is defined in the documentation.

Categories