Send location ( lat & long ) to API AI - python

I'm using API AI to make a Facebook bot. After sharing my location in Facebook chat bot. I got a JSON like this:
{'message': {'attachments': [{'payload': {'coordinates': {'lat': 52.335001190772,'long': 4.8887078680234}},'title': 'Holiday Inn','type': 'location','url': 'https://www.facebook.com/l.php?u=https%3A%2F%2Fwww.bing.com%2Fmaps%2Fdefault.aspx%3Fv%3D2%26pc%3DFACEBK%26mid%3D8100%26where1%3DDe%2BBoelelaan%2B2%252C%2B1083%2BHJ%2BAmsterdam%252C%2BNetherlands%26FORM%3DFBKPL1%26mkt%3Den-US&h=mAQEt4NIX&s=1&enc=AZN97DQxpVq5xpkZqvgi3bMq2OVJNwWBOXOiIOW4FHx1-kgYHxTPKfFwRkUsl0ibr0K5GAquaEltxBMLGvjxmUbCa1AmptlN85rg4jLhDH6K0g'}],
According to that JSON, I have lat and long value:
payload = message['message']['attachments'][0]['payload']
lat = payload['coordinates']['lat']
long = payload['coordinates']['long']
What I want is to send those values to parameters in API AI. So I wrote a method to post that:
def post_location(self, text, lat, long):
return self.get(
params={
'query': text,
'parameters': {
'latitude': lat,
'longitude': long,
},
'lang': 'en'
}
)
And this is how my get looks like:
def get(self, params):
"""
Get connection with api ai
:rtype: object
"""
print(params)
request = requests.get(
url=self.url, params=params, headers=self.headers)
content = request.content.decode('utf-8')
try:
return json.loads(content)
except ValueError:
print('Invalid JSON')
Finally I call post_location method where I handle the facebook message and give it the values but when I run, only the text ( query ) is sent to API AI.
def _post_location_to_api(message, lat, long):
ai_api = AIApi()
return ai_api.post_location(message, lat, long)
location = _post_location_to_api(message['message']['attachments'][0]['type'], latitude, longitude)
print(location) gives me this:
{'id': 'd4374511-86ce-4ccb-b7b3-e813011a0998', 'sessionId': '00000000-0000-0000-0000-000000000000', 'timestamp': '2016-10-04T11:26:11.613Z', 'result': {'action': 'PlaceSearch', 'actionIncomplete': False, 'score': 0.51, 'contexts': [], 'fulfillment': {'speech': ''}, 'parameters': {'latitude': '', 'longitude': ''}, 'source': 'agent', 'resolvedQuery': 'location', 'metadata': {'intentName': 'I want to eat in Amsterdam', 'intentId': '89f515a6-f723-4df5-96b2-9e0f784747c6', 'webhookUsed': 'true', 'warning': 'IMPORTANT: Please use unique session ID for each client. Otherwise you may experience unstable behaviour.'}}, 'status': {'errorDetails': 'Webhook call failed. Status code 404. Error:404 Not Found', 'errorType': 'partial_content', 'code': 206}}
What did I do wrong?

Related

python - aiohttp.ClientSession().post

So, I had this code and it worked perfectly fine:
def upload_to_imgur(url):
j1 = requests.post(
"https://api.imgur.com/3/upload.json",
headers=headers,
data={
'key': api_key,
'image': b64encode(requests.get(url).content),
'type': 'base64',
'name': '1.jpg',
'title': 'Picture no. 1'
}
)
data = json.loads(j1.text)['data']
return data['link']
Now, I wanted to make all this async, but that doesn't really seem to work. Here's my current code:
async def async_upload_to_imgur(url):
image = await get_as_base64(url)
j1 = await aiohttp.ClientSession().post(
"https://api.imgur.com/3/upload.json",
headers=headers,
data={
'key': api_key,
'image': image,
'type': 'base64',
'name': '1.jpg',
'title': 'Picture no. 1'
}
)
data = await j1.json()
return data['link']
The get_as_base64-function is not the issue.
Header and Api Key are the same
This is the output when I print "data" in the second example.
{'data': {'error': {'code': 1001, 'message': 'File was not uploaded correctly', 'type': 'Exception_Logged', 'exception': {}}, 'request': '/3/upload.json', 'method': 'POST'}, 'success': False, 'status': 500}
It has to be the get_as_base64, for 2 reasons -:
1.) It says the file was not uploaded correctly meaning it doesn't support the URL or something like that
2.) I think you need to link a file not a link containing the file in it.

Process JSON Responses, Editing and Sending

