I'm creating a chatbot with Dialogflow and Django-python. Right now, I already created an agent in Dialogflow, already have a Django app, used ngork, and other necessary stuffs except for connecting Dialogflow to Django app's fulfillment/and calling APIs.
I stumbled across this documentation https://github.com/googleapis/dialogflow-python-client-v2 and successfully did all the steps needed. In the last part of the documentation, it seems that what I finally need to do is use the dialogflow detect intent text , so I copied it and put it into my Django app(views.py).
def detect_intent_texts(project_id, session_id, texts, language_code):
"""Returns the result of detect intent with texts as inputs.
Using the same `session_id` between requests allows continuation
of the conversation."""
import dialogflow_v2 as dialogflow
session_client = dialogflow.SessionsClient()
session = session_client.session_path(project_id, session_id)
print('Session path: {}\n'.format(session))
for text in texts:
text_input = dialogflow.types.TextInput(
text=text, language_code=language_code)
query_input = dialogflow.types.QueryInput(text=text_input)
response = session_client.detect_intent(
session=session, query_input=query_input)
print('=' * 20)
print('Query text: {}'.format(response.query_result.query_text))
print('Detected intent: {} (confidence: {})\n'.format(
response.query_result.intent.display_name,
response.query_result.intent_detection_confidence))
print('Fulfillment text: {}\n'.format(
response.query_result.fulfillment_text))
Now, I don't know what to do next. Unfortunately, I don't know how to use it or how it exactly works as I am still new to this. I already searched for answers in the web but I didn't get a clear understanding about it and got overwhelmed a bit(as it seems that there is a lot to do with this). I hope I could get an example or step by step procedure about it.
I am assuming you know the basic functionalities of Django, and you are using v2 of Dialogflow.
You need to pass the user text request from front-end to the views.py. YOu will get it in request object, then you need to extract it.
After extracting the text, you need to call dialogflow's detect_intent() function with text and session_id (text requests with same session_id will be treated as same part of conversation).
Also, you would need to get a json file from GCP console in order to authenticate the dialogflow request. You can read more about that here.
Here is sample code which you can extend according to your use:
import dialogflow
from django.http import HttpResponse
def your_view(request):
text = request.POST.get("text_request")
session_id = 'some_session_id'
res = detect_intent(text)
return HttpResponse(res)
def detect_intent(text, session_id):
language_code = 'en'
project_id = 'your_dialogflow_project_id'
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'path_to_your_json_file'
session_client = dialogflow.SessionsClient()
session = session_client.session_path(project_id, session_id)
text_input = dialogflow.types.TextInput(text=text, language_code=language_code)
query_input = dialogflow.types.QueryInput(text=text_input)
response = session_client.detect_intent(session=session, query_input=query_input)
print('Query text: {}'.format(response.query_result.query_text))
print('Detected intent: {} (confidence: {})\n'.format(
response.query_result.intent.display_name,
response.query_result.intent_detection_confidence))
print('Fulfillment text: {}\n'.format(
response.query_result.fulfillment_text))
return response.query_result.fulfillment_text
Hope it helps.
Related
I'm trying to start a conversation from dialogflow cx python API. I have seen this question Start a conversation at the beginning of a flow using flow ID that solves the problem using Node.js but I'm not able to replicate in python.
In my code I have:
text_input = session.TextInput(text=msg)
query_input = session.QueryInput(text=text_input, language_code=language_code)
request = session.DetectIntentRequest(session=session_path, query_input=query_input)
response = session_client.detect_intent(request=request)
I would like to change session.TextInput() to session.EventInput, for example, as here but it does not work with dialogflow CX and the library dialogflowcx_v3beta1
To use an event as query_input, you should use type EventInput() in your QueryInput(). See code below on how to implement it.
from google.cloud import dialogflowcx_v3beta1 as dialogflow
from google.cloud.dialogflowcx_v3beta1 import types
import uuid
project_id = "your-project"
location = "us-central1" # my project is located here hence us-central1
session_id = uuid.uuid4()
agent_id = "999999-aaaa-aaaa" # to get your agent_id see https://stackoverflow.com/questions/65389964/where-can-i-find-the-dialogflow-cx-agent-id
session_path = f"projects/{project_id}/locations/{location}/agents/{agent_id}/sessions/{session_id}"
api_endpoint = f"{location}-dialogflow.googleapis.com"
client_options = {"api_endpoint": api_endpoint}
client = dialogflow.services.sessions.SessionsClient(client_options=client_options)
event = "custom_event"
event_input = types.EventInput(event=event)
query_input = types.QueryInput(event=event_input,language_code="en-US")
request = types.DetectIntentRequest(
session=session_path,query_input=query_input
)
response = client.detect_intent(request=request)
print(response.query_result.response_messages[0])
Custom event:
Output using the custom event created:
I made an agent with a knowledge base and documents in it using dialogflow console.
know I want to test it form a python code from my computer how can I code the query to get the response?
You can use the following official python package and install using pip.
pip install google-cloud-dialogflow
Check out the quickstart on the official google cloud documentation to detect the intent and retrieve the response.
https://cloud.google.com/dialogflow/es/docs/quick/api
Please find below links for code as you required. this has multiple links which can help you to understand flow.
https://cloudacademy.com/blog/how-to-build-an-intelligent-chatbot-with-python-and-dialogflow/
https://dev.to/mrkanthaliya/build-intelligent-chatbot-using-dialogflow-54nh
https://medium.com/zenofai/creating-chatbot-using-python-flask-d6947d8ef805
https://chatbotslife.com/dialogflow-tutorial-back-functionality-in-chatbot-using-python-django-eb2ce921dd19
this is a code can solve the problem
def detect_intent_texts(project_id, session_id, texts, language_code):
"""Returns the result of detect intent with texts as inputs.
Using the same `session_id` between requests allows continuation
of the conversation."""
from google.cloud import dialogflow_v2beta1
session_client = dialogflow_v2beta1.SessionsClient()
session = session_client.session_path(project_id, session_id)
print("Session path: {}\n".format(session))
#for text in texts:
text_input = dialogflow_v2beta1.TextInput(text=text, language_code=language_code)
query_input = dialogflow_v2beta1.QueryInput(text=text_input)
response = session_client.detect_intent(
request={"session": session, "query_input": query_input}
)
print("=" * 20)
print("Query text: {}".format(response.query_result.query_text))
print(
"Detected intent: {} (confidence: {})\n".format(
response.query_result.intent.display_name,
response.query_result.intent_detection_confidence,
)
)
print("Fulfillment text: {}\n".format(response.query_result.fulfillment_text))
my problem I was importing and using the normal dialogflow instead of using dialogflow_v2beta1 because using knowledge base is a beta feature.
I am following the following tutorial to understand Dialogflow Python API.
Here is how my adaptation looks:
import dialogflow_v2 as dialogflow
import json
from google.api_core.exceptions import InvalidArgument
from google.oauth2 import service_account
dialogflow_key = json.load(open(r'path_to_json_file.json'))
credentials = (service_account.Credentials.from_service_account_info(dialogflow_key))
session_client = dialogflow.SessionsClient(credentials=credentials)
DIALOGFLOW_LANGUAGE_CODE = 'en-US'
DIALOGFLOW_PROJECT_ID = 'some_project_id'
SESSION_ID = 'current-user-id'
session = session_client.session_path(DIALOGFLOW_PROJECT_ID, SESSION_ID)
text_to_be_analyzed = "mobile data"
text_input = dialogflow.types.TextInput(text=text_to_be_analyzed, language_code=DIALOGFLOW_LANGUAGE_CODE)
query_input = dialogflow.types.QueryInput(text=text_input)
try:
response = session_client.detect_intent(session=session, query_input=query_input)
except InvalidArgument:
raise
print("Query text:", response.query_result.query_text)
print("Detected intent:", response.query_result.intent.display_name)
print("Detected intent confidence:", response.query_result.intent_detection_confidence)
print("Fulfillment text:", response.query_result.fulfillment_text)
Here is what program outputs:
Query text: mobile data
Detected intent: support.problem
Detected intent confidence: 0.41999998688697815
Fulfillment text: Make sure mobile data is enabled and Wi-Fi is turned off.
Now my intent support.problem has follow up intent support.problem-yes, where customer replies Done it and gets back another response Let us try another step
How do I pass text/query to follow up intent and how do I get response in Python?
The response.query_result object should also contain an output_context field, which should be an array of Context objects. This array should be passed in query_parameters.context you pass to detect_intent().
You should be able to create a dictionary with the query parameters fields (including one for context) that you pass to session_client.detect_intent.
I am trying to create a quick web app that authenticates into a users Yahoo account, but I am having trouble getting 'user approval'.
Yahoo Auth Page
Personally, every time I go to external website and have to authenticate, I usually log into my account. This seems to be redirecting me to a page and asking for a code. I have 0 idea what code I would need to supply in order to authenticate. And if I dont know, my users certainly wont! I am building a flask app, and I have tried to model my code around this repo.
I have added some code specifically for Yahoo, but cant seem to connect the dots. New YahooSignIn subclass in the oauth.py file below:
class YahooSignIn(OAuthSignIn):
def __init__(self):
super(YahooSignIn, self).__init__('yahoo')
self.service = OAuth2Service(
name='yahoo',
consumer_id=self.consumer_id,
consumer_secret=self.consume_secret,
authorize_url='https://api.login.yahoo.com/oauth/v2/request_auth',
access_token_url='https://api.login.yahoo.com/oauth/v2/get_token',
base_url='http://fantasysports.yahooapis.com/'
)
def authorize(self):
return redirect(self.service.get_authorize_url(
scope='email',
response_type='code',
redirect_uri=self.get_callback_url())
)
def callback(self):
def decode_json(payload):
return json.loads(payload.decode('utf-8'))
if 'code' not in request.args:
return None, None, None
oauth_session = self.service.get_auth_session(
data={'code': request.args['code'],
'grant_type': 'authorization_code',
'redirect_uri': self.get_callback_url()},
decoder=decode_json
)
me = oauth_session.get('me?fields=id,email').json()
return (
'yahoo$' + me['id'],
me.get('email').split('#')[0],
me.get('email')
)
The only other change made was to the index.html page to add an additional link with a 'yahoo' parameter
<p>Login with Yahoo</p>
Any help would be greatly appreciated as this one has stumped me the last two nights and I would love to move past this!
Previous to this year (2018/19) I had been using Yahoo's Oauth 1.0 API. This year I ran into problems using it so I switched to using Oauth 2.0 via the yahoo-oauth library linked below. They have a nice page that describes how to use their library. Here is the code that I used.
from yahoo_oauth import OAuth2
class YahooFantasyAPI:
def fetchGameID(self):
session = self.getSession()
r = session.get(
'https://fantasysports.yahooapis.com/fantasy/v2/game/nfl'
)
print(r.text)
def getSession(self):
oauth = OAuth2(None, None, from_file='oauth2.json')
if not oauth.token_is_valid():
oauth.refresh_access_token()
return oauth.session
api = YahooFantasyAPI()
fetchGameID()
https://yahoo-oauth.readthedocs.io/en/latest/
How do I update FB Status using Python & GraphAPI? This question has been asked before, but many of the solutions have been deprecated and the requirement of GraphAPI seems to have rendered many solutions irrelevant.
I have fiddled around with the fbpy, Facebook, OAuth, and oauth2 packages, and have looked through their examples, but I still cannot figure out how to get them working. I have no trust in any of the code or the packages I have been using and am wondering if anyone has any definitive solutions that they know will work.
First you need to do is understand login flows. You should understand if you easily want to switch through the different Facebook libraries. Therefore it can have code that is very verbose to code that is very simple based on implementation.
The next thing is that there are different ways to implement handling OAuth and different ways to display and launch your web app in Python. There is no way to authorize without hitting a browser. Otherwise you would have to keep copy pasting the access_token to the code.
Let's say you chose web.py to handle your web app presentation and requests.py to handle the Graph API HTTP calls.
import web, requests
Then setup the URL we want all request to go through
url = (
'/', 'index'
)
Now get your application id, secret and post-login URL you would like to use
app_id = "YOUR_APP_ID"
app_secret = "APP_SECRET"
post_login_url = "http://0.0.0.0:8080/"
This code will have one class index to handle the logic. In this class we want to deal with the authorization code Facebook will return after logging in
user_data = web.input(code=None)
code = user_data.code
From here setup a conditional to check the code
if not code:
# we are not authorized
# send to oauth dialog
else:
# authorized, get access_token
Within the "not authorized" branch, send the user to the dialog
dialog_url = ( "http://www.facebook.com/dialog/oauth?" +
"client_id=" + app_id +
"&redirect_uri=" + post_login_url +
"&scope=publish_stream" )
return "<script>top.location.href='" + dialog_url + "'</script>"
Else we can extract the access_token using the code received
token_url = ( "https://graph.facebook.com/oauth/access_token?" +
"client_id=" + app_id +
"&redirect_uri=" + post_login_url +
"&client_secret=" + app_secret +
"&code=" + code )
response = requests.get(token_url).content
params = {}
result = response.split("&", 1)
for p in result:
(k,v) = p.split("=")
params[k] = v
access_token = params['access_token']
From here you can choose how you want to deal with the call to update the status, for example a form,
graph_url = ( "https://graph.facebook.com/me/feed?" +
"access_token=" + access_token )
return ( '<html><body>' + '\n' +
'<form enctype="multipart/form-data" action="' +
graph_url + ' "method="POST">' + '\n' +
'Say something: ' + '\n' +
'<input name="message" type="text" value=""><br/><br/>' + '\n' +
'<input type="submit" value="Send"/><br/>' + '\n' +
'</form>' + '\n' +
'</body></html>' )
Or using face.py
from facepy import GraphAPI
graph = GraphAPI(access_token)
try:
graph.post(
path = 'me/feed',
message = 'Your message here'
)
except GraphAPI.OAuthError, e:
print e.message
So in the end you can get a slimmed down version like
import web
from facepy import GraphAPI
from urlparse import parse_qs
url = ('/', 'index')
app_id = "YOUR_APP_ID"
app_secret = "APP_SECRET"
post_login_url = "http://0.0.0.0:8080/"
user_data = web.input(code=None)
if not user_data.code:
dialog_url = ( "http://www.facebook.com/dialog/oauth?" +
"client_id=" + app_id +
"&redirect_uri=" + post_login_url +
"&scope=publish_stream" )
return "<script>top.location.href='" + dialog_url + "'</script>"
else:
graph = GraphAPI()
response = graph.get(
path='oauth/access_token',
client_id=app_id,
client_secret=app_secret,
redirect_uri=post_login_url,
code=code
)
data = parse_qs(response)
graph = GraphAPI(data['access_token'][0])
graph.post(path = 'me/feed', message = 'Your message here')
For more info see
* Facebook API - User Feed: http://developers.facebook.com/docs/reference/api/user/#feed
* Publish a Facebook Photo in Python – The Basic Sauce: http://philippeharewood.com/facebook/publish-a-facebook-photo-in-python-the-basic-sauce/
* Facebook and Python – The Basic Sauce: http://philippeharewood.com/facebook/facebook-and-python-the-basic-sauce/
One possible (tested!) solution using facepy:
Create a new application or use an existing one previously created.
Generate a user access token using the Graph API explorer with the status_update extended permission for the application.
Use the user access token created in the previous step with facepy:
from facepy import GraphAPI
ACCESS_TOKEN = 'access-token-copied-from-graph-api-explorer-on-web-browser'
graph = GraphAPI(ACCESS_TOKEN)
graph.post('me/feed', message='Hello World!')
You can try this blog too. It's using fbconsole app.
The code from the blog:
from urllib import urlretrieve
import imp
urlretrieve('https://raw.github.com/gist/1194123/fbconsole.py', '.fbconsole.py')
fb = imp.load_source('fb', '.fbconsole.py')
fb.AUTH_SCOPE = ['publish_stream']
fb.authenticate()
status = fb.graph_post("/me/feed", {"message":"Your message here"})
This is how I got it to work. You absolutely don't need to create any app for this. I'll describe how to post status updates to your profile and to a facebook page of yours.
First, to post a status update to your profile:
Go to https://developers.facebook.com/tools/explorer.
You'll see a textbox with Access Token written before it. Click on the button 'Get Access Token' beside this textbox. It will open a pop up asking you for various permissions for the access token. Basically these permissions define what all you can do through the Graph API using this token. Check the tick boxes beside all the permissions you need one of which will be updating your status.
Now go ahead and install the facepy module. Best way would be to use pip install.
After this pase the following code snippet in any .py file:
from facepy import GraphAPI
access_token = 'YOUR_GENERATED_ACCESS_TOKEN'
apiConnection = GraphAPI(access_token)
apiConnection.post(path='me/feed',
message='YOUR_DESIRED_STATUS_UPDATE_HERE')
Now execute this .py file the standard python way and check your facebook. You should see YOUR_DESIRED_STATUS_UPDATE_HERE posted to your facebook profile.
Next, to do the same thing with a facebook page of yours:
The procedure is almost exactly the same except for generating your access token.
Now you can't use the same access token to post to your facebook page. You need to generate a new one, which might be a little tricky for someone new to the Graph API. Here's what you need to do:
Go to the same developers.facebook.com/tools/explorer page.
Find a dropdown showing 'Graph API Explorer' and click on it. From the dropdown, select your page you want to post updates from. Generate a new access token for this page. The process is described here: . Do not forget to check the manage_pages permission in the extended permissions tab.
Now use this token in the same code as you used earlier and run it.
Go to your facebook page. You should YOUR_DESIRED_STATUS_UPDATE posted to your page.
Hope this helps!