I've connected my chatbot (Watson Conversation) to messenger. However,
I'm stuck on passing of context variable for my Google Map API.
Process Flow:
User: I want to compute the distance
Bot: Gets $var1 and $var2
User: Inputs $var1 and $var2
Bot: Provides the distance between $var1 and $var2
How will I be able to get the user's $var1 and $var2 on my Application Code?
Note: It is on Dialogue Node [2].
For java just simply use :
Conversation service = new Conversation("2017-07-13");
service.setUsernameAndPassword("", "");
MessageOptions newMessage = new MessageOptions.Builder().workspaceId("")
.input(new
InputData.Builder(input).build()).context(context).build();
MessageResponse response = service.message(newMessage).execute();
int var1 = response.getContext().get("$var1");
Similarly for 2nd variable.
Related
Query via Python REST-APi
message: Invalid input: ':'
Hello,
i am starting a query via my Python-Neo4j-Api.
But the code ist not working, resulting in the the error message above.
But the same query is working in the Neo4J Desktop App.
Why is it working in the Neo4j Desktop App, but not via my Api Query. Why is the : before param a Problem?
I am new to Python and Neo4j, please help.
King regards.
Trying to query via a Python-Neo4j-RestAPI.
Below is the syntax on passing parameters in neo4j python driver. Unfortunately, you cannot use labels or relationship types in the parameter. If you need to pass labels (like Human:Moviestar) then you can use string function in python like this: passing parameters in neo4j using python
name = "Tom Cruise"
placeOfBirth = "Syracuse, New York, United States"
query = "Create (n:Human:Moviestar { name: $name, placeOfBirth: $placeOfBirth})"
session = driver.session()
result = session.run(query, name=name, placeOfBirth=placeOfBirth)
I see that you have been working with the database though the browser application. So commands that are prefixed with ":" like :params or :connect are browser commands and is not valid cypher. Instead, in python pass your parameters as the second argument to your to your session.run() function or transaction. Then use variable substitution to in your cypher query.
params = {"name": "Tom Hanks" }
with driver.session as session:
result = session.run ("MATCH (p:person) where p.name = $name return p", params)
Using this code allows me to search for YouTube channels and return their statistics; for some reason, however, only about half the channels return any results.
For example, if I use this link to test the API, you can see that I searched for Animal Planet, and that yields no results. However, if we go to YouTube's website and search for the same thing, we get the channel as needed.
Why does this happen and how can this be fixed?
This is the code I used:
#commands.command()
async def yt_test(self, ctx, *, search):
api_key = '...'
youtube = build('youtube', 'v3', developerKey=api_key)
request = youtube.channels().list(
part="snippet,statistics",
forUsername=search,
maxResults=1
)
response = request.execute()
try:
for item in response['items']:
link = item['id']
thumb_image = item['snippet']['thumbnails']['default']['url']
views = "{:,}".format(int(item['statistics']['viewCount']))
subs = "{:,}".format(int(item['statistics']['subscriberCount']))
vidCount = "{:,}".format(int(item['statistics']['videoCount']))
except:
Notfound = discord.Embed(description= "Sorry, but this Channel was not located, check spelling" , color=0xfc0328)
await ctx.send(embed=Notfound)
finalresult = discord.Embed(title = search, url='https://www.youtube.com/channel/' + link,
description= '**Statistics**\nViews: ' + views + '\nSubscribers: ' + subs + "\nVideos: " + vidCount, color=0x00ff00)
finalresult.set_thumbnail(url = thumb_image)
await ctx.send(embed=finalresult)
print(f"{ctx.author} looked up the profile of {search} --- in #{ctx.guild.name}")
You have to acknowledge that invoking the Channels.list API endpoint, by passing to it the parameter forUsername, is by no means the same thing as going to the YouTube's Web UI for to apply a manual search. For these things to come to light, do bear with me for a little while...
According to the official docs, the Channels.list endpoint invoked with forUsername=... produces the meta-data associated to the channel of which username is given as argument to the parameter forUsername:
forUsername (string)
The forUsername parameter specifies a YouTube username, thereby requesting the channel associated with that username.
According to an official Google staff post from 2013-07-11, it's not a requisite that every channel have attached an username. Hence, is perfectly possible for Channels.list endpoint to return no channel at all, if the argument of forUsername does not represent a YouTube username.
If you use one of my public (MIT licensed) Python 3 script -- youtube-search.py --, you'll see that it returns nothing for your queried username Animal Planet:
$ python3 youtube-search.py --user-name "Animal Planet"
youtube-search.py: error: user name "Animal Planet": no associated channel found
But if you invoke that script as follows:
$ python3 youtube-search.py --search-term "Animal Planet" --type channel
UCkEBDbzLyH-LbB2FgMoSMaQ: Animal Planet
UCuTSm59-_kap6J7Se-orUVA: Animal Planet Latinoamérica
UCpvajaPSWvFlyl83xvzs65A: animalplanet românia
UCgyOEJZJLPKclqrDyUkZ6Ag: Animal planet 1
UCypzlOdJyyOR2NhKv0o3zig: 動物星球頻道/ Animal Planet Taiwan
UCmMm-p51c14XJ1p294faCmA: Animal Planet Brasil
UCejVe2sNPjjvfCXg35q_EQQ: Animal Planet Videos
UClQLf_zw2A_nRaB45HWTbtA: Your Animal Planet
UChQEdt9dBiCkcCch6LyrjtA: Cute Animal Planet
UCRIS8Y1kfrFvFF_6vt6_3Cg: Animal Planet Videos
you'll see pretty much the same output as the YouTube's Web UI will show when queried for the same search term and filtered for TYPE being Channel.
Do note that your own results (the one obtained from youtube-search.py and the other provided by the YouTube Web UI) may very likely differ from the above ones; this is so because Google searches are tailored for the user that initiates the query.
The explanation behind the matching results sets obtained from youtube-search.py and YouTube Web UI is the following:
The API endpoint that corresponds to YouTube's own search feature accessible via its Web UI is none other than Search.list.
Do convince yourself about this claim by reading the code of youtube-search.py: when invoking it with --search-term "Animal Planet" --type channel, that script executes the function Service.search_term:
class Service:
...
def search_term(self, term, type = None):
resp = self.youtube.search().list(
q = term,
type = type,
part = 'id,snippet',
fields = 'items(id,snippet(title))',
maxResults = self.max_results
).execute()
...
with term equal to the string Animal Planet and type equal to the string channel. Consequently, this script is calling for the Search.list endpoint, passing to it the parameters q and type as mentioned.
We have a chat interface which we are using to request to dialogflow. Here the chat window is designed in php.
Now the chat can be initiated in any location, so when user connects we are also trying to capture timezone and send in the request to dialogflow. Based on the timeZone the results also differ.
Now i used the below code to append timezone, based on api considered from github in php.
GIT HUB link from where i have taken the code
https://github.com/GoogleCloudPlatform/php-docs-samples/blob/master/dialogflow/src/detect_intent_texts.php
The script taken from git hub is as follows
// Actual Script
// START dialogflow_detect_intent_text
//namespace Google\Cloud\Samples\Dialogflow;
use Google\Cloud\Dialogflow\V2\SessionsClient;
use Google\Cloud\Dialogflow\V2\TextInput;
use Google\Cloud\Dialogflow\V2\QueryInput;
use Google\Cloud\Dialogflow\V2\QueryParameters;
use Google\Cloud\Dialogflow\V2\SessionEntityTypesClient;
use Google\Cloud\Dialogflow\V2\EntityTypesClient;
use Google\Cloud\Dialogflow\V2\ContextsClient;
function detect_intent_texts($projectId, $texts, $sessionId, $languageCode = 'en-US')
{
$test = array('credentials' => 'apikey/test-cd4f0-XXXXX.json');
// new session
$sessionsClient = new SessionsClient($test);
$session = $sessionsClient->sessionName($projectId, $sessionId ?: uniqid());
printf('Session path: %s' . PHP_EOL, $session);
// query for each string in array
// create text input
$textInput = new TextInput();
$textInput->setText($text);
$textInput->setLanguageCode($languageCode);
// create query input
$queryInput = new QueryInput();
$queryInput->setText($textInput);
// get response and relevant info
$response = $sessionsClient->detectIntent($session, $queryInput);
$queryResult = $response->getQueryResult();
$queryText = $queryResult->getQueryText();
$intent = $queryResult->getIntent();
$displayName = $intent->getDisplayName();
$confidence = $queryResult->getIntentDetectionConfidence();
// output relevant info
$fulfilmentText = $queryResult->getFulfillmentText();
$sessionsClient->close();
}
echo detect_intent_texts('vehicle-test-cd4f0','text chat','123456','en-US','America/New_York');
// END dialogflow_detect_intent_text
Environment Details
OS : Linux
PHP 7.1
dialogflow v2
I have modified the script when sending data from detectIntent.
But my queryParams object returns me empty data, therefore the default timezone mentioned in the agent is considered. My main concern is to send TimeZone in the request. Which i am able to do with the online testing in google cloud interface https://cloud.google.com/dialogflow/docs/reference/rest/v2/projects.agent.sessions/detectIntent?apix=true. The same implementation is not working for me. What i am doing wrong? Please suggest.
/*
Modified script
All the other statements
*/
// I tried to add this code before the detectintent method to get timezone but the variable returns empty data.
// get response and relevant info
//queryParams optional adding new code before detectintent
$optionalArgs = new QueryParameters();
$optionalArgs->setTimeZone('America/New_York');
$optionalArgs->getTimeZone();
$optionArgs = (array)$optionalArgs;
$response = $sessionsClient->detectIntent($session, $queryInput, $optionArgs);// I have added $optionArgs for adding time zone
// other statements
//
// end of code
I am trying to retrieve information on users using the Microsoft Graph Library for PHP.
But this code runs into the error Trying to get property 'getGivenName' of non-object.
$user = $graph->createRequest("GET", "/users")
->setReturnType(Model\User::class)
->execute();
This is due to the fact, that $user is an array instead of an object!? What is wrong with the SDK (or my code)?
Is there any better documentation for the SDK???
This is due to the fact, that $user is an array instead of an object!?
That's right, since the endpoint GET Users returns the list of users, in the provided example:
$users = $graph->createRequest("GET", "/users")
->setReturnType(\Microsoft\Graph\Model\User::class)
->execute();
$users contains an array of objects of Microsoft\Graph\Model\User type, and
$givenName = $users[0]->getGivenName();
gives GivenName property of first item in array.
A specific user could be requested via GET /users/{id | userPrincipalName} endpoint:
$user = $graph->createRequest("GET", "/users/{$userId}")
->setReturnType(\Microsoft\Graph\Model\User::class)
->execute();
In that case $user object is of Microsoft\Graph\Model\User type:
$givenName = $user->getGivenName();
Update
setReturnType function accept Microsoft Graph API entity type name, in your example it appears Model\User points to type which doesn't belong to Microsoft\Graph\Model namespace and as a result JSON response is not getting deserialized into class instance.
Instead of
setReturnType(Model\User::class)
try to specify fully qualified class name:
setReturnType(\Microsoft\Graph\Model\User::class)
I use the following code to set some sessions when an user logs in using his twitter account:
$twitteroauth = new TwitterOAuth(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$access_token = $twitteroauth->getAccessToken($_GET['oauth_verifier']);
$_SESSION['access_token'] = $access_token;
$user_info = $twitteroauth->get('account/verify_credentials');
As you see, I have all the tokens (token, secret token and access token) stored in a session, so that I can use this later on when an user wants to change his profile picture for example
But when I want to have access again to the user info... I am not able to access it. Again I build the twitteroauth connection, but now using the sessions stored during login:
$twitteroauth = new TwitterOAuth(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$access_token = $_SESSION['access_token'];
$user_info = $twitteroauth->get('account/verify_credentials');
if (isset($user_info->error)) {
echo "token:", $_SESSION['oauth_token'], "<br>";
echo "token_secret:", $_SESSION['oauth_token_secret'], "<br>";
echo "access-token:", $access_token, "<br>";
echo "error";
} else {
echo "oke";
}
I receive the error echo. When I echo my token strings, the all contain data and the access-token contains the value "Array".
Does someone know what I am doing wrong?
You need to use print_r to print the array values.