Can't send reply with markup by Telegram Bot API - php

Trying to build up a simple bot.
Here's my code:
require 'vendor/autoload.php';
use Telegram\Bot\Api;
$telegram = new Api('<MY TOKEN>');
$result = $telegram -> getWebhookUpdates();
$text = $result["message"]["text"];
$chat_id = $result["message"]["chat"]["id"];
$name = $result["message"]["from"]["username"];
$keyboard = [["news"],["more news"],["loolz"]];
if ($text == "/start") {
$reply = "Hello there!";
$reply_markup = $telegram->replyKeyboardMarkup([ 'keyboard' => $keyboard, 'resize_keyboard' => true, 'one_time_keyboard' => false ]);
$telegram->sendMessage([ 'chat_id' => $chat_id, 'text' => $reply, 'reply_markup' => $reply_markup ]);
}
if ($text == "/btn1") {
$reply = "AWESOME! YOU TAPPED 2nd BUTTON :)";
$telegram->sendMessage([ 'chat_id' => $chat_id, 'text' => $reply ]);
}
Condition if ($text == "/btn1") works, but it stops when i add $reply_markup to "btn1" action.
Accordingly, the first condition also does not work due to $reply_markup
This SDK used in my project: click
How should i fix this?
ty <3

In order to use reply markup buttons you should always encode them as a JSON format use json_encode($reply_markup) instead of using $reply_markup.

replace:
$reply_markup = $telegram->replyKeyboardMarkup([ 'keyboard' => $keyboard, 'resize_keyboard' => true, 'one_time_keyboard' => false ]);
to:
$reply_markup = json_encode([ 'keyboard' => $keyboard, 'resize_keyboard' => true, 'one_time_keyboard' => false ]);

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)

how to use callback data in telegram bot

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
}
}

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.

ClientException: Client Error giving '401 Unauthorized' error in GuzzleHttp while using eBay SDK api using Php

I am using eBay SDK for Inventory API using php. While running the following code, I am getting the error saying ClientExcemption with some '401 Unauthorized' error code. I have downloaded zip of eBay SDK and unzip it in my vendor folder.
Below is the code I wrote:
config.php
<?php
return [
'sandbox' => [
'credentials' => [
'devId' => 'my devID',
'appId' => 'my appID',
'certId' => 'my certID',
],
'authToken' => 'myauthToken',
'oauthUserToken' => 'my oauthUserToken',
'ruName' => 'my ruName'
]
];
?>
In controller.php, the following is the code for ebay feed:
$config = require __DIR__.'/../config.php';
require './vendor/ebay-sdk-php/ebay-sdk-php-autoloader.php';
use \DTS\eBaySDK\Inventory\Services;
use \DTS\eBaySDK\Inventory\Types;
use \DTS\eBaySDK\Inventory\Enums;
public function ebay_feed($save = true){
$service = new Services\InventoryService([
'authorization' => $config['sandbox']['oauthUserToken'],
'requestLanguage' => 'en-US',
'responseLanguage' => 'en-US',
'sandbox' => true,
'httpOptions' => [
'verify' => false
]
]);
$request = new Types\CreateOrReplaceInventoryItemRestRequest();
$request->sku = '123';
$request->availability = new Types\Availability();
$request->availability->shipToLocationAvailability = new Types\ShipToLocationAvailability();
$request->availability->shipToLocationAvailability->quantity = 50;
$request->condition = Enums\ConditionEnum::C_NEW_OTHER;
$request->product = new Types\Product();
$request->product->title = 'Honda';
$request->product->description = 'New';
$request->product->aspects = [
'Brand' => ['Honda'],
'Type' => ['Vehicles'],
'Storage Type' => ['Removable'],
'Recording Definition' => ['High Definition'],
'Media Format' => ['Flash Drive (SSD)'],
'Optical Zoom' => ['10x', '8x', '4x']
];
$request->product->imageUrls = [
'http://i.ebayimg.com/images/i/182196556219-0-1/s-l1000.jpg',
'http://i.ebayimg.com/images/i/182196556219-0-1/s-l1001.jpg',
'http://i.ebayimg.com/images/i/182196556219-0-1/s-l1002.jpg'
];
$response = $service->createOrReplaceInventoryItem($request);
printf("\nStatus Code: %s\n\n", $response->getStatusCode());
if (isset($response->errors)) {
foreach ($response->errors as $error) {
printf(
"%s: %s\n%s\n\n",
$error->errorId,
$error->message,
$error->longMessage
);
}
}
if ($response->getStatusCode() >= 200 && $response->getStatusCode() < 400) {
echo "Success\n";
}
}
The following error that I get when I try to run my code.
How to solve this error ?

Telegram PHP inline_keyboard

I'm trying to create a bot which send an inline_keyboard when in receive the text "/start", the problem is that i can't see the response when i use this function to send the keyboard
function sendKeyboard($chat_id, $text) {
$keyboard = ['inline_keyboard' => [
['text':'Yes'],
['text':'No']
],
'resize_keyboard' => true,
'one_time_keyboard' => true,
'selective' => true
];
$keyboard = json_encode($keyboard);
$url = $GLOBALS[website] . "/sendMessage?chat_id=".$chat_id."&
reply_markup=".$keyboard."&text=".urlencode($text);
file_get_contents($url);
}
Can somebody understand how to solve this problem?
Inline Keyboard buttons is array of array of Button, and resize_keyboard, one_time_keyboard and selective is not for inline keyboard, it's parameters for Reply Keyboard.
Your code only have array of Button, and Button only have text field, it need to add callback_data or url, or you will get error.
You have better to see reference about details.
function robot($method,$datas=[]){
$url = "https://api.telegram.org/bot".API_KEY."/".$method;
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$datas);
$res = curl_exec($ch);
if(curl_error($ch)){
var_dump(curl_error($ch));
}else{
return json_decode($res);
}
}
robot('sendmessage', [
"chat_id" => $chat_id,
'message_id'=>$messageid,
"text" => "* buttonwith out link *
",
'reply_markup' => json_encode([
"one_time_keyboard" => true,
'inline_keyboard'=> [
[
['text' => "button 1", 'callback_data' => "buttoncode-39500"]
]
]
])
]);

Categories