I'm building a weather bot using watson conversation api.
Whenever a user sends 'what is the weather of '. I get back a response with intents and entities. Now I make a call to a weather api and get a response. How do I pass this weather response back to watson dialog to be displayed?
I think that I have to send the response through context object, but how do I make the call to conversation api to pass the response?
I'm using python api.
In this case, the API Referecence from IBM official document, show one example to how send message inside Watson Conversation Service.
Check this example:
import json
from watson_developer_cloud import ConversationV1
conversation = ConversationV1(
username='{username}',
password='{password}',
version='2017-04-21'
)
# Replace with the context obtained from the initial request
context = {}
workspace_id = '25dfa8a0-0263-471b-8980-317e68c30488'
response = conversation.message(
workspace_id=workspace_id,
message_input={'text': 'Turn on the lights'},
context=context
)
print(json.dumps(response, indent=2))
In this case, to send the message from user, you can use message_input, and to send message like Watson, you can use output.
If your parameter is set to response, for example, you can use:
#Get response from Watson Conversation
responseFromWatson = conversation.message(
workspace_id=WORKSPACE_ID,
message_input={'text': command},
context=context
)
See one official example code from IBM Developers:
if intent == "schedule":
response = "Here are your upcoming events: "
attachments = calendarUsage(user, intent)
elif intent == "free_time":
response = calendarUsage(user, intent)
else:
response = responseFromWatson['output']['text'][0] //THIS SEND THE MESSAGE TO USER
slack_client.api_call("chat.postMessage", as_user=True, channel=channel, text=response,
attachments=attachments)
Use this to send:
response = responseFromWatson['output']['text'][0];
if intent == "timeWeather":
response = "The Weather today is: " +yourReturnWeather
Tutorial from IBM Developer for this project here.
This example will integrate with Slack, but you can see one good example to did what you want in this project.
See official documentation.
Related
I'm building a chatbot deployed via FB messenger. According to FB documentation, you have to send this post request to the messenger platform. I send a string representation of the payload using json.dumps. However, I never see the typing bubble and only get the actual response message from the bot. Here is the pertinent code from the Flask app.
#app.route('/', methods=['GET', 'POST'])
def receive_message():
global tag, latest_message
if request.method == 'GET':
# Before allowing people to message your bot Facebook has implemented a verify token
# that confirms all requests that your bot receives came from Facebook.
token_sent = request.args.get("hub.verify_token")
return verify_fb_token(token_sent)
# If the request was not GET, it must be POSTand we can just proceed with sending a message
# back to user
else:
# get whatever message a user sent the bot
output = request.get_json()
for event in output['entry']:
messaging = event['messaging']
for message in messaging:
if message.get('message'):
# Facebook Messenger ID for user so we know where to send response back to
recipient_id = message['sender']['id']
typing_payload = json.dumps({"recipient":{"id":recipient_id}, "sender_action":"typing_on"})
bot.send_raw(typing_payload)
time.sleep(3)
if message['message'].get('text'):
response_sent_text = send(message['message'].get('text'))
send_message(recipient_id, response_sent_text)
latest_message = response_sent_text
return "Message Processed"
You can use Pymessenger wrapper. Just import it, create an instance and pass your FB_TOKEN and wrap your actions. Remember when sending action, Facebook doc state that you must only pass the recipient_id and action and call the method separate from the response.
set action to "typing_on" in your method.
NB: Your method is incorrect because you are mixing sender_id and recipient_id
from pymessenger import Bot
bot = Bot(<FB_ACCESS_TOKEN>)
def send_typing_bubble(sender_id, recipient_id, action, response_sent_text):
bot.send_action(sender_id, action)
bot.send_text_message(sender_id, response_sent_text)
After your create the method you can just call send_typing_bubble() inside your webhook receive_message() method
if messaging_event.get('message'):
#your code here
send_typing_bubble(sender_id, recipient_id, action,
response_sent_text)
I'm trying to set my chatbot to display a typing bubble before sending the user the response so that it's more human like. I followed the documentation but am still getting instant responses from the bot with no typing bubble. As per the documentation I am using this sender action:
{"recipient":{"id":recipient_id}, "sender_action":"typing_on"}
And to put it in context, here is how I'm using it in the flask app:
#app.route('/', methods=['GET', 'POST'])
def receive_message():
global tag, latest_message
if request.method == 'GET':
# Before allowing people to message your bot Facebook has implemented a verify token
# that confirms all requests that your bot receives came from Facebook.
token_sent = request.args.get("hub.verify_token")
return verify_fb_token(token_sent)
# If the request was not GET, it must be POSTand we can just proceed with sending a message
# back to user
else:
# get whatever message a user sent the bot
output = request.get_json()
for event in output['entry']:
messaging = event['messaging']
for message in messaging:
if message.get('message'):
# Facebook Messenger ID for user so we know where to send response back to
recipient_id = message['sender']['id']
if message['message'].get('text'):
response_sent_text = send(message['message'].get('text'))
send_message(recipient_id, response_sent_text)
latest_message = response_sent_text
return "Message Processed"
def send_message(recipient_id, response):
# sends user the text message provided via input response parameter
typing_payload = {"recipient":{"id":recipient_id}, "sender_action":"typing_on"}
bot.send_raw(typing_payload)
print(bot.send_raw(typing_payload))
bot.send_text_message(recipient_id, response)
return "success"
Any ideas would be much appreciated!
You should pass a string representation of the payload (not a dictionary).
try doing something like this:
import json
...
def send_message(recipient_id, response):
# sends user the text message provided via input response parameter
typing_payload = json.dumps({"recipient":{"id":recipient_id}, "sender_action":"typing_on"})
bot.send_raw(typing_payload)
print(bot.send_raw(typing_payload))
bot.send_text_message(recipient_id, response)
return "success"
Also it's best practice to send these indicators upon receiving message (to show the typing indicator while processing), as opposed to directly before sending message.
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'm working on a webhook that sends Telegrams messages to Slack and Slack messages to Telegram; right now I can send Telegram messages to Slack but I can't send from Slack to Telegram because I don't know how to get the data. As the Slack documentation states, the data sent on the POST request is like this:
token=XXXXXXXXXXXXXXXXXX
team_id=T0001
team_domain=example
channel_id=C2147483705
channel_name=test
timestamp=1355517523.000005
user_id=U2147483697
user_name=Steve
text=googlebot: What is the air-speed velocity of an unladen swallow?
trigger_word=googlebot:
The content type is application/x-www-form-urlencoded
From that data I want to get the user_name and text
On my Flask code I don't have nothing because I don't know how to receive that data or how can I see it on the console so I could try to extract it and send it to Telegram, this is the only thing that I have for the Slack webhook just because I wanted to see if it was working, I think that these lines of code are not relevant right now:
#app.route("/" + SLACK, methods=['POST'])
def slack_handler():
if request.method == "POST":
return "POST"
And that's my problem; how can I receive, store that data? if I should explain more my issue please let me know and thanks for any help.
As long as your slack webhook is configured appropriately you should be able to treat it like a form. The following should work-
from flask import Flask, request
slack_webhook = your_webhook_here
#app.route('/slack', methods=['POST'])
def slack():
if request.form.get('token') == slack_webhook:
channel = request.form.get('channel')
username = request.form.get('username')
return "Channel: " + channel + "Username: " + username
else:
return "None found"
Read this post for more on this-
realpython.com
I am currently using Instagram API in the sandbox mode using Python's python-instagram library. Now, I have an application and its associated client id, client secret and access token, and one connected sandbox user.
Earlier today, I was experimenting with the users/search endpoint. First, I directly used their endpoint URL to send a request:
https://api.instagram.com/v1/users/search?q=XXXX&access_token=<my_access_token>
where XXXX is the connected sandbox user of my Instagram application. This is the generated response:
{"meta":{"code":200},"data":[{"username":"XXXX","bio":"Twitter: #XXXX","website":"","profile_picture":"https:a.jpg","full_name":"XXXX XXXX","id":"22222222"}]}
Now, I tried using the python-instagram library to send request to the same endpoint as follows:
from instagram.client import InstagramAPI
access_token = <my_access_token>
api = InstagramAPI(client_secret='aaaa', access_token = access_token[0])
usr = api.user_search('XXXX')
print usr
However, this is the response I get in this case:
[User: XXXX]
Why is it that I get different responses when I try to call the same endpoint using the direct URL and the Python library?
What python-instagram is doing is that it will take the raw JSON response you get when you issue an HTTP request, and map it to python objects.
When you issue a print usr, you are printing a User object that's in a list, so you see a string which is [User: XXXX].
You can find the model they use for the User object here. It actually directly maps the fields from the Json to get attributes.
Try the following code to retrieve a username and id:
my_usr = usr[0]
print 'User id is', my_usr.id, 'and name is ', my_usr.username