I use flask-assistant on python 3 with dilaogflow as a webhook. I looked at the official documentation and I don't find how to get the user message ("queryText" on dialogflow json request).
I tried this with no success:
# -*- coding: utf-8 -*-
from flask import Flask
from flask_assistant import Assistant, ask, tell, context_manager, event
project_id='myproject_id'
app = Flask(__name__)
assist = Assistant(app, route='/', project_id = project_id)
#assist.action('Default Fallback Intent')
def manage_fallback(queryText):
print('*'*40,queryText)
speech='Running'
return tell(speech)
if __name__ == '__main__':
app.run(debug=True)
The print of queryText always return None, but when I inspect on the ngrok web interface (http://127.0.0.1:4040) , I can see the request.
And I want to know how canI get the user message from flask-assistant?
I also asked about this question on github and get the answer, so I will share for the others:
You can get the query text from the flask-assistant request object.
from flask_assistant import request
...
...
#assist.action('Default Fallback Intent')
def manage_fallback():
user_query = request['queryResult']['queryText']
speech = "You said " + user_query
return tell(speech)
The reason the value of queryText expected by your manage_fallback function is None is because the parameter name must match the entity type expected by the intent.
Parameters are used to receive parsed entities for an intent, not the full user query.
Related
I am trying to follow the WeChat Official Account tutorial to build an app.
In the step of
1.4 Basic Configuration for Developers
After the restart is successful (python main.py 80), click the Submit button. If the prompt "token verification failed" appears,
check the code or network link. If the token is successfully verified,
you will be redirected back to the Basic Configuration page. Click
Start.
However, based on the tutorial, there is no submit button related code. I cannot find the submit button.
When I open the pages through WeChat Official Account in the app WeChat, it just shows "hello, this is handle view".
Any guide? Thanks
main.py
import web
from handle import Handle
urls = (
'/wx', 'Handle',
)
if __name__ == '__main__':
app = web.application(urls, globals())
app.run()
handle.py
import hashlib
import web
class Handle(object):
def GET(self):
try:
data = web.input()
if len(data) == 0:
return "hello, this is handle view"
signature = data.signature
timestamp = data.timestamp
nonce = data.nonce
echostr = data.echostr
token = "xxxx" #Enter the value in **Basic Configuration ** at Official Accounts Platform.
list = [token, timestamp, nonce]
list.sort()
sha1 = hashlib.sha1()
map(sha1.update, list)
hashcode = sha1.hexdigest()
print "handle/GET func: hashcode, signature: ", hashcode, signature
if hashcode == signature:
return echostr
else:
return ""
except Exception, Argument:
return Argument
I figured out the submit button here in the tutorial is referring the submit button at
https://mp.weixin.qq.com/
开发 -> 基本配置 -> 服务器配置 -> 修改配置 -> URL
After you fill the URL, that submit (提交) button.
(Unfortunately, the WeChat Official Accounts settings panel only has Mandarin language not like the developer doc. But hopefully my screenshot will help locate it.)
I'm trying to get make an API for the first time and I've made my app but it says I have to do a local authentication with instructions here:
Link to TDAmeritrade authentication
But it says I have to go on https://auth.tdameritrade.com/auth?response_type=code&redirect_uri={URLENCODED REDIRECT URI}&client_id={URLENCODED Consumer Key}%40AMER.OAUTHAP where I plug in the "url encoded redirect uri" and "urlencoded consumer key" and I dont know how to get the URI. Let's say if I'm using local host 1111 do i just plug in "localhost:1111"? because that didnt work
Perhaps that doesn't even matter? because I was writing the following:
import requests
from config import consumer_key
#daily prices generator
endpoint = "https://api.tdameritrade.com/v1/marketdata/{}/pricehistory".format("AAPL")
#parameters
import time
timeStamp=time.time()
timeStamp=int(timeStamp)
parameters = {'api_key':consumer_key,
'periodType':'day',
'frequencyType':"minute",
'frequency':'5',
'period':'1',
'endDate':str(timeStamp+86400),
'startDate':str(timeStamp),
'extendedHourData':'true'}
#caller
stuff = requests.get(url = endpoint, params = parameters)
#reformater
lister = stuff.json()
lister
which returned "{'error': 'The API key in request query param is either null or blank or invalid.'}"
TDA has some rules
timeStamp needs to be in milliseconds
Can only get past 31 days in minute format
There is also some format constraints.
frequenceType=minute --> then use periodType=day
frequencyType=daily --> then use periodType=month
I am a beginner to the Django framework and I am building a Django app that uses the Slack RTM API.
I have a coded a program in python that performs the OAuth authentication process like so :
def initialize():
url="https://slack.com/api/rtm.connect"
payload={"token":"xxx"}
r=requests.post(url,payload)
res=json.loads(r.text)
url1=res['url']
ws = create_connection(url1)
return ws
My Requirement:
The stream of events I receive (from my slack channel that my slack app is added to) is processed to filter out events of the type - message ,then match the message with a regex pattern and then store the matched string in a database.
As a stand alone python program I am receiving the stream of events from my channel.
My questions:
How do I successfully integrate this code to Django so that I can
fulfill my requirement?
Do I put the code in templates/views? What is the
recommended method to process this stream of data?
def initialize():
url = "https://slack.com/api/rtm.connect"
r = requests.get(url, params={'token': '<YOUR TOKEN>'})
res = r.json()
url1=res['url']
ws = create_connection(url1) #Note: There is no function called create_connnection() so it will raise an error
return ws
if you read the API web methods, you see :
Preferred HTTP method: GET
See here: Slack rtm.connect method
look at the comment, and thats the right code, see the differences between this code and yours.
basically to get JSON from a request don't use json.loads because this search your local computer not the request
use r.json() so it call the json you got from r.
Note that r.text will return raw text output so when you want to get url it will not be identified, with r.json you can call the object url as stated about
Hope this help.
and please could you tell us more what you wanna do with this in view ? because template is a directory which contains all the HTML files which you don't need to work with.
but why views.py ?
I have asked a few questions about this before, but still haven't solved my problem.
I am trying to allow Salesforce to remotely send commands to a Raspberry Pi via JSON (REST API). The Raspberry Pi controls the power of some RF Plugs via an RF Transmitter called a TellStick. This is all setup, and I can use Python to send these commands. All I need to do now is make the Pi accept JSON, then work out how to send the commands from Salesforce.
Someone kindly forked my repo on GitHub, and provided me with some code which should make it work. But unfortunately it still isn't working.
Here is the previous question: How to accept a JSON POST?
And here is the forked repo: https://github.com/bfagundez/RemotePiControl/blob/master/power.py
What do I need to do? I have sent test JSON messages n the Postman extension and in cURL but keep getting errors.
I just want to be able to send various variables, and let the script work the rest out.
I can currently post to a .py script I have with some URL variables, so /python.py?power=on&device=1&time=10&pass=whatever and it figures it out. Surely there's a simple way to send this in JSON?
Here is the power.py code:
# add flask here
from flask import Flask
app = Flask(__name__)
app.debug = True
# keep your code
import time
import cgi
from tellcore.telldus import TelldusCore
core = TelldusCore()
devices = core.devices()
# define a "power ON api endpoint"
#app.route("/API/v1.0/power-on/<deviceId>",methods=['POST'])
def powerOnDevice(deviceId):
payload = {}
#get the device by id somehow
device = devices[deviceId]
# get some extra parameters
# let's say how long to stay on
params = request.get_json()
try:
device.turn_on()
payload['success'] = True
return payload
except:
payload['success'] = False
# add an exception description here
return payload
# define a "power OFF api endpoint"
#app.route("/API/v1.0/power-off/<deviceId>",methods=['POST'])
def powerOffDevice(deviceId):
payload = {}
#get the device by id somehow
device = devices[deviceId]
try:
device.turn_off()
payload['success'] = True
return payload
except:
payload['success'] = False
# add an exception description here
return payload
app.run()
Your deviceID variable is a string, not an integer; it contains a '1' digit, but that's not yet an integer.
You can either convert it explicitly:
device = devices[int(deviceId)]
or tell Flask you wanted an integer parameter in the route:
#app.route("/API/v1.0/power-on/<int:deviceId>", methods=['POST'])
def powerOnDevice(deviceId):
where the int: part is a URL route converter.
Your views should return a response object, a string or a tuple instead of a dictionary (as you do now), see About Responses. If you wanted to return JSON, use the flask.json.jsonify() function:
# define a "power ON api endpoint"
#app.route("/API/v1.0/power-on/<int:deviceId>", methods=['POST'])
def powerOnDevice(deviceId):
device = devices[deviceId]
# get some extra parameters
# let's say how long to stay on
params = request.get_json()
try:
device.turn_on()
return jsonify(success=True)
except SomeSpecificException as exc:
return jsonify(success=False, exception=str(exc))
where I also altered the exception handler to handle a specific exception only; try to avoid Pokemon exception handling; do not try to catch them all!
To retrieve the Json Post values you must use request.json
if request.json and 'email' in request.json:
request.json['email']
i have already developed a FB app.now,i am trying to harvest the user data and store it into the database.But, one thing i am not understanding is how to store the data of the logged in user in mongo db using graph api? prior to that how to fetch data in python?
I know this is repetitive but,i am not able to clear my concept of how to use the api in python.
i have tried this:
#!/usr/bin/env python
# encoding: utf-8
import json
import urllib2
import re
def getdata(id):
'''Queries the Facebook API for the specific group ID, and populates the
results dictionary with the Group ID, User Name, and User ID'''
#An access token is now required for quering the group messages.
a_token='access_token=<access token>'
urlquery='https://graph.facebook.com/'+id+'/feed&limit=20?access_token='+ a_token +''
print urlquery
data=json.load(urllib2.urlopen(urlquery))
harvest = []
results = {}
for item in data['data']:
try:
results = {}
results['grpid'] = id
user = item['from']
results['uname'] = user['name']
results['uid'] = user['id']
harvest.append(results)
except:
pass
print len(harvest)
def getgrpids():
urlquery='https://graph.facebook.com/<any username>'#can i put my app name?
#not clear from examples given on facebook graph api page.
data=json.load(urllib2.urlopen(urlquery))
ids=[]
for item in data['data']:
try:
ids.append(item['id'])
except:
pass
return ids
def main():
idres=getgrpids()
for id in idres:
#Loops through all of the group ids returned by getgrpids()
print 'Group ID:', id
getdata(id)
if __name__ == '__main__':
main()
Now the problem goes like this.When i change the username to some other the error report says that the user should be logged in or the app cannot get the user details.I am not understanding this since my friend was online at that time still the error?
Am i missing something?secondly i am not able to put my APP NAME IN THE QUERY (see the comment). Somebody please help.
thanks,
Assuming that you have access token of the user:
import facebook as fb
graph = fb.GraphAPI(access_token)
profile = graph.get_object("me")
# if you want to get the user's profile picture (you need to have the session UID)
profile.update({"picture": "http://graph.facebook.com/%s/picture?type=large" % uid})