I'm fairly new to all of this, but I have created a simple telegram bot to test their functionality. I have set the webhook and I'm using ngrok for the "host". However when I type a command the bot just doesn't do anything.
Does anyone know how to fix this?
Here is the index.php file:
<?php
require('token.php');
require('config.php');
try{
$ngrokUrl = "ngrok url";
$bot = new TelegramBot($token);
$jH = new jsonHandler($token);
var_dump($bot->setWebhook($ngrokUrl));
$webhookJson = $jH->getWebhookJson();
$chatId = $jH->getChatId($webhookJson);
$msg = $jH->getText($webhookJson) !== "" ? $jH->getText($webhookJson) : "";
switch($msg){
default:{
if ($msg[0] == '/')
$bot->sendMessage($chatId, 'The command does not exist');
break;
}
case '/test':{
$msg = 'test test';
$bot->sendMessage($chatId, $msg);
break;
}
case '/help':{
$msg = 'Help!';
$bot->sendMessage($chatId, $msg);
break;
}
}
}catch(ErrorException $e){
echo $e->getMessage();
}
?>
And the config.php file:
<?php
function fetchApi($url){
$req = curl_init($url);
$resp = curl_exec($req);
if($resp == false){
$error = curl_error($req);
curl_close($req);
throw new ErrorException($error);
}
else{
curl_close($req);
//return $resp;
}
}
class TelegramBot{
protected $tUrl;
function __construct($token){
$this->tUrl = "https://api.telegram.org/bot".$token;
}
function setUrl($method){
return $this->tUrl."/".$method;
}
function sendMessage($chatId, $msg){
$data = [
'chat_id' => $chatId,
'&text' => $msg
];
$url = $this->setUrl("sendMessage?".http_build_query($data));
fetchApi($url);
file_get_contents($url);
}
class jsonHandler extends TelegramBot{
function getWebhookJson(){
$json = file_get_contents("php://input");
return json_decode($json, true);
}
function getChatId($jsonDecoded){
return $jsonDecoded["message"]["chat"]["id"];
}
function getText($jsonDecoded){
return $jsonDecoded["message"]["text"];
}
}
?>
Related
I am trying to validate the request received from the plivo to my application server.
For this I am using the sample code provided by the plivo in the documentation.
<?php
require 'vendor/autoload.php';
use Plivo\Exceptions\PlivoValidationException;
use Plivo\Util\v3SignatureValidation;
use Plivo\XML\Response;
if (preg_match('/speak/', $_SERVER["REQUEST_URI"])) {
$auth_token = "<auth_token>";
$signature = #$_SERVER["X-Plivo-Signature-V3"] ?: 'signature';
$nonce = #$_SERVER["X-Plivo-Signature-V3-Nonce"] ?: 'nonce';
$url = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
$method = $_SERVER['REQUEST_METHOD'];
$SVUtil = new v3SignatureValidation();
if ($method == "GET") {
try {
$valid = $SVUtil->validateV3Signature($method, $url, $nonce, $auth_token, $signature);
} catch (PlivoValidationException $e) {
echo("error");
}
} else {
$body = file_get_contents("php://input");
$params = json_decode($body, true);
try {
$valid = $SVUtil->validateV3Signature($method, $url, $nonce, $auth_token, $signature, $params);
} catch (PlivoValidationException $e) {
echo("error");
}
}
echo $valid;
$body = 'Hi, Calling from Plivo';
$attributes = array(
'loop' => 3,
);
$r = new Response();
$r->addSpeak($body, $attributes);
echo($r->toXML());
} else {
echo "<p>Welcome to Plivo</p>";
}
But I am getting this error
Invalid argument supplied for foreach() in code/plivo/vendor/plivo/plivo-php/src/Plivo/Util/v3SignatureValidation.php on line 13
I am debugging, but not able to find the solution.
One thing I noticed that nothing is being received in json from the PLIVO server.
Can anyone help, as There is not enough documentation available for Plivo Request Validation.
Plivo's Developer Evangelist here. Please try the below code instead.
<?php
require 'vendor/autoload.php';
use Plivo\Exceptions\PlivoValidationException;
use Plivo\Util\v3SignatureValidation;
use Plivo\XML\Response;
if (preg_match('/speak/', $_SERVER["REQUEST_URI"]))
{
$auth_token = "<auth_token>";
$signature = #$_SERVER["HTTP_X_PLIVO_SIGNATURE_V3"] ? : 'signature';
$nonce = #$_SERVER["HTTP_X_PLIVO_SIGNATURE_V3_NONCE"] ? : 'nonce';
$url = $_SERVER['HTTP_REFERER'];
$method = $_SERVER['REQUEST_METHOD'];
$SVUtil = new v3SignatureValidation();
if ($method == "GET")
{
try
{
$valid = $SVUtil->validateV3Signature($method, $url, $nonce, $auth_token, $signature);
}
catch(PlivoValidationException $e)
{
echo ("error");
}
}
else
{
$body = file_get_contents("php://input", true);
parse_str($body, $get_array);
try
{
$valid = $SVUtil->validateV3Signature($method, $url, $nonce, $auth_token, $signature, $get_array);
}
catch(PlivoValidationException $e)
{
echo ("error");
}
}
error_log(print_r($valid, true));
$body = 'Hi, Calling from Plivo';
$attributes = array(
'loop' => 3,
);
$r = new Response();
$r->addSpeak($body, $attributes);
echo ($r->toXML());
}
else
{
echo "<p>Welcome to Plivo</p>";
}
And run the below command
php -S localhost:5000
In case if you still face any issues, please free to contact our support team
src: https://www.plivo.com/docs/voice/concepts/signature-validation#code
I have already work this in php. Here is my working code:
$request = array(
'DomainNames' => $domain_names
);
$response = dreamScapeAPI('DomainCheck', $request);
$available = false;
$alt_domains = array(); // Alternative to user's expected domain names
if (!is_soap_fault($response)) {
// Successfully checked the availability of the domains
if (isset($response->APIResponse->AvailabilityList)) {
$availabilityList = $response->APIResponse->AvailabilityList;
foreach ($availabilityList as $list) {
if ($list->Available){
if ($domain == $list->Item) {
$available = true; // user prefered domain found
}
else {
$alt_domains[] = $list->Item;
}
}
}
}
else {
$error = $response->APIResponse->Errors;
foreach ($error as $e) {
$api_error = $e->Message;
//echo $e->Item . ' - ' . $e->Message . '<br />';
}
}
}
function dreamScapeAPI($method, $data = null) {
$reseller_api_soap_client = "";
$soap_location = 'http://soap.secureapi.com.au/API-2.1';
$wsdl_location = 'http://soap.secureapi.com.au/wsdl/API-2.1.wsdl';
$authenticate = array();
$authenticate['AuthenticateRequest'] = array();
$authenticate['AuthenticateRequest']['ResellerID'] = '**';
$authenticate['AuthenticateRequest']['APIKey'] = '**';
//convert $authenticate to a soap variable
$authenticate['AuthenticateRequest'] = new SoapVar($authenticate['AuthenticateRequest'], SOAP_ENC_OBJECT);
$authenticate = new SoapVar($authenticate, SOAP_ENC_OBJECT);
$header = new SoapHeader($soap_location, 'Authenticate', $authenticate, false);
$reseller_api_soap_client = new SoapClient($wsdl_location, array('soap_version' => SOAP_1_2, 'cache_wsdl' => WSDL_CACHE_NONE));
$reseller_api_soap_client->__setSoapHeaders(array($header));
$prepared_data = $data != null ? array($data) : array();
try {
$response = $reseller_api_soap_client->__soapCall($method, $prepared_data);
} catch (SoapFault $response) { }
return $response;
}
I tried with this : https://github.com/dan-power/node-dreamscape
But domain search can not work properly. Mainly, I want it on nodejs using nodejs dreamscape api but this method is not available on nodejs.
Here is my working demo: click here
I am Kevin and these days I'm having problems with the functions editMessageText and editReplyMarkup. This is my code and I don't know where is the problem.
This is my code:
<?php
$botToken = "XXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$website = "https://api.telegram.org/bot".$botToken;
$FilejSon = file_get_contents("php://input");
$FilejSon = json_decode($FilejSon, TRUE);
$FirstName = $FilejSon["message"]["chat"]["first_name"];
$UserChatId = $FilejSon["message"]["chat"]["id"];
$Message = $FilejSon["message"]["text"];
$MessageID = $FilejSon["message"]["message_id"];
$CallBackID = $FilejSon["callback_query"]["from"]["id"];
$CallBackData = $FilejSon["callback_query"]["data"];
$what = ["callback_query"]["message"]["inline_message_id"];
$document = "http://media.giphy.com/media/109Ku3hdapZJle/giphy.gif"; //It's just a funny image
//Emoji
$phone = json_decode('"\uD83D\uDCF2"');
$list = json_decode('"\uD83D\uDCCB"');
$money = json_decode('"\uD83D\uDCB0"');
$postbox = json_decode('"\uD83D\uDCEE"');
$sos = json_decode('"\uD83C\uDD98"');
$link = json_decode('"\uD83D\uDD17"');
$jSonCodeKeyboard = '&reply_markup={"inline_keyboard":[[{"text":"1","url":"https://core.telegram.org/bots/api"}],[{"text":"2","url":"https://www.google.it"}],[{"text":"4","switch_inline_query_current_chat":"try"}],[{"text":"5","url":"https://www.google.it"},{"text":"'.$link.'%20Link%20'.$link.'","url":"http://botkevin.altervista.org/Bot/Nuovo_documento_di_testo.txt"}],[{"text":"6","callback_data":"Press"}]]}';
$jSonCodeKeyboard1 = '&reply_markup={"inline_keyboard":[[{"text":"Indietro","callback_data":"Ok"}]]}';
switch ($Message){
case '/start':
$msg = "Hello $GLOBALS[FirstName] $GLOBALS[MessageID] $GLOBALS[UserChatId] $GLOBALS[what].\n";
sendMessage($UserChatId, $msg, $jSonCodeKeyboard);
break;
case '/prova':
sendFile($UserChatId, $document);
break;
case '/prova1':
$msg = "worked $GLOBALS[MessageID]";
sendMessage($UserChatId, $msg, $jSonCodeKeyboard1);
break;
default:
if (callback($FilejSon)){
if ($CallBackData == "Press"){
sendMessage($CallBackID, "gg", $jSonCodeKeyboard1);
}
else if($CallBackData == "Ok")
{
$msg = "Edited";
Edit($CallBackID, $MessageID, $msg);
Edit1($CallBackID, $MessageID, $jSonCodeKeyboard1);
}
}
$msg = "Unrecognized command.";
sendMessage($UserChatId, $msg);
break;
}
function sendMessage($chat_id, $text, $LayoutKey){
if($LayoutKey==""){
$url = $GLOBALS[website]."/sendMessage?chat_id=".$chat_id."&text=".urlencode($text);
file_get_contents($url);
}
else{
$url = $GLOBALS[website]."/sendMessage?chat_id=".$chat_id."&text=".urlencode($text).$LayoutKey;
file_get_contents($url);
}
}
function sendFile($chat_id, $file){
$url = $GLOBALS[website]."/sendDocument?chat_id=".$chat_id."&document=".$file; //Gif,Pdf e Zip
file_get_contents($url);
}
function Edit($chat_id, $msgID, $text){
$url = $GLOBALS[website]."/editMessageText?chat_id=".$chat_id."&message_id=".$msgID."&text=".urlencode($text);
file_get_contents($url);
}
function Edit1($chat_id, $msgID, $LayoutKey){
$url = $GLOBALS[website]."/editMessageReplyMarkup?chat_id=".$chat_id."&message_id=".$msgID.$jSonCodeKeyboard1;
file_get_contents($url);
}
function callback($getUpdate){
return $getUpdate["callback_query"];
}?>
I've searched everywhere a solution but either were in another programming language or used a library and more, I'm not very good at php so i would like a basic thing like my code.
I would like to do that when I click on the inline keyboard of the first message that sends the bot by doing "/ start", clicking a button can modify the message and the inline keyboard without sending other messages clogging the chat.
(already checked https://core.telegram.org/bots/api)
I am learning how to create and consume a webservice in PHP using SOAP. My client.php file is like this:
require_once "lib/nusoap.php";
$client = new nusoap_client("http://localhost/ehsanashar/webservice/service.php?wsdl");
$book_name = "xyz";
$response = $client->call("price", array("name" => "$book_name"));
if ($response == null) {
echo "Nothing Found";
} else {
echo "Book Data: ". $response;
}
and my service.php is like this:
require_once "lib/nusoap.php";
require_once "function.php";
$server = new nusoap_server();
$server->configureWSDL('webservice', 'urn:webservice');
$server->register(
"price",
array("name" => "xsd:string"),
array("return" => "xsd:integer")
);
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
It requires a file called function.php that is like this:
function price($name) {
$details = array(
'abc' => 100,
'xyz' => 200
);
foreach ($details as $n => $p) {
if ($name == $n) {
$price = $p;
}
return $price;
}
}
When I run the file client.php, theresponse is null, but it shouldn't be, where is the problem? any help?
Try this
FOR WAMP
in client.php
require_once ('lib/nusoap.php');
$client = new soapclient('http://localhost/SOAP/server.php');
//Call a function at server and send parameters too
//$response = $client->call('get_message',$param);
$param = array( 'name' => 'xyz');
$response = $client->call('price',$param);
//Process result
if($client->fault)
{
echo "FAULT: <p>Code: (".$client->faultcode."</p>";
echo "String: ".$client->faultstring;
}
else
{
echo $response;
}
and in server.php
<?php
//call library
require_once ('lib/nusoap.php');
//using soap_server to create server object
$server = new soap_server;
//register a function that works on server
$server->register('get_message');
$server->register('price');
// create the function
function get_message($your_name)
{
if(!$your_name){
return new soap_fault('Client','','Put Your Name!');
}
$result = "Welcome to ".$your_name .". Thanks for Your First Web Service Using PHP with SOAP";
return $result;
}
function price($name){
if(!$name){
return new soap_fault('Client','','Put Book name!');
}
$details=array(
'abc' => 100,
'xyz' => 200
);
foreach($details as $n => $p){
if($name == $n){
$price = $p;
}
}
return "price is ". $price;
}
// create HTTP listener
$server->service($HTTP_RAW_POST_DATA);
exit();
?>
FOR XAMP
in server.php
<?php
//call library
require_once ('lib/nusoap.php');
$URL = "www.your-url.com";
$namespace = $URL . '?wsdl';
//using soap_server to create server object
$server = new soap_server;
$server->configureWSDL('pricetesting', $namespace);
//register a function that works on server
$server->register('hello');
// create the function
function price($name){
if(!$name){
return new soap_fault('Client','','Put Book name!');
}
$details=array(
'abc' => 100,
'xyz' => 200
);
foreach($details as $n => $p){
if($name == $n){
$price = $p;
}
}
return "price is ". $price;
}
// create HTTP listener
$server->service($HTTP_RAW_POST_DATA);
exit();
?>
in client.php
<?php
require_once ('lib/nusoap.php');
$client = new soapclient("http://localhost/soap/server.php?wsdl");
//Call a function at server and send parameters too
//$response = $client->call('get_message',$param);
$param = array( 'name' => 'abc');
$response = $client->call('price',$param);
//Process result
if($client->fault)
{
echo "FAULT: <p>Code: (".$client->faultcode."</p>";
echo "String: ".$client->faultstring;
}
else
{
echo $response;
}
?>
I make with tonic (php library for rest ) a rest webservice.
I use according to CRUD and REST put for editing a element.
So i call my method with a picture and filetype and parse the paramters and save the base64 encoded file on my server.
Code:
function put($request) {
$response = new Response($request);
$msg = new ErrorMessage();
$dbmodel = new DBModel();
$arr = array('Data' => null,'Message' =>null,'Code' => null);
try{
$split = explode ('&',$request->data);
$para = array();
foreach($split as $i) {
$names = explode('=',$i);
if(!isset($names[0]) or !isset($names[1]))
{
throw new Exception();
}
$para[$names[0]] = $names[1];
}
}
catch(Exception $e)
{
$arr['Code'] = 400;
$arr['Message'] = $msg->getMessage(400);
$response->body = json_encode($arr);
return $response;
}
if (isset($para['picture']) or isset($para['filetype']) )
{
if (isset($para['picture']) and isset($para['filetype']))
{
if (!($para['filetype'] == 'jpg' || $para['filetype'] == 'png'))
{
$arr['Code'] = 688;
$arr['Message'] = $msg->getMessage(617);
$response->body = json_encode($arr);
return $response;
}
$bin = base64_decode($para['picture']);
if (strlen($bin) >524288)
{
$arr['Code'] = 617;
$arr['Message'] = $msg->getMessage(617);
$response->body = json_encode($arr);
return $response;
}
$uid = $dbmodel->getUid($sid);
if($uid<1)
{
$arr['Code'] = 699;
$arr['Message'] = $msg->getMessage(699);
$response->body = json_encode($arr);
return $response;
}
$file = fopen($_SERVER['DOCUMENT_ROOT']."/img/".$uid.".".$para['filetype'], 'wb');
fwrite($file, $bin);
fclose($file);
}
else
{
$arr['Code'] = 616;
$arr['Message'] = $msg->getMessage(616);
$response->body = json_encode($arr);
return $response;
}
}
$arr['Code'] = 200;
$arr['Message'] = $msg->getMessage(200);
$response->body = json_encode($arr);
return $response;
}
Problem: The saved picture isn't like the original one it can't be displayed as image
I use http://www.redio.info/werkzeuge/file2base64.html to convert my picture into base64. I think that the problem could be in the parsing at the beginning of my code.
Original: 13.872 Bytes
New Image: 14.313 Bytes
Your picture parameter gets probably urlencoded, that would explain the bigger filesize. (e.g. '/' to %2F)
Try to put a urldecode around the parameter before you decode it.
$bin = base64_decode(urldecode($para['picture']));