import tweepy
import json
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
OAUTH_TOKEN = ''
OAUTH_TOKEN_SECRET = ''
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
twitter_api = tweepy.API(auth)
# I made a dict of different countries and their WOE_ID...
PLACE_WOE_ID = country_id[country]
place_trends = twitter_api.trends.place(_id=PLACE_WOE_ID)
Everytime I run my code I am getting the following error. I checked other posts on stackoverflow regarding twitter api but I haven't found a solution yet.
Traceback (most recent call last):
File "C:/Users/user/Documents/twipgm.py", line 44, in <module>
place_trends = twitter_api.trends.place(_id=PLACE_WOE_ID)
AttributeError: 'API' object has no attribute 'trends'
There is no method like
place()
in tweepy documentation.
place_trends = twitter_api.trends_place(..)
Should solve your problem, I strongly suggest you to check this docs.
Note that Tweepy 4.0 version has renamed this method to .get_place_trends().
You can follow this tutorial to get some recent updates on Tweepy >4.0 use cases.
Related
The following code I wrote was intended to retweet tweets with #programming. But, anything I run the code I get an error "search" object is not an attribute of the Twitter API. The error is posted below the code. Thanks
import tweepy
import time
# get api code and password(secret)
comsumers_key = '#########'
comsumers_secret = '######'
token_key = '#########'
token_secret = '###########'
auth = tweepy.OAuthHandler(comsumers_key,comsumers_secret)
auth.set_access_token(token_key, token_secret)
api = tweepy.API(auth)
hashtag = "programming"
tweetNum = 20
tweets = tweepy.Cursor(api.search, hashtag).items(tweetNum)
def bot1():
for tweet in tweets:
try:
tweet.retweet()
print("retweet")
time.sleep(50)
except tweepy.TweepError as e:
print(e.reason)
time.strftime(20)
bot1()
error:
Traceback (most recent call last):
File "/Users/sonter/tweetbot/bot1.py", line 48, in <module>
tweets = tweepy.Cursor(api.search, hashtag).items(tweetNum)
AttributeError: 'API' object has no attribute 'search'
The Cursor expects a regular api method, but looking at its reference doc there is no search only, but :
search_30_day
search_full_archive
search_tweets
search_users
search_geo
Maybe you meant one of them ?
I'm trying to get Tweets using the Tweepy module in Python. However, whenever I try to collect Tweets using the tweepy.Cursor function, it returns the error:
TweepyException Traceback (most recent call last)
<ipython-input-5-a26c992842dc> in <module>
----> 1 tweets_list = tweepy.Cursor(api.search_tweets(q="oranges", tweet_mode='extended', lang='en')).items()
~\anaconda3\lib\site-packages\tweepy\cursor.py in __init__(self, method, *args, **kwargs)
38 raise TweepyException('Invalid pagination mode.')
39 else:
---> 40 raise TweepyException('This method does not perform pagination')
41
42 def pages(self, limit=inf):
TweepyException: This method does not perform pagination
I do not know why this is. I can still post Tweets using the api.update_status() function. Please help. Here is my code. As you can see, the setup is correct; it is only this function that is returning the error.
from config import *
import tweepy
import datetime
consumer_key= 'CONSUMER KEY HERE'
consumer_secret= 'CONSUMER KEY SECRET HERE'
access_token= 'ACCESS TOKEN HERE'
access_token_secret= 'ACCESS TOKEN SECRET HERE'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
try:
api.verify_credentials()
print("Authentication Successful")
except:
print("Authentication Error")
tweets_list = tweepy.Cursor(api.search_tweets(q="oranges", tweet_mode='extended', lang='en')).items()
If there is an error in the function or the code itself, can you please write a correct version? I'm trying to gather Tweet data for a project.
You're passing the result of the call to / invocation of API.search_tweets, rather than the method itself, to Cursor.
See Tweepy's Pagination documentation for an example of how to use Cursor.
I install Tweepy and Python-Twitter and try code, and I tried to run.
If I try this code:
import tweepy
import time
#insert your Twitter keys here
consumer_key ='xxx'
consumer_secret='xxx'
access_token='xxx'
access_token_secret='xxx'
twitter_handle='handle'
auth = tweepy.auth.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
list= open('twitter_followers.txt','w')
if(api.verify_credentials):
print ('We successfully logged in')
user = tweepy.Cursor(api.followers, screen_name=twitter_handle).items()
while True:
try:
u = next(user)
list.write(u.screen_name +' \n')
except:
time.sleep(15*60)
print ('We got a timeout ... Sleeping for 15 minutes')
u = next(user)
list.write(u.screen_name +' \n')
list.close()
I get this error when I do:
File "C:\Users\xxx.py", line 19, in <module>
user = tweepy.Cursor(api.followers, screen_name=twitter_handle).items()
AttributeError: 'API' object has no attribute 'followers'
Are there any errors that have not been progressed yet?
Tweepy v4.0.0 renamed API.followers to API.get_followers.
Also, you're not calling API.verify_credentials and instead only checking if the method exists, so that if statement expression will always evaluate to True and print.
I am trying to make a program that will remove songs from spotify playlists. Currently I am unable to refresh the auth tokens despite having them saved on my hard drive and specifying the cache paths when making oauth objects.
from bottle import route, run, request
import spotipy
from spotipy import oauth2
import time
PORT_NUMBER = 8080
SPOTIPY_CLIENT_ID = 'e1bb48ed8b594aeb9faf74f7e8915de7'
SPOTIPY_CLIENT_SECRET = 'dd6de8b7a0324d6ebf1fc0591e8e3220'
SPOTIPY_REDIRECT_URI = 'http://localhost:8080'
SCOPE = 'playlist-modify-public'
tracks = ['6DCZcSspjsKoFjzjrWoCdn']
def remove(sp_oauth):
access_token = ""
token_info = sp_oauth.get_cached_token()
if token_info:
if sp_oauth.is_token_expired:
token_info = sp_oauth.refresh_access_token(token_info['refresh_token'])
access_token = token_info['access_token']
else:
print ("Found cached token!")
access_token = token_info['access_token']
if access_token:
print ("Access token available! Trying to get user information...")
sp = spotipy.Spotify(access_token)
results = sp.current_user_playlists()
userinfo = sp.current_user()
userid = userinfo['id']
for items in results['items']:
if userid == items['owner']['id']:
sp.user_playlist_remove_all_occurrences_of_tracks(items['owner']['id'],items['id'],tracks)
print("removed from " + items['owner']['display_name'] + " s list " + items['name'])
example =oauth2.SpotifyOAuth( SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRET,SPOTIPY_REDIRECT_URI,scope=SCOPE,cache_path=r'C:\Users\rrako\AppData\Local\Programs\Python\Python38-32\Caches\example')
remove(example)
The error I get is
Traceback (most recent call last):
File "C:\Users\rrako\AppData\Local\Programs\Python\Python38-32\unfollowLists.py", line 212, in <module>
remove(blake)
File "C:\Users\rrako\AppData\Local\Programs\Python\Python38-32\unfollowLists.py", line 63, in remove
if sp_oauth.is_token_expired:
AttributeError: 'SpotifyOAuth' object has no attribute 'is_token_expired'
The version of spotipy I have is 2.4.4
Update your version of spotipy and the token should be refreshed automatically
pip3 install spotipy --upgrade
I am wondering why this code does not return for every json object the desired text?
# import
import json
from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream
# Authentication
ACCESS_TOKEN = 'hidden'
ACCESS_SECRET = 'hidden'
CONSUMER_KEY = 'hidden'
CONSUMER_SECRET = 'hidden'
oauth = OAuth(ACCESS_TOKEN, ACCESS_SECRET, CONSUMER_KEY, CONSUMER_SECRET)
# TWITTER SEARCH
twitter = Twitter(auth=oauth)
search_tweets = twitter.search.tweets(q='#google')
json_dump = json.dumps(search_tweets)
for line in json_dump:
print(json_dump['text'])
It gives me the following error:
Traceback (most recent call last):
File "twitter_streaming.py", line 46, in
print(json_dump['text'])
TypeError: string indices must be integers
This line:
json_dump = json.dumps(search_tweets)
converted the search_tweets variable into a string containing JSON in it. The issue is then with this code:
for line in json_dump:
print(json_dump['text'])
What this code does is iterates over the characters in json_dump (since json_dump is now a string), and then for each character, tries getting the ['text'] index from this character, which is obviously possible.
It seems like you need to convert search_tweets to a list of dictionaries instead, in order to make it work with your later code. However, without an example output of the search_tweets variable I can't say what exact code you need to do - if you could add the contents of the search_tweets variable that would be helpful.