I wrote simple Python script that suppose to send message from myself to myself via Facebook.
The problems is that I can't obtain page access token.
Permissions are set correctly.
import json
import requests
ACCESS_TOKEN = 'generated this with all possible permissions'
r = requests.get('https://graph.facebook.com/me', params={'access_token': ACCESS_TOKEN})
my_id = r.json()['id']
print(my_id)
r = requests.get('https://graph.facebook.com/me/accounts', params={'access_token': ACCESS_TOKEN})
PAGE_ACCESS_TOKEN = r.json()#####['access_token'] cant be found cos 'data' is empty
print(PAGE_ACCESS_TOKEN)
json = {
'recipient': {'id': my_id},
'message': {'text': 'Hello'}
}
params = {
'access_token': PAGE_ACCESS_TOKEN
}
r = requests.post('https://graph.facebook.com/me/messages', json=json, params=params)
print(r)
It's like I don't have access to data in /user/accounts despite that all permissions are set. I only get my user id.
11330393********
{'data': []}
<Response [400]>
What can be done to fix this?
Related
We recently deployed a Bot to Azure with type User assigned managed identity, so I only have app id, but not app password. I am trying to send messages via the Direct Line service from a python app. Following are my code:
from botframework.connector.auth import MicrosoftAppCredentials
from botframework.connector.client import ConnectorClient
credentials = MicrosoftAppCredentials("YOUR_CLIENT_ID", "")
base_url="https://directline.botframework.com/"
client = ConnectorClient(credentials, base_url=base_url)
connectorClient = ConnectorClient(credentials, base_url=base_url)
client.conversations.send_to_conversation(conversation_id, message, service_url=base_url)
The python package I installed is botframework-connector==4.14.0
I got an error about access_token. Can anyone help what I am missing?
Thanks
You can make use of the request library to send direct message to azure bot via direct line like this :
import requests
# Replace YOUR_DIRECT_LINE_SECRET with your bot's Direct Line secret
direct_line_secret = 'YOUR_DIRECT_LINE_SECRET'
# Set the headers for the request
headers = {
'Authorization': 'Bearer ' + direct_line_secret,
'Content-Type': 'application/json'
}
# Set the parameters for the request
data = {
'type': 'message',
'from': {
'id': 'YOUR_USER_ID'
},
'text': 'Hello, world!'
}
# Send the request to the Direct Line API
response = requests.post('https://directline.botframework.com/v3/directline/conversations/YOUR_CONVERSATION_ID/activities', json=data, headers=headers)
# Print the response status code
print(response.status_code)
If you want a user-assigned managed identity to authenticate the BotFrameworkConnectorClient without specifying an app password.
Follow this :
import os
from botframework.connector import ConnectorClient
from botframework.connector.auth import AzureActiveDirectoryAuthentication
# Replace YOUR_CLIENT_ID and YOUR_TENANT_ID with your own values
CLIENT_ID = 'YOUR_CLIENT_ID'
TENANT_ID = 'YOUR_TENANT_ID'
# Get the access token for the Bot Framework API
auth = AzureActiveDirectoryAuthentication(CLIENT_ID, TENANT_ID)
access_token = auth.get_access_token()
# Create a ConnectorClient
client = ConnectorClient(auth, base_url='https://directline.botframework.com/v3/directline')
# Set the parameters for the request
conversation_id = 'YOUR_CONVERSATION_ID'
activity = {
'type': 'message',
'from': {
'id': 'YOUR_USER_ID'
},
'text': 'Hello, world!'
}
# Send the message
response = client.conversations.send_to_conversation(conversation_id, activity)
# Print the response
print(response)
or you could use ManagedIdentityCredential
import os
from azure.identity import ManagedIdentityCredential
from botframework.connector import ConnectorClient
# Set the resource and tenant ID
RESOURCE = "https://directline.botframework.com"
TENANT_ID = "YOUR_TENANT_ID"
# Create a ManagedIdentityCredential
credential = ManagedIdentityCredential(resource=RESOURCE, tenant_id=TENANT_ID)
# Create a ConnectorClient
client = ConnectorClient(credential, base_url='https://directline.botframework.com/v3/directline')
# Set the parameters for the request
conversation_id = 'YOUR_CONVERSATION_ID'
activity = {
'type': 'message',
'from': {
'id': 'YOUR_USER_ID'
},
'text': 'Hello, world!'
}
# Send the message
response = client.conversations.send_to_conversation(conversation_id, activity)
# Print the response
print(response
)
I'm trying to scrape the results of this booking website. The site drops a cookie to recognise the session. I've tried replicating it with requests but I still getting an Invalid Session ID error in my response. What am I doing wrong?
url = 'https://alilauro-tickets.certusonline.com/php/proxy.php'
s = requests.Session()
s.get(url)
data = {
'msg': 'TimeTable',
'req': '{"getAvailability":"Y","getBasicPrice":"Y","getRouteAnalysis":"Y","directOnly":"Y","legs":1,"pax":1,"origin":"BEV","destination":"FOR","tripRequest":[{"tripfrom":"BEV","tripto":"FOR","tripdate":"2020-03-21","tripleg":0}]}'
}
r = s.post(url, data=data, cookies=s.cookies)
Here is the error I get:
'sessionID': none, 'errorCode': '620', 'errorDescription': 'Invalid Session Number'
Here is the cookie information:
Cookie informaiton
Indeed the cookie is present when you call https://alilauro-tickets.certusonline.com/php/proxy.php but the cookie is not valid until a Javascript function call https://alilauro-tickets.certusonline.com/php/proxy.php?msg=Connect. This is a protection against CSRF as Dan-Dev mentionned it in comments.
Using the following would work :
import requests
import json
url = "https://alilauro-tickets.certusonline.com/php/proxy.php"
session = requests.Session()
r = session.post(url, data= { "msg": "Connect"})
r = session.post(url, data= {
"msg": "TimeTable",
"req": json.dumps({
"getAvailability":"Y",
"getBasicPrice":"Y",
"getRouteAnalysis":"Y",
"directOnly":"Y",
"legs":"1",
"pax":1,
"origin":"FOR",
"destination":"BEV",
"tripRequest":[{
"tripfrom":"FOR",
"tripto":"BEV",
"tripdate":"2020-03-20",
"tripleg":0
}]
})
})
print(json.loads(r.text)["VWS_Trips_Trip"])
Question in short: how to get Facebook API access_token with permission
I want to read the reach for specific ad settings from the Facebook API using Python. In order to do so, I need a facebook access token with extended permissions. I use the following function to get a new access token, but the token I get does not have the proper permission levels. So: how to get an access_token with custom permissions, like you can do manually here?
Python example below (problem is actually language independent):
import requests
import json
from facebookads.adobjects.adaccount import AdAccount
from facebookads.api import FacebookAdsApi
from facebookads.adobjects.adset import AdSet
app_id = 'xxxx'
app_secret = 'xxxx'
account_id = 'xxxx'
def get_fb_token(app_id, app_secret):
payload = {'grant_type': 'client_credentials',
'client_id': app_id,
'client_secret': app_secret,
}
file = requests.post('https://graph.facebook.com/oauth/access_token?', params = payload)
string = file.content.decode('utf-8')
json_obj = json.loads(string)
return json_obj['access_token']
access_token = get_fb_token(app_id, app_secret)
account = AdAccount(account_id)
# initiate API
FacebookAdsApi.init(app_id, app_secret, access_token)
# Request reach
targeting_spec = {
'geo_locations': {
'countries': ['nl']
},
}
fb_params = {
'currency': 'EUR',
'optimize_for': AdSet.OptimizationGoal.offsite_conversions,
'targeting_spec': targeting_spec,
}
reach_estimate = account.get_reach_estimate(params=fb_params)
And the error message I get:
(#278) Reading advertisements requires an access token with the extended permission ads_read
Help is highly appreciated!
Try this:
payload = {
'grant_type': 'client_credentials',
'client_id': app_id,
'client_secret': app_secret,
'scope': 'ads_read'
}
file = requests.post('https://graph.facebook.com/oauth/access_token?', params = payload)
Also, you need to redirect to the correct endpoint (https://www.facebook.com/v2.xy/dialog/oauth), not POST to it. You cannot get a User token without user interaction.
I am trying to send a simple POST to an api.
import requests
url ="http://someapi/v1/auth"
payload = {'username': '', 'password': ''}
s1 = requests.post(url, headers={"content-type":"application/x-www-form-urlencoded"}, data=json.dumps(payload))
print s1.status_code
I keep getting status code 401.
Same steps Works fine in POSTMAN.
Any Ideas/pointers ?
Post data in raw format.
payload = "username=;password=;"
s1 = requests.post(
url,
headers={"content-type":"application/x-www-form-urlencoded"},
data=payload)
FWIW, you can click on Code below the Save button on the top right corner of Postman to view code in a couple of languages for your request.
It will only works if the API accepts also JSON body.
Otherwise you can use the #Oluwafemi Sule's answer.
import requests
url ="http://someapi/v1/auth"
payload = {'username': '', 'password': ''}
s1 = requests.post(url, headers={"content-type":"application/json"}, data=json.dumps(payload))
print s1.status_code
This code worked for me.
import requests
from requests_ntlm import HttpNtlmAuth
payload = "username=;password=;"
s= requests.post(
"http://someapi/v1/auth",
headers={"content-type":"application/x-www-form-urlencoded"},
data = payload,
auth=HttpNtlmAuth('',''))
print s.status_code
I am trying to request an authorization code as documented here.
I am using Python requests package to do this and have the following example code:
import requests
auth_endpoint = 'https://login.microsoftonline.com/%s/oauth2/authorize?api-version=1.0' % TENANT_ID
payload = {
'client_id': CLIENT_ID,
'response_type': 'code',
'resource': APP_ID_URI,
'redirect_uri': REPLY_URL
}
response = requests.get(url=auth_endpoint, data=payload)
However, when I run the code above, I get back HTML in the body and not the response I'm expecting. It seems like the HTML code is for a login page.
When I take the formatted endpoint URI and plug it into a browser, I am able to get the auth code from the redirect URI. But, is there a way to get this from the body of the response while still using the requests package?
Please use session class of requests module to implement your requirement. Please refer to the following code sample:
import requests
s = requests.Session()
USERNAME = '<username_email>'
PASSWORD = '<userpassword>'
s.auth = (USERNAME, PASSWORD)
TENANT_ID = '<tenant_id>'
# Authorize URL
authorize_url = 'https://login.microsoftonline.com/%s/oauth2/authorize' % TENANT_ID
# Token endpoint.
token_url = 'https://login.microsoftonline.com/%s/oauth2/token' % TENANT_ID
payload = { 'response_type': 'code',
'client_id': '<tenant_id>',
'redirect_uri': 'http://localhost',
'authority' :'authority'
}
response = s.get(authorize_url, params=payload ,allow_redirects=True)
print response
print response.url
Any further concern, please feel free to let me know.