I am working with an API. I get a response from the API which looks like this:
from oauthlib.oauth2 import BackendApplicationClient
from requests.auth import HTTPBasicAuth
from requests_oauthlib import OAuth2Session
auth = HTTPBasicAuth(client_id, client_secret)
client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
token = oauth.fetch_token(token_url=token_url, auth=auth)
client = OAuth2Session(client_id, token=token, auto_refresh_url=token_url,token_updater=token_saver)
token_saver = []
device_policy = client.get('{URL}/v1?ids='+ids)
I get this response
[{'id': '',
'name': 'A Name',
'description': '',
'platform_name': 'Windows',
'groups': [],
'enabled': True,
'created_by': 'An Email',
'created_timestamp': '2019-03-28T12:51:30.989736386Z',
'modified_by': 'An Email ,
'modified_timestamp': '2019-11-19T21:14:53.0189419Z',
'settings': {'enforcement_mode': 'MONITOR_ENFORCE',
'end_user_notification': 'SILENT',
'classes': [{'id': 'ANY', 'action': 'FULL_ACCESS', 'exceptions': []},
{'id': 'IMAGING', 'action': 'FULL_ACCESS', 'exceptions': []},
{'id': 'MASS_STORAGE', 'action': 'BLOCK_ALL', 'exceptions': []},
{'id': 'MOBILE', 'action': 'BLOCK_ALL', 'exceptions': []},
{'id': 'PRINTER', 'action': 'FULL_ACCESS', 'exceptions': []},
{'id': 'WIRELESS', 'action': 'BLOCK_ALL', 'exceptions': []}]}}]
In each class there is list for hold exceptions. The API accepts a patch (not really a patch) that if this data is resubmitted with the exception field holding the contents of this function then an exception is accepted.
`
file_info = {
"class": "ANY",
"vendor_name": "",
"product_name": "",
"serial_number": serial_number,
"combined_id": "",
"action": "FULL_ACCESS",
"match_method": "VID_PID_SERIAL"
}
`
The challenge I have is accepting the first document and then adding the exception material to create a this patch request. I can "walk" the document but cannot work how to create a new body text to send. I think I want to do something like this but not using append as this throws an error.
new_walk_json = walk_json.append(['classes'][0]['exceptions']['Test'])
Realised .update function can used.

How to fix "'User' object is not subscriptable"

I am trying to write some Python code, that gets the users Gitlab Profile picture/avatar to be sent in a Discord Embed later on in the code. However, when i try to read the json that the Gitlab API returns but i receive the error "'User' object is not subscriptable" this json doesnt look like other jsons returned by the Gitlab API.
I have tried to use Attributes but i still receive the same error, i have also tried just to read it but i still receive the same error.
import gitlab
import json
# private token or personal token authentication
gl = gitlab.Gitlab('URL', private_token='')
project = gl.projects.get(13)
json_data = project.tags.list(order_by='updated', sort='desc')
newest_tagjson = (json_data[0].attributes)
latesttag = newest_tagjson["name"]
name1 = newest_tagjson["commit"]["author_name"]
projectid = newest_tagjson["project_id"]
footer1 = "Panel"
if name1 == "------":
ID = 16
user = gl.users.get(ID)
print(user)
user2 = (user['avatar_url'].attributes)
i should receive a clean json that i can read but instead i recieve this in the print
<class 'gitlab.v4.objects.User'> => {'id': 16, 'name': '', 'username': '', 'state': 'active', 'avatar_url': 'https://URL.io/uploads/-/system/user/avatar/16/avatar.png', 'web_url': '', 'created_at': '2019-01-29T18:30:53.819Z', 'bio': ' \r\n', 'location': ', United Kingdom', 'public_email': '', 'skype': '', 'linkedin': '', 'twitter': '', 'website_url': '', 'organization': ''}
and i cannot read this.
The error seems pretty clear: the result of calling gl.users.get(ID) is not a Python dictionary, so you can't access keys with subscripts as in user['avatar_url']. You can access attributes using Python's dot notation, as in user.avatar_url.
You can of course extract the information you want into a Python dictionary:
>>> user_dict = {k: getattr(user, k) for k in
... ['id', 'name', 'state', 'avatar_url', 'web_url']}
>>> user_dict
{'id': 28841, 'name': 'Lars Kellogg-Stedman', 'state': 'active', 'avatar_url': 'https://secure.gravatar.com/avatar/1c09a8d9e719f9d13b6c99f6bb2637d8?s=80&d=identicon', 'web_url': 'https://gitlab.com/larsks'}
And then you can serialize this to JSON:
>>> print(json.dumps(user_dict, indent=2))
{
"id": 28841,
"name": "Lars Kellogg-Stedman",
"state": "active",
"avatar_url": "https://secure.gravatar.com/avatar/1c09a8d9e719f9d13b6c99f6bb2637d8?s=80&d=identicon",
"web_url": "https://gitlab.com/larsks"
}
The Python gitlab module wraps the gitlab API in a variety of managers designed to make certain things easier, but if your goal is to serialize things to JSON it might be easier to simply call the REST API yourself:
>>> import requests
>>> session = requests.Session()
>>> session.headers['private-token'] = your_private_token
>>> res = session.get('https://gitlab.com/api/v4/users/28841')
>>> res.json()
{'id': 28841, 'name': 'Lars Kellogg-Stedman', 'username': 'larsks', 'state': 'active', 'avatar_url': 'https://secure.gravatar.com/avatar/1c09a8d9e719f9d13b6c99f6bb2637d8?s=80&d=identicon', 'web_url': 'https://gitlab.com/larsks', 'created_at': '2014-04-26T01:52:14.000Z', 'bio': '', 'location': None, 'public_email': '', 'skype': '', 'linkedin': '', 'twitter': 'larsks', 'website_url': 'http://blog.oddbit.com/', 'organization': None}

