Bot Framework Web Chat Token Protocol - python

I'm building a chatbot for fun and I cannot send messages to the following API: https://webchat.botframework.com/api/conversations.
After a webchat user send a message, I know the conversation Id and Sender ID. In order to reply, I do the following steps:
First, I retrieve the token with the following code:
response = requests.post(
"https://webchat.botframework.com/api/tokens/conversation",
headers={"Authorization": "BotConnector " + pwdChat,"Content-Type": "application/json"})
data = response.json()
token = data
Then, I would like to send a message to the webchat user with he following code:
requests.post('https://webchat.botframework.com/api/conversations/' + sendersk2 + '/messages/',
headers={"Authorization": "Botconnector " + token, "Content-Type": "application/json"},
json={
"type": "message",
"text": "Hi!"
})
But, I receive an Response [403] error labelled as : "BadArgument:Security token not valid for this conversation"
Any idea of the issue?

There are a couple things that might help.
The endpoint you're using brings back a complex JSON object and you'll need to extract the token property from that.
Alternatively, you can use https://webchat.botframework.com/api/tokens instead, but you'll also need to trim quotes off the end.
Basically, look at the response from your token POST request and ensure you're pulling the token out properly.

Additionally it looks like you are talking to the V1 endpoints. We no longer actively support V1. Please consider upgrading to V3. Thanks.

Related

How to take take access tokens from oauth2

I'm having problems on taking the access token from the oauth2 platform with python.
Currently, that's what I'm using on my post request:
def token(self):
client_id=ID_DO_CLIENTE
client_secret=SECRET_TOKEN
grant_type='client_credentials'
response = requests.post("https://oauth2.googleapis.com/token",
auth=(client_id, client_secret),
data={'grant_type':grant_type,'client_id':client_id,'client_secret':client_secret})
print(response.text)
This specific code is returning the following error:
{
"error": "unsupported_grant_type",
"error_description": "Invalid grant_type: "
}
But I don't think the problem is the grant_type, since I've tried everything I've found online to solve this.
Anyway, if there's any info missing, please let me know. Please help !
A valid request will also need these headers in order to send data in the correct format - I suspect JSON is sent by default, resulting in a malformed request:
Content-Type: application/x-www-form-url-encoded
Authorization: Basic [base 64 encoded client id and secret]
TECHNIQUES
Aim to use the curl tool to get the token first, to ensure the setup is right - as in this article.
Also aim to trace the request via an HTTP proxy tool to ensure that the wire message is being sent correctly.
These techniques will make you more productive when working with OAuth.
CODE
I had a search and this answer seems to use the correct code, though you may be able to send the Authorization header like this:
auth=HTTPBasicAuth('user', 'pass')
This is a sample code for reference:
data = {'grant_type': 'client_credentials'}
requests.post(token_url,
data=data,
auth=(client_id, client_secret))
In the provided sample code, the data part is being sent incorrectly viz:
data={'grant_type':grant_type,'client_id':client_id,'client_secret':client_secret}
I think it should be this:
data={'grant_type':grant_type}
Adding the sample code which I am testing to verify the token generation logic:
client_id = '<value>'
client_secret = '<value>'
# This is optional
scope = '<uri>'
#Token generation step
#If scope is not defined above then remove it from this call
data = {'grant_type': 'client_credentials','scope': scope}
access_token_response = requests.post(token_url, data=data, verify=False, allow_redirects=False, auth=(client_id, client_secret))
print (access_token_response.headers)
print (access_token_response.text)
tokens = json.loads(access_token_response.text)
print ("access token: " + tokens['access_token'])

Alexa fetching user email using python

I am trying to make an Alexa skill using python backend.
I am using amazon developer console to create model and code backend.
I want to retrieve user email address.
I would appreciate if you could provide me with sample code. I tried many methods but none were working.
here are some codes I tried :
https://github.com/alexa/alexa-skills-kit-sdk-for-python/tree/master/samples/GetDeviceAddress
I know this is device address but this was also not working, and I thought if i could get address I can get email.
Everything mentioned online is for Node, and I want to make my backend on python
As specified in the official documentation you need to make an API call to the ASK.
For email you need to call your api_endpoint followed by /v2/accounts/~current/settings/Profile.email
For me endpoint is : https://api.eu.amazonalexa.com therefore the complete url becomes :
https://api.eu.amazonalexa.com/v2/accounts/~current/settings/Profile.email
As far as adding the token to authorize the request it can be done by using the requests library by passing header to the get request. You can learn more about that from here
The final code should then look something like this :
#Fetching access token
accesstoken = str(handler_input.request_envelope.context.system.api_access_token)
#Fetching user emailaddress from ASK API
endpoint = "https://api.eu.amazonalexa.com/v2/accounts/~current/settings/Profile.email"
api_access_token = "Bearer " + accesstoken
headers = {"Authorization": api_access_token}
r = requests.get(endpoint, headers=headers)
email = r.json()
Hope this helps, Cheers!

