I am getting this keyerror: 'groups' when trying to fetch nearby venues using Foursquare API - foursquare

Hi I am getting keyerror: 'groups' when trying to fetch nearby venues using Foursquare API. Following is my code:
LIMIT = 100 # limit of number of venues returned by Foursquare API
radius = 500 # define radius
venues_list = []
for lat, long, post, borough, neighborhood, hospital in zip(hospital_df['Latitude'], hospital_df['Longitude'], hospital_df['Pincode'], hospital_df['District'], hospital_df['Location'], hospital_df['Hospital_Name']):
print(neighborhood)
print(borough)
url = "https://api.foursquare.com/v2/venues/explore?client_id={}&client_secret={}&v=
{}&ll={},{}&radius={}&limit={}".format(
CLIENT_ID,
CLIENT_SECRET,
VERSION,
lat,
long,
radius,
LIMIT)
results = requests.get(url).json()["response"]['groups'][0]['items']
venues_list.append([(
post,
borough,
neighborhood,
hospital,
lat,
lng,
v['venue']['name'],
v['venue']['location']['lat'],
v['venue']['location']['lng'],
v['venue']['categories'][0]['name']) for v in results])
nearby_venues = pd.DataFrame([item for venue_list in venues_list for item in venue_list])
nearby_venues.columns = ['PostalCode', 'Borough', 'Neighborhood', 'Hospital', 'Neighborhood_Latitude', 'Neighborhood_Longitude', 'VenueName', 'VenueLatitude', 'VenueLongitude', 'VenueCategory']
I keep getting the following error:
KeyError: 'groups'

I had the same issue "KeyError: 'groups'" with very similar code. What I found was that while my URL variable that I built was incorrectly formed (I added a filter for categoryId, but I passed an incorrectly formatted variable for this value).
Once I corrected this formula, the "results = requests.get(url).json()["response"]['groups'][0['items']" was able to process without errors.
My guess is that when I submitted the incorrectly formed URL, the JSON return was an error message without the correct formatting that included 'groups'.

This was due to exceeding the number of free calls to the Foursquare API in my case. I have very similar code, prewritten as part of an online course. I was running it fine for many days with no issues. Then, suddenly I got the 'groups' key error a few times. Then, I stopped working, and the next morning the code ran fine. Then, after a few calls I got the error again. So I checked the .json file, and it didn't contain the key 'groups' because it was basically a .json file telling me the quota was exceeded.

Try resetting your CLIENT SECRET from Foursquare account. It worked for me.

Related

Google Photos API mediaItems list/search methods ignore pageSize param

I am attempting to do a retrieve of all media items that a given Google Photos user has, irrespective of any album(s) that they are in. However when I attempt to use either the mediaItems.list or the mediaItems.search methods, the pageSize param I am including in either request is either being ignored or not fully fullfilled.
Details of mediaItems.list request
GET https://photoslibrary.googleapis.com/v1/mediaItems?pageSize=<###>
Details of mediaItems.search request
POST https://photoslibrary.googleapis.com/v1/mediaItems:search
BODY { 'pageSize': <###> }
I have made a simple implementation of these two requests here as an example for this question, it just requires a valid accessToken to use:
https://jsfiddle.net/zb2htog1/
Running this script with the following pageSize against a Google Photos account with 100s of photos and 10s of albums consistently returns the same unexpected amount of result for both methods:
Request pageSize
Returned media items count
1
1
25
9
50
17
100
34
I know that Google states the following for the pageSize parameter for both of these methods:
“Maximum number of media items to return in the response. Fewer media
items might be returned than the specified number. The default
pageSize is 25, the maximum is 100.”
I originally assumed that the reason fewer media items might be returned is because an account might have less media items in total than a requested pageSize, or that a request with a pageToken has reached the end of a set of paged results. However I am now wondering if this just means that results may vary in general?
Can anyone else confirm if they have the same experience when using these methods without an album ID for an account with a suitable amount of photos to test this? Or am I perhaps constructing my requests in an incorrect fashion?
I experience something similar. I get back half of what I expect.
If I don't set the pageSize, I get back just 13, If I set to 100, I get back 50.

How to get a certain (e.g. second or third) mention sent in a message

I've been trying to make a ship command that can either ship the author of the message with a mentioned user, or ship two mentioned users. I can get the 1st mention in a message but I have no idea on how to get the 2nd or even third mention in a message. I tried using:
message.mentions.users.first(2)
splitting the args then slicing them so only the second mention is avalaible, but this gives an "undefined" error when I try to get the username.
Could someone give me a script on exactly how to do it since I can't really get the hang of this
According to the documentation message.mentions.users yields a Collection. So you can just iterate over this collection or convert it to an array and then access the required index:
const userArray = message.mentions.users.array();
console.log(userArray[yourDesiredIndex]);

Foursquare API - Cannot query using Category ID and same results keep coming back

I am writing a Foursquare API to find all the Bus Stops via category ID (52f2ab2ebcbc57f1066b8b4f) within a set radius from a set location in New York. I am using the following code:
CLIENT_ID = '123'
CLIENT_SECRET = '456'
latitude = location.latitude
longitude = location.longitude
intent = "checkin"
VERSION = '20180604'
radius = 5000
LIMIT = 10
category = "52f2ab2ebcbc57f1066b8b4f"
and these variables are passed to the URL as follows:
url = 'https://api.foursquare.com/v2/venues/search?client_id={}&client_secret={}&ll={},
{}&intent{}&v={}&radius={}&limit={}&category{}'.format(CLIENT_ID, CLIENT_SECRET,
latitude, longitude, intent, VERSION, radius, LIMIT, category)
which gives
https://api.foursquare.com/v2/venues/search&client_id=123&client_secret=456&ll=40.7149555,-74.0153365&intentcheckin&v=20180604&radius=5000&limit=10&category52f2ab2ebcbc57f1066b8b4f
However, this query returns locations which are not Bus Stops - but the category IDs that are being returned are also not to be found on the Foursquare Dev website, as follows:
In addition, whenever I change the ID to test the code, it brings back the same info. I cant get it to change. Something isnt updating somewhere and I keep restarting my notebook with no effect.
Do we know why my code isn't bringing back bus stop location?
Does it matter the order that I send in the URL? e.g. could I define intent after LL or Category after client ID?
Why am I getting the same return each time?
Thank you.
I have used a workaround to search under a query using the text from the category ID instead. Not perfect, but gets me to where I need to be.

twitter api count more than 100, using twitter search api

i want to search-tweet related 'data' and count more than 100
this is python grammer
from twython import Twython
twitter= Twython(app_key=APP_KEY,app_secret=APP_SECRET)
for status in twitter.search(q='"data"',count =10000)["statuses"]:
user =status["user"]["screen_name"].encode('utf-8')
text =status["text"]
data = "{0} {1} {2}".format(user ,text,'\n\n')
print(data)
f.writelines(data)
So what you're trying to do uses the Twitter API. Specifically the GET search/tweets endpoint.
In the docs for this endpoint:
https://dev.twitter.com/rest/reference/get/search/tweets
We can see that count has a maximum value of 100:
So even though you specify 10000, it only returns 100 because that's the max.
I've not tried either, but you can likely use the until or max_id parameters also mentioned in the docs to get more results/the next 100 results.
Keep in mind: "that the search index has a 7-day limit. In other words, no tweets will be found for a date older than one week" - the docs
Hope this helps!
You can use the field next_token of the response to get more tweets.
Refer to these articles:
https://lixinjack.com/how-to-collect-more-than-100-tweets-when-using-twitter-api-v2/
https://developer.twitter.com/en/docs/twitter-api/tweets/search/integrate/paginate
The max_id parameter is the key and it is further explained here:
To use max_id correctly, an application’s first request to a timeline
endpoint should only specify a count. When processing this and
subsequent responses, keep track of the lowest ID received. This ID
should be passed as the value of the max_id parameter for the next
request, which will only return Tweets with IDs lower than or equal to
the value of the max_id parameter.
https://developer.twitter.com/en/docs/tweets/timelines/guides/working-with-timelines
In other words, using the lowest id retrieved from a search, you can access the older tweets. As mentioned by Tyler, the non-commercial version is limited to 7-day, but the commercial version can search up to 30 days.

Foursquare API error No venues or groups specified returned when adding campaign

Using the Foursquare Merchant API, I'm trying to add a campaign. I am able to add a special successfully. However, when using the special's id and adding a campaign, I receive the following error, "Foursquare2::APIError: other: No venues or groups specified. (400)".
Even after specifying both the specialId and venueId, I receive the same error. Although the foursquare docs state that only the specialId is required.
I am using the Foursquare2 ruby wrapper gem with my code additions to add a campaign
def add_campaign(options={})
response = connection.post do |req|
req.url "campaigns/add", options
end
return_error_or_body(response, response.body.response.campaign)
end
Having receiving a client object from the foursquare gem. I use the below code
client.add_campaign(:specialId => specialId, :venueId => venueId)
Any thoughts on why this is causing an error?
venueIds and groupIds are not individually required, but one of them must be provided. I'll update the documentation to make this clearer. Thanks for pointing this out!

Resources