Where I can get payer_id for executing payment (paypal)?

Working with PayPal Python REST SDK. After payment created we need to execute this payment. At https://github.com/paypal/PayPal-Python-SDK/blob/master/samples/payment/execute.py is code sample. But when executing payment
if payment.execute({"payer_id": "DUFRQ8GWYMJXC"}): # return True or False
print("Payment[%s] execute successfully" % (payment.id))
else:
print(payment.error)
we need to write payer_id. But how I can take it? Any ideas or code examples?
The payerid is returned in the host headers on the callback - Alternatively, you can do the following..
In the process of creating a sale, do...
saleinfo_ = {"intent":"sale",
"redirect_urls":{
"return_url":("myurlonsuccess"),
"cancel_url":("myurlonfail")
},
"payer":{"payment_method":"paypal"},
"transactions":[
{"amount":{"total":out_totaltopay_, "details":{"tax":out_taxes_, "subtotal":out_subtotal_}, "currency":symbol_}, "description":description_}
payment_ = Payment(saleinfo_)
if (payment_.create()):
token_ = payment_.id
Then when the return callback arrives, use...
payment_ = Payment.find(token_)
if (payment_ != None):
payerid_ = payment_.payer.payer_info.payer_id
if (payment_.execute({"payer_id":payerid_})):
....
The json data received in the find process is similar to the following
{'payment_method': 'paypal', 'status': 'VERIFIED', 'payer_info': {'shipping_address': {'line1': '1 Main St', 'recipient_name': 'Test Buyer', 'country_code': 'US', 'state': 'CA', 'postal_code': '95131', 'city': 'San Jose'}, 'first_name': 'Test', 'payer_id': '<<SOMEID>>', 'country_code': 'US', 'email': 'testbuyer#mydomain.com', 'last_name': 'Buyer'}}
Hope that helps

Convert json list into dictionary in python

The data I am using is Twitter API's twitter trending topics.
url_0 = 'https://api.twitter.com/1.1/trends/place.json?id=2459115'
res = requests.get(url_0, auth=auth)
print(res, res.status_code, res.headers['content-type'])
print(res.url)
top_trends_twitter = res.json()
data= top_trends_twitter[0]
This is how data looks like:
[{'as_of': '2017-02-13T21:59:32Z',
'created_at': '2017-02-13T21:53:22Z',
'locations': [{'name': 'New York', 'woeid': 2459115}],
'trends': [{'name': 'Victor Cruz',
'promoted_content': None,
'query': '%22Victor+Cruz%22',
'tweet_volume': 45690,
'url': 'http://twitter.com/search?q=%22Victor+Cruz%22'},
{'name': '#percussion',
'promoted_content': None,
'query': '%23percussion',
'tweet_volume': None,
'url': 'http://twitter.com/search?q=%23percussion'}, .....etc
Now, after I connect the server with SQL, and create database and table, an error appears. This is the part that is causing me trouble:
for entry in data:
trendname = entry['trends']['name']
url = entry['trends']['url']
num_tweets = entry['trends']['trend_volume']
date= entry['as_of']
print("Inserting trend", trendname, "at", url)
query_parameters = (trendname, url, num_tweets, date)
cursor.execute(query_template, query_parameters)
con.commit()
cursor.close()
Then, I get this error:
TypeError Traceback (most recent call last)
<ipython-input-112-da3e17aadce0> in <module>()
29
30 for entry in data:
---> 31 trendname = entry['trends']['name']
32 url = entry['trends']['url']
33 num_tweets = entry['trends']['trend_volume']
TypeError: string indices must be integers
How can I get the set of strings into dictionary, so that I can use that for entry data code?
You Need entry['trends'][0]['name']. entry['trends'] is a list and you need integer index to access items of list.
Try like so:
data=[{'as_of': '2017-02-13T21:59:32Z',
'created_at': '2017-02-13T21:53:22Z',
'locations': [{'name': 'New York', 'woeid': 2459115}],
'trends': [{'name': 'Victor Cruz',
'promoted_content': None,
'query': '%22Victor+Cruz%22',
'tweet_volume': 45690,
'url': 'http://twitter.com/search?q=%22Victor+Cruz%22'},
{'name': '#percussion',
'promoted_content': None,
'query': '%23percussion',
'tweet_volume': None,
'url': 'http://twitter.com/search?q=%23percussion'}]}]
for entry in data:
date= entry['as_of']
for trend in entry['trends']:
trendname = trend['name']
url = trend['url']
num_tweets = trend['tweet_volume']
print trendname, url, num_tweets, date
Output:
Victor Cruz http://twitter.com/search?q=%22Victor+Cruz%22 45690 2017-02-13T21:59:32Z
#percussion http://twitter.com/search?q=%23percussion None 2017-02-13T21:59:32Z

Categories