Python - Spotify API returning Error 400 "Malformed JSON"

Heyo. I'm trying to make a small application in my spare time that uses the Spotify API . I have managed to get my program to use oAuth 2 to let a user authorize my app to manipulate their Spotify, but I have run into a problem with a certain endpoint on the Spotify API.
The endpoint I am having trouble with is https://api.spotify.com/v1/me/player/play (here's a link to their docs for the endpoint https://developer.spotify.com/console/put-play/). Whenever I try to make a put request to the endpoint I receive a 400 status code with the message "Malformed json" I get this message even when I copy/paste their own json from the docs, so I don't think it's a problem with how I am formatting my json, besides I have used json before to call other endpoints and they haven't had a problem with my formatting on those calls.
Here is my code:
headers = {"Authorization":"Bearer {}".format(access_token)}
url = 'https://api.spotify.com/v1/me/player/play'
payload = {"context_uri": "spotify:album:5ht7ItJgpBH7W6vJ5BqpPr"}
r = requests.put(url, headers=headers, data=payload)
print(r)
print(r.text)
To clarify, access_token is the access token that I have gotten from their authorization process, and I am using python-requests to make the http requests (Here is the docs for that: https://requests.kennethreitz.org/en/master/)
I am wondering if the problem is due to the fact that Spotify uses colons int their track IDs and colons are also used in JSON? I saw in another thread on here that I should try to add "Content-Type":"application/json" to my headers but that didn't change the outcome at all.
Any help is greatly appreciated, and if you need any more info please let me know. Thank you!
If your payload is a dict use json kwargs in requests lib. data works for string payload. Here you go:
r = requests.put(url, headers=headers, json=payload)

Why am I getting a 403 error response with my SurveyMonkey API get request?

I have attempted to follow the SurveyMonkey API documentation to a tee, just to get familiar with it before I move into the very simple functionality of my private application.
I have pretty much attempted to duplicate exactly what I've found in the documentation, but am getting a 403 response. You can see the exact snipped of code here in the docs: https://api.surveymonkey.net/v3/docs?python#surveys-id
api_token = 'MyVerySecretApiKey'
survey_id = 'ASillyLittleNumber'
s.headers.update ({
"Authorization": "Bearer %s" % api_token,
"Content-Type": "application/json"
})
HOST = "https://api.surveymonkey.com/v3/surveys/%s" % (survey_id)
print s.get(HOST)
I've printed the GET just to see what exactly I'm getting, and I'm getting Response [403]. I can't figure out what I've done, especially with such a simple application. I've checked my api token and the survey id several time for accuracy. Is there anything I'm not understanding about the code from the documentation?
I've passed my api key and survey id as strings, and that's correct right?
Your code looks fine - the requests module will take care of integers / strings in your headers, no need to worry about that.
The only thing I can think of is that maybe you're confusing your API key with your bearer token - based on this line:
api_token = 'MyVerySecretApiKey'
Check the settings page on your SM dev page and see if you can generate a bearer token for your account, and if it differes from the API key.

Token error when sending Wechat message with Python

I have a Wechat subscribe page, and I set up in https://admin.wechat.com/ a token as well as the webhook URL of my server myserver.com/wechat/webhook
My server Python code authenticates Wechat server with signature check, nonce and timestamp and I'm able to receive messages from Wechat to my webhook.
But I can't send messages from my server to Wechat, I'm using the following code and the token set in the admin console as previously, and following the previous docs:
http://admin.wechat.com/wiki/index.php?title=Customer_Service_Messages
# Parse the received WeChat message
message = xmltodict.parse(message)
content = message['xml']['Content']
fromUser = message['xml']['FromUserName']
toUser = message['xml']['ToUserName']
createdTime = message['xml']['CreateTime']
# reply to message
post_data = {
"touser": fromUser,
"msgtype": "text",
"text":
{
"content": "Thanks for your message"
}
}
api_url = 'https://api.wechat.com/cgi-bin/message/custom/send?access_token=' + token
response = requests.post(api_url, data=post_data)
content = response.content
This is the error that I'm getting:
{"errcode":40001,"errmsg":"invalid credential, access_token is invalid or not latest hint: [udQ9ka0880vr32!]"}
What token am I supposed to use? Or what could be the error? Thanks
I think it might be a permission problem... In my Wechat page admin console, it says I have Permission obtained for Auto-reply, but not for Service API. Anyone can confirm this?
Indeed I tested successfully instantly replying to POST messages with an http response (Auto-reply or callback) http://admin.wechat.com/wiki/index.php?title=Callback_Messages
And the Service API seems to not be working (which was the purpose of my question) http://admin.wechat.com/wiki/index.php?title=Customer_Service_Messages

Categories

Resources