I am using PHP with XAMPP and Dialogflow to create a chat interface. In a simple intent(question) in Dialogflow, I have created a webhook to XAMPP regarding the question 'Who is X' (e.g. Paul, George). Therefore , I place a POST REQUEST in order to have access to the json form of this question in DIalogflow so that I can answer it as I want to. Specifically, the ultimate goal of this is to retrieve some data from a MySQL database in phpMyAdmin about this question and respond for example that 'X is a developer' or 'X is a financial analyst'. This is why wrote a php script which is the following:
<?php
$method = $_SERVER['REQUEST_METHOD'];
// Process when it is POST method
if ($method == 'POST') {
$requestBody = file_get_contents('php://input');
$json = json_decode($requestBody);
$text = $json->result->parameters;
switch($text) {
case 'given-name':
$name = $text->given-name;
$speech = $name . 'is a developer';
break;
default:
$speech = 'Sorry I did not get this. Can you repeat please?';
}
$response = new \stdClass();
$response->speech = "";
$response->displayText = "";
$respone->source = "webhook";
echo json_encode($response);
}
else
{
echo "Method not allowed";
}
?>
However, the output of this program is: Method not allowed.
Paradoxically enough $method has the value 'GET' so it identifies a GET REQUEST while Dialogflow explicitly states at the webhook page that
Your web service will receive a POST request from Dialogflow in the
form of the response to a user query matched by intents with webhook
enabled.
Hence I am wondering: why my php script cannot see and process the POST REQUEST from Dialogflow?
P.S. Questions close to mine are the following: Form sends GET instead of POST, Why is $_SERVER['REQUEST_METHOD'] always GET?.
It doesn't work because $_SERVER['REQUEST_METHOD'] == "GET" by default.
So you program execute the 'else' condition.
You need to submit a request with the POST method to change this value.
You can use
<form method="POST">
[...]
</form>
in your HTML, or
$.ajax({
url : "ajax_url.php",
type : 'POST',
data : 'data='+data,
[...]
});
in your AJAX JS code for example
Here i am doing same like you from below code your Query will be resolved,
index.php
<?php
require 'get_enews.php';
function processMessage($input) {
$action = $input["result"]["action"];
switch($action){
case 'getNews':
$param = $input["result"]["parameters"]["number"];
getNews($param);
break;
default :
sendMessage(array(
"source" => "RMC",
"speech" => "I am not able to understand. what do you want ?",
"displayText" => "I am not able to understand. what do you want ?",
"contextOut" => array()
));
}
}
function sendMessage($parameters) {
header('Content-Type: application/json');
$data = str_replace('\/','/',json_encode($parameters));
echo $data;
}
$input = json_decode(file_get_contents('php://input'), true);
if (isset($input["result"]["action"])) {
processMessage($input);
}
?>
get_enews.php
<?php
function getNews($param){
require 'config.php';
$getNews="";
$Query="SELECT link FROM public.news WHERE year='$param'";
$Result=pg_query($con,$Query);
if(isset($Result) && !empty($Result) && pg_num_rows($Result) > 0){
$row=pg_fetch_assoc($Result);
$getNews= "Here is details that you require - Link: " . $row["link"];
$arr=array(
"source" => "RMC",
"speech" => $getNews,
"displayText" => $getNews,
);
sendMessage($arr);
}else{
$arr=array(
"source" => "RMC",
"speech" => "No year matched in database.",
"displayText" => "No year matched in database.",
);
sendMessage($arr);
}
}
?>
php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input
Related
I am new in PHP and I am trying to access file of another website of mine. So on my web #1 I am trying to send a POST request like this:
<?php
$url = 'http://localhost/modul_cms/admin/api.php'; //Web #2
$data = array(
"Action" => "getNewestRecipe",
"Secret" => "61cbe6797d18a2772176b0ce73c580d95f79500d77e45ef810035bc738aef99c3e13568993f735eeb0d3c9e73b22986c57da60a0b2d6413c5dc32b764cc5897a",
"User" => "joomla localhost",
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo $result;
if($result === FALSE){
echo "Not working connection :(";
}else{
echo "HOORAY!";
var_dump($result);
}
And on my web #2 I have some kind of receiver I made. Now I need to return after selecting stuff from my database array of data. So I have code like this on my web #2:
<?php
$action = isset( $_POST["action"] ) ? $_POST["action"] : "";
$secret = isset( $_POST["secret"] ) ? $_POST["secret"] : "";
$user = isset( $_POST["user"] ) ? $_POST["user"] : "";
if(!empty($secret)){
if(!empty($user)){
switch($action){
case 'getNewestRecipe':
getNewestRecipe();
break;
case '':
error();
break;
default:
error();
break;
}
}
}
/* *************** FUNCTIONS ************* */
function getNewestRecipe(){
return array("msg" => "Here is your message!");
}
The problem is everything I get on my web #1 from the response is actually the echo I have there for knowing that the HTTP request reached something (so I've got the message "HOORAY!") but the
var_dump($response)
has empty value (not NULL or something it's literally this):
C:\Program Files (x86)\Ampps\www\joomla30\templates\protostar\index.php:214:string '' (length=0)
Thank you for any help!
On web#1 you are sending "Secret","User","Action" in upper-case, but on web#2 you are accessing $_POST['secret'] (lower-case). Because of this your code never gets to the call of getNewestRecipe() nor to your error() call, thus there is no content / a blank page, but also no error.
Also, you need to output the array your function returns in some way.
An array cannot simply be echod, so you need to serialize it. I suggest using json_encode: echo json_encode(getNewestRecipe());
I created a chatbot in Dialogflow which informs the user about the members of my (extended) family and about where they are living. I have created a small database with MySQL which has these data stored and I fetch them with a PHP script (hosted on Heroku) whenever this is appropriate depending on the interaction of the user with the chatbot.
My PHP script which receives the POST request (webhook) from Dialogflow is the following:
<?php
$dbServername = '******************';
$dbUsername = '******************';
$dbPassword = '******************';
$dbName = '******************';
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];
if($method == 'POST'){
$requestBody = file_get_contents('php://input');
$json = json_decode($requestBody);
$action = $json->result->action;
$first_name = $json->result->contexts[0]->parameters->{'given-name'};
$last_name = $json->result->contexts[0]->parameters->{'last-name'};
$lifespan = $json->result->contexts[0]->lifespan;
$sql = "SELECT * FROM family WHERE name LIKE '%$first_name%$last_name%';";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$person = $row;
}
switch ($action) {
case 'Name':
$speech= "$first_name is my" . $person["name"] . ".";
break;
case 'Location':
$speech = "$first_name is living in {$person["location"]}.";
break;
default:
$speech = "Please ask me something more relevant to my family";
break;
}
}
else {
$speech = "Sorry, $first_name $last_name is not a member of my family.";
}
$response = new \stdClass();
$response->speech = $speech;
$response->displayText = $speech;
$response->source = "agent";
echo json_encode($response);
}
else
{
echo "Method not allowed";
}
?>
I can instantly see on Dialogflow the json response that I am receiving from it in my PHP script. However, Google Assistant does not provide this option. The problem also is that the json response when using Google Assistant is considerably different than the one when using only Dialogflow.
My question is: how can I "see" what JSON is being sent to my PHP script when using the Google Assistant? In other words, how can I "see" the whole of $requestBody variable at once?
For example, I tried to use https://webhook.site/ and I filled in the following information to create the new URL/endpoint:
Default status code -> 200
Content Type -> application/json
Timeout before response -> 0
Response body -> {
"speech": "WEBHOOK",
"displayText": "WEBHOOK",
"source": "agent"
}
The response body has the same structure as in my PHP script. However, for some reason, Google Assistant does not receive the json response from this custom endpoint (while Dialogflow does receive it perfectly). Therefore I cannot exactly move on and see what it is sent by Dialogflow & Google Assistant in the case of intents which are further triggered by context...
Easy solution: add logging
Add some error logging into your code that prints out the formatted JSON. Something like this right after you create $json would log it to your normal HTTP log file:
error_log( json_encode( $json, JSON_PRETTY_PRINT ) );
You can then examine your HTTP error log after each request to see what was sent. (As you've noted in the comments, you can do this with heroku logs on heroku in the terminal in your project directory.)
If you want it sent to a different location, you can examine the documentation for error_log() for details about how to send it to an email address (if your configuration supports that) or to another file. For example, this would log things to a file named /tmp/json.txt:
error_log( json_encode( $json, JSON_PRETTY_PRINT ), 3, "/tmp/json.txt" );
More complicated solution: use a proxy
You could also use a proxy such as ngrok that allows request inspection. This will give you a public hostname that you will set to forward to the hostname where your service is running. You can then use this public hostname for the fulfillment URL in Dialogflow with the path for the webhook. When Dialogflow sends a request, it will go to this proxy which will forward it to your service. Your service replies to the proxy which forwards it back to Dialogflow. You can inspect both the request and the response. (ngrok runs on the same machine as the service and allows inspection by having another URL you can use that views the request and response. Other proxies may work differently. webhook.site looks like it does something similar, but I haven't tested how its proxying works.)
I am using DIalogflow (api.ai) to create chat interfaces. I created a webhook from Dialogflow to a simple app containing a php script deployed on Heroku.
Therefore, I placed in the webhook form of Dialogflow the url of my Heroku app which resembles to this: https://my_heroku_app_name.herokuapp.com.
My ultimate goal is to fetch some data from a database (through the php script) and then feed Dialogflow with them. For now, I am only trying to connect the Heroku app (php script) with Dialogflow through a webhook.
The php script of the Heroku app is the following:
<?php
$method = $_SERVER['REQUEST_METHOD'];
if($method == 'GET'){
$requestBody = file_get_contents('php://input');
$json = json_decode($requestBody);
$text = $json->metadata->intentName->text;
switch ($text) {
case 'Name':
$speech = "This question is too personal";
break;
default:
$speech = "Sorry, I didnt get that.";
break;
}
$response = new \stdClass();
$response->speech = $speech;
$response->displayText = $speech;
$response->source = "webhook";
echo json_encode($response);
}
else
{
echo "Method not allowed";
}
?>
Keep in mind the following:
$method is GET for some reason instead of POST as it is supposed to be from Dialogflow.
if you try to echo any of the variables $requestBody, $json or $text then nothing is printed.
I have tested that the if branch is executed and that the default branch is executed at switch.
Why my PHP script cannot "see" the webhook from DIaloflow and fetch the data from it so as to respond appropriately?
P.S. My question is not a duplicate of Valid JSON output but still getting error. The former is about the input of the php script whereas the latter is about the output of the php script. These two things do not necessarily constitute identical problems.
try to do something like this with some modification in your code.
First, I suggest you to use action instead of using intent name for switch case.
index.php
<?php
require 'get_wardinfo.php';
function processMessage($input) {
$action = $input["result"]["action"];
switch($action){
case 'wardinfo':
$param = $input["result"]["parameters"]["number"];
getWardInfo($param);
break;
default :
sendMessage(array(
"source" => "RMC",
"speech" => "I am not able to understand. what do you want ?",
"displayText" => "I am not able to understand. what do you want ?",
"contextOut" => array()
));
}
}
function sendMessage($parameters) {
header('Content-Type: application/json');
$data = str_replace('\/','/',json_encode($parameters));
echo $data;
}
$input = json_decode(file_get_contents('php://input'), true);
if (isset($input["result"]["action"])) {
processMessage($input);
}
?>
get_wardinfo.php
<?php
require 'config.php';
function getWardInfo($param){
$wardinfo="";
$Query="SELECT * FROM public.wardinfo WHERE wardno=$param";
$Result=pg_query($con,$Query);
if(isset($Result) && !empty($Result) && pg_num_rows($Result) > 0){
$row=pg_fetch_assoc($Result);
$wardinfo= "Here is details that you require: Name: " . $row["name"]. " --- Address: " . $row["address"]. " --- MobileNo: " . $row["contact"];
$arr=array(
"source" => "RMC",
"speech" => $wardinfo,
"displayText" => $wardinfo,
);
sendMessage($arr);
}else{
$arr=array(
"source" => "RMC",
"speech" => "Have some problem .",
"displayText" => "Have some problem .",
);
sendMessage($arr);
}
}
?>
It seems you know each parameter and all about dialogflow and how it works with PHP arrays and all still if you have confusion in above code or method kindly put a comment.
And I will suggest you don't go for Heroku directly first try it with ngrok it will make your local server live and put the URL as webhook in dialogflow and you can easily debug the errors and all.
I managed to connect Dialogflow to my php script on Heroku.
I made the following changes on my php script (on Heroku) and on Dialogflow which led to this result:
I replaced the condition if($method == 'GET') with the condition if($method == 'POST') so as to anticipate the POST request of Dialogflow.
Keep in mind that until I solved the whole problem I was not receiving any POST request but I GET request so I thought that the POST request from Dialogflow leads to GET request because of a webpage redirection which I could not really see at that moment.
I replaced $text = $json->metadata->intentName->text; with $text = $json->results->metadata->intentName; which was the right json parsing for retrieving the value of intentName. (I have published here the json request from Dialogflow but nobody noticed my mistake)
I published my bot on Dialogflow through its built-in web demo and on Slack. This may sound quite irrelevant but also one person on the Dialogflow forum stated that: "Maybe it should rementioned somewhere. that api.ai98 is not parsing any parameters/values/data to you service untill you bot is published!!" (See the second post here: https://discuss.api.ai/t/webhook-in-php-example/229).
i want the php script to be able the get json using Unirest php
<?php
require_once 'src/Unirest.php';
$word = 'Cartoon newttork';
// return: convert-spaces-to-underscore-and-lowercase-with-php
$word = str_replace(' ', '_', strtolower($word));
// These code snippets use an open-source library.
$response = Unirest\Request::get("https://od-api.oxforddictionaries.com:443/api/v1/entries/en/$word",
array(
"Accept" => "application/json", // accept app as json
"app_id" => "xxxxx", // app id found in dashboard
"app_key" => "xxxxxx" //app key also found in dashboard
)
);
$word_name = $response->body;
if ($word_name === "Not Found") {
echo "Not Found";
}
?>
i want is to be something like this
$word_name = $response->body;
if ($word_name === "Not Found") {
echo "Not Found";
}
P.S if you have another php http client that is better write it down also
I have a Discord servern with 1361 members and on my website I want to display a total number of joined users.
I have figured out how to get all online Members on the server using:
<?php
$jsonIn = file_get_contents('https://discordapp.com/api/guilds/356230556738125824/widget.json');
$JSON = json_decode($jsonIn, true);
$membersCount = count($JSON['members']);
echo "Number of members: " . $membersCount;
?>
What should I do differently to get a total number of ALL users that have joined the server, and not just display the online members?
Now, I realize I am reviving a pretty old thread here, but I figure some might still use an answer. As jrenk pointed out, you should instead access https://discordapp.com/api/guilds/356230556738125824/members.
Your 404: Unauthorized comes from the fact that you are -you guessed it- not authorized.
If you have created a bot, it is fairly easy: just add a request header Authorization: Bot YOUR_BOT_TOKEN_HERE. If you use a normal Discord account, the whole problem is a bit more tricky:
You will first have to send a POST request to https://discordapp.com/api/auth/login and set the body to {"email": "EMAIL_HERE", "password": "PASSWORD_HERE"}.
You will get a response with the parameter token. Save this token, you will need it later. BUT:
NEVER, UNDER ANY CIRCUMSTANCES show anyone this token, as it is equivalent to your login credentials!
With this token, you can now send a POST request to the same address: https://discordapp.com/api/auth/login, but now add the header Authorization: YOUR_BOT_TOKEN_HERE. Note the missing "Bot" at the beginning.
Also, what you mustn't forget:
If you don't add the parameter ?limit=MAX_USERS, you will only get the first guild member. Take a look here to see details.
You have to count the number of online member
here is the working code
<?php
$members = json_decode(file_get_contents('https://discordapp.com/api/guilds/356230556738125824/widget.json'), true)['members'];
$membersCount = 1;
foreach ($members as $member) {
if ($member['status'] == 'online') {
$membersCount++;
}
}
echo "Number of members: " . $membersCount;
?>
You need a bot on your discord server to get all members. Use the Discord js library for example.
First create a discord bot and get a token, see the following url:
https://github.com/reactiflux/discord-irc/wiki/Creating-a-discord-bot-&-getting-a-token
As #2Kreeper noted, do not reveal your token publicly.
Then use the following code, replacing "enter-bot-token-here" and "enter-guild-id-here" with your own information:
<?php
$json_options = [
"http" => [
"method" => "GET",
"header" => "Authorization: Bot enter-bot-token-here"
]
];
$json_context = stream_context_create($json_options);
$json_get = file_get_contents('https://discordapp.com/api/guilds/enter-guild-id-here/members?limit=1000', false, $json_context);
$json_decode = json_decode($json_get, true);
echo '<h2>Member Count</h2>';
echo count($json_decode);
echo '<h2>JSON Output</h2>';
echo '<pre>';
print_r($json_decode);
echo '</pre>';
?>
For anyone still interested, here's the solution I currently use using RestCord:
use RestCord\DiscordClient;
$serverId = <YourGuildId>;
$discord = new DiscordClient([
'token' => '<YourBotToken>'
]);
$limit = 1000;
$membercnt = 0;
$_ids = array();
function getTotalUsersCount($ids, $limit, $serverId, $discord) {
if( count($ids) > 0 ) {
$last_id = max($ids);
$last_id = (int)$last_id;
} else {
$last_id = null;
}
$members = $discord->guild->listGuildMembers(['guild.id' => $serverId, 'limit' => $limit, 'after' => $last_id]);
$_ids = array();
foreach( $members as $member ) {
$ids[] = $member->user->id;
$_ids[] = $member->user->id;
}
if( count($_ids) > 0 ) {
return getTotalUsersCount($ids, $limit, $serverId, $discord);
} else {
return $ids;
}
}
$ids = getTotalUsersCount($_ids, $limit, $serverId, $discord);
$membercnt = count($ids);
echo "Member Count: " . $membercnt;
In addition to Soubhagya Kumar's answer comment by iTeY you can simply use count(), there is no need to loop if you do not require a loop.
I'm reviving this since it still seems to be relevant and the other answers seem a bit too complex I think (maybe the API used to be bad(?)). So:
Generate a permanent discord invite and keep the code at the end (https://discord.gg/xxxxxxx) and then all you do is this:
<?php
$server_code = "xxxxxxx";
$url = "https://discord.com/api/v9/invites/".$server_code."?with_counts=true&with_expiration=true";
$jsonIn = file_get_contents($url);
$json_obj = json_decode($jsonIn, $assoc = false);
$total = $json_obj ->approximate_member_count;
?>
And there you go, that's the total member count. Keep in mind, this will also count the bots I think so you have to account for that if you want to refine it even more