I'm trying to search tweets by geo-location. I'm trying to get tweets in New York using:
twitter = Twython(app_key, app_secret, oauth_token, oauth_token_secret)
geocode = "42.3482° N, 75.1890° W"
search_results = twitter.search_geo(count=10,geocode=geocode)
try:
for tweet in search["statuses"]:
print(tweet ['text'])
it returns an error
Traceback (most recent call last):
File "D:\Projects\M Tools\Twython\My works\new.py", line 18, in <module>
search_results = twitter.search_geo(count=10,geocode=geocode)
File "C:\Python34\lib\site-packages\twython-3.2.0-py3.4.egg\twython\endpoints.py", line 818, in search_geo
return self.get('geo/search', params=params)
File "C:\Python34\lib\site-packages\twython-3.2.0-py3.4.egg\twython\api.py", line 263, in get
return self.request(endpoint, params=params, version=version)
File "C:\Python34\lib\site-packages\twython-3.2.0-py3.4.egg\twython\api.py", line 257, in request
api_call=url)
File "C:\Python34\lib\site-packages\twython-3.2.0-py3.4.egg\twython\api.py", line 198, in _request
retry_after=response.headers.get('X-Rate-Limit-Reset'))
twython.exceptions.TwythonError: Twitter API returned a 400 (Bad Request), You must provide valid coordinates, IP address, query, or attributes.
The geocode parameter should be similar to the following in the eventual Twitter search call:
41.8734,-70.6394,5mi
According to the call in the Twitter API console (https://dev.twitter.com/rest/tools/console)
Returns tweets by users located within a given radius of the given
latitude/longitude. The location is preferentially taking from the
Geotagging API, but will fall back to their Twitter profile. The
parameter value is specified by "latitude,longitude,radius", where
radius units must be specified as either "mi" (miles) or "km"
(kilometers). Note that you cannot use the near operator via the API
to geocode arbitrary locations; however you can use this geocode
parameter to search near geocodes directly. A maximum of 1,000
distinct "sub-regions" will be considered when using the radius
modifier.
In Twython, the method search_geo is used to find place_id for 'places' that are within radius of the provided geolocation. You need to use the search method like so:
from twython import Twython, TwythonError
app_key = 'your_app_key'
app_secret = 'your_app_secret'
oauth_token = 'your_oauth_tokem'
oauth_token_secret = 'your_oauth_secret'
twitter = Twython(app_key, app_secret, oauth_token, oauth_token_secret)
geocode = '42.3482,75.1890,1mi' # latitude,longitude,distance(mi/km)
search_results = twitter.search(count=10, geocode=geocode)
try:
for tweet in search_results['statuses']:
print (tweet['text'])
except TwythonError as e:
print(e)
Related
My code is as simple as this, but it gave me 403 error:
def init_api():
api = json.load(open('secret.json'))['twitterapi']
consumer_key = api['api_token']
consumer_secret = api['api_secret']
access_token = api["access_token"]
access_token_secret = api["access_secret"]
bearer_token = api["bearer_token"]
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
#Step 2 - Retrieve Tweets
public_tweets = api.home_timeline()
for tweet in public_tweets:
print(tweet.text)
if __name__ == "__main__":
init_api()
Traceback (most recent call last):
File "path/to/project/config.py", line 45, in <module>
init_api()
File "path/to/project/config.py", line 39, in init_api
public_tweets = api.home_timeline()
File "path/to/project/venv/lib64/python3.10/site-packages/tweepy/api.py", line 33, in wrapper
return method(*args, **kwargs)
File "path/to/project/venv/lib64/python3.10/site-packages/tweepy/api.py", line 46, in wrapper
return method(*args, **kwargs)
File "path/to/project/venv/lib64/python3.10/site-packages/tweepy/api.py", line 488, in home_timeline
return self.request(
File "path/to/project/venv/lib64/python3.10/site-packages/tweepy/api.py", line 259, in request
raise Forbidden(resp)
tweepy.errors.Forbidden: 403 Forbidden
453 - You currently have Essential access which includes access to Twitter API v2 endpoints only. If you need access to this endpoint, you’ll need to apply for Elevated access via the Developer Portal. You can learn more here: https://developer.twitter.com/en/docs/twitter-api/getting-started/about-twitter-api#v2-access-leve
(venv)
From the error message:
453 - You currently have Essential access which includes access to Twitter API v2 endpoints only.
So, you are only allowed to use v2 endpoints, but api.home_timeline() is a v1.1 API, so the v2 endpoint for reading the timeline is:
GET /2/users/:id/tweets
Or, since you are using tweepy, use their v2 API
Client.get_users_tweets(id, *, end_time=None, exclude=None, expansions=None, max_results=None,
media_fields=None, pagination_token=None, place_fields=None, poll_fields=None,
since_id=None, start_time=None, tweet_fields=None, until_id=None,
user_fields=None, user_auth=False)
Request the elevated v1.1 access. It generally gets accepted either instantly or very quickly. May not solve your issue though, because since they folded StreamListener into Stream, I can't seem to figure it out myself.
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
tweet_list=api.favorites.list(screen_name="your_username", count=10)
Error :
Traceback (most recent call last):
File "C:/Python34/fav.py", line 19, in
tweet_list=api.favorites.list(screen_name="your_username", count=10)
AttributeError: 'function' object has no attribute 'list'
From Tweepy docs:
API.favorites([id][, page])
Returns the favorite statuses for the authenticating user or user specified by the ID parameter.
Parameters:
id – The ID or screen name of the user to request favorites
page – Specifies the page of results to retrieve. Note: there are pagination limits.
Return type:
list of Status objects
So you had it almost right, I'm not sure where you got the list method from but remove it and you'll get the list of tweets you want:
tweet_list = api.favorites(screen_name="your_username", count=10)
I am using the below code to post a Tweet. This is a pretty standard authentication procedure but for some reason I cannot authenticate. The error I am getting is Twitter API returned a 401 (Unauthorized), Invalid or expired token.
from twython import Twython, TwythonError
import requests
APP_KEY = 'rpOzpgp2FZNJqsq0' #fake key
APP_SECRET = 'FKBJWXOJwXTblhi1xBl4PtKgPemNFvumH' #fake secret
twitter = Twython(APP_KEY, APP_SECRET)
auth = twitter.get_authentication_tokens()
OAUTH_TOKEN = auth['oauth_token']
OAUTH_TOKEN_SECRET = auth['oauth_token_secret']
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
oauth_verifier_url = auth['auth_url']
oauth_verifier = requests.get(oauth_verifier_url)
# Getting the FINAL authentication tokens
final_step = twitter.get_authorized_tokens(oauth_verifier)
OAUTH_TOKEN = final_step['oauth_token']
OAUTH_TOKEN_SECRET = auth['oauth_token_secret']
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
twitter.update_status(status='Yo')
Here is the full error message:
Traceback (most recent call last):
File "test.py", line 20, in <module>
final_step = twitter.get_authorized_tokens(oauth_verifier)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/twython/api.py", line 380, in get_authorized_tokens
ken'), error_code=response.status_code)
twython.exceptions.TwythonError: Twitter API returned a 401 (Unauthorized), Invalid / expired To ken
Why could I be getting this error and what can I do to fix it?
I have tried regenerating my keys multiple times. I have even deleted my app and created new ones multiple times but I still keep getting this error.
Under Application Settings my access level is set to read and write:
Screenshot of app page
I am not behind a firewall.
I have read other solutions concerning Twython authentication on this site but they all seem to provide the above code as the solution but this itself is not working for me.
I was facing the same problem, but after regeneration of keys the problem got solved.
You need to send four arguments not only 2
Objtwython = Twython(APP_KEY,APP_SECRET,ACCESS_TOKEN,ACCESS_TOKEN_SECRET)
last ones the same way you get the others, getting from twitter directly.
Seems that you're using the Twitter API too often. Due to security reasons, Twitter has rate limiting on the usage of their Twitter API from an arbitrary app. Twitter says in their post how their Twitter API rate-limiting works. You can make a maximum of 15 GET requests under 15 minutes from a specific set of authorization keys of that particular app. After 15 minutes, you are free to make the next 15 requests available.
I'm trying to learn social web mining from this python book entitled Mining the social web, and I'm getting on the first few functions, here's my output:
import twitter
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
OAUTH_TOKEN_SECRET = ''
OAUTH_TOKEN = ''
auth = twitter.oauth.OAuth(OAUTH_TOKEN, OAUTH_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET)
twitter_api = twitter.Twitter(auth=auth)
print twitter_api
WORLD_WOE_ID = 1
US_WOE_ID = 23424977
world_trends = twitter_api.trends.place(_id=WORLD_WOE_ID)
Traceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python2.7/dist-packages/twitter/api.py", line 245, in call
return self._handle_response(req, uri, arg_data, _timeout)
File "/usr/local/lib/python2.7/dist-packages/twitter/api.py", line 276, in _handle_response
raise TwitterHTTPError(e, uri, self.format, arg_data)
twitter.api.TwitterHTTPError: Twitter sent status 400 for URL: 1.1/trends/place.json using parameters: (id=1&oauth_consumer_key=&oauth_nonce=9996743856969920690&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1406787153&oauth_version=1.0&oauth_signature=NAVC2M%2FtUQRL3xtuWZRqsuP1rCg%3D)
details: {"errors":[{"message":"Bad Authentication data","code":215}]}
What seems to be the problem here, how can I use this function correctly?
You should get access token before accessing the twitter url. Follow this link to get the access token.
I am very new to Python having taught it to myself just a few weeks ago. I have tried to cobble together some simple script using Tweepy to do various things with the Twitter API. I have been trying to get the Search API working but to no avail. I have the following code just to simply Search the last 7 days of Twitter for keywords.
# 1.Import required libs and used objects/libs
import tweepy
from tweepy import OAuthHandler
from tweepy import API
from tweepy import Cursor
#2. GET or input App keys and tokens. Here keys/tokens are pasted from Twitter.
ckey = 'key'
csecret = 'secret'
atoken = 'token'
asecret = 'secret'
# 3. Set authorization tokens.
auth = tweepy.OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
#4. Define API.
api = tweepy.API(auth)
#5. Define list or library.
for tweets in tweepy.Cursor(api.search, q = '#IS', count = 100,
result_type ='recent').items():
print tweet.text
Every time I get the following error:
Traceback (most recent call last):
File "C:/Users/jbutk_001/Desktop/Tweety Test/tweepy streaming.py", line 25, in <module>
result_type ='recent')).items():
File "build\bdist.win-amd64\egg\tweepy\cursor.py", line 22, in __init__
raise TweepError('This method does not perform pagination')
TweepError: This method does not perform pagination
I also tried
for tweets in tweepy.Cursor(api.search(q = '#IS', count = 100,
result_type ='recent')).items():
print tweet.text
But then I get:
Traceback (most recent call last):
File "C:/Users/jbutk_001/Desktop/Tweety Test/tweepy streaming.py", line 25, in <module>
result_type ='recent').items():
File "build\bdist.win-amd64\egg\tweepy\cursor.py", line 181, in next
self.current_page = self.page_iterator.next()
File "build\bdist.win-amd64\egg\tweepy\cursor.py", line 101, in next
old_parser = self.method.__self__.parser
AttributeError: 'function' object has no attribute '__self__'
Can anyone please point me in the right direction, this has been driving me nuts for the past few days.
Thanks.
First of all, you are importing some things wrong, you might want to read more about how import works:
What are good rules of thumb for Python imports?
A working example of how to make this kind of search work:
import tweepy
CONSUMER_KEY = 'key'
CONSUMER_SECRET = 'secret'
ACCESS_KEY = 'accesskey'
ACCESS_SECRET = 'accesssecret'
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
for tweet in tweepy.Cursor(api.search,
q="#IS",
count=100,
result_type="recent",
include_entities=True,
lang="en").items():
print tweet.tweet
Also, I would recommend to avoid spaces in filenames, instead of "tweepy streaming.py" go for something like "tweepy_streaming.py".