Twitter API throws error : 'API' object has no attribute 'search' - python

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 ?

Related

tweepy API.user_timeline returns empty list

I am building a Telegram bot that will forward Elon Musk's latest Twitter.
Even if it works without any problems, occasionly index error is occured.
"api_user_timeline" returns empty list.
To find out the problem, print() was added and driven, but an error occurred in the second iteration of while().
import telepot
import os
import tweepy
import time
import requests
token = '' #telepot bot token
user_list=[''] #user id
bot = telepot.Bot(token)
consumer_key = "" # Twitter API Key
consumer_secret = "" # Twitter API Secret Key
access_token = "" # Twitter Access Key
access_token_secret = "" # Twitter Access Secret Key
auth = tweepy.OAuthHandler(consumer_key,consumer_secret)
auth.set_access_token(access_token,access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True)
user_id='44196397'
status = api.user_timeline(user_id=user_id,exclude_replies=True,include_rts=False, tweet_mode = 'extended')
print("[status] "+status_present[0].full_text)
while True:
time.sleep(30)
status_present = api.user_timeline(user_id=user_id,exclude_replies=True, include_rts=False, tweet_mode = 'extended')
print("[status_present] "+status_present[0].full_text)
if status[0].full_text!=status_present[0].full_text:
for i in user_list:
bot.sendMessage(i,status_present[0].full_text)
status=status_present
here's output print() message & error message below
I ran it in jupyter notebook.
[status] Given that Twitter serves as the de facto public town square, failing to adhere to free speech principles fundamentally undermines democracy.
[status_present] Given that Twitter serves as the de facto public town square, failing to adhere to free speech principles fundamentally undermines democracy.
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9460/139022525.py in <module>
56 time.sleep(30)
57 status_present = api.user_timeline(user_id=user_id,exclude_replies=True, include_rts=False, tweet_mode = 'extended')
---> 58 print("[status_present] "+status_present[0].full_text)
59 if status[0].full_text!=status_present[0].full_text:
60 for i in user_list:
IndexError: list index out of range
I want to know why this phenomenon occurs. I would appreciate it if you could let me know if there is anything to fix in the code. Thanks

Tweepy error when trying to gather Tweets

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.

Twitter module has no object 'trends'

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.

Twitter API returned a 401 (Unauthorized) when trying to get users's friends on twitter

I'm using the following code which for a while worked like charm, but recently in 9 of the 10 attempts I'm getting error from twitter api
from twython import Twython, TwythonError
from pymongo import Connection
import pika, time
connection = Connection("host")
connection.admin.authenticate('admin', 'passwords')
db = connection['tweets']
consumer_key="key"
consumer_secret="secret"
access_token="token"
access_token_secret="secret_token"
t = Twython(app_key=consumer_key,
app_secret=consumer_secret,
oauth_token=access_token,
oauth_token_secret=access_token_secret
)
Q ='download_friends'
r_connection = pika.BlockingConnection(pika.ConnectionParameters(
'host'))
channel = r_connection.channel()
channel.queue_declare(queue= Q,
arguments={'x-message-ttl':600000})
while 1:
method_frame, header_frame, id = channel.basic_get(Q)
if db.friends.find_one({"_id": id}) != None:
print "Panic, user already exists"
continue
try:
r = t.get_friends_list(user_id = id)
except Exception as ex:
print ex, id
else:
print id
r['_id'] = id
r['time'] = time.time()
db.friends.save(r)
time.sleep(121)
Twitter API returned a 401 (Unauthorized), An error occurred
processing your request.
Here is a stacktrace
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/twython/endpoints.py", line 290, in get_friends_list
return self.get('friends/list', params=params)
File "/usr/local/lib/python2.7/dist-packages/twython/api.py", line 230, in get
return self.request(endpoint, params=params, version=version)
File "/usr/local/lib/python2.7/dist-packages/twython/api.py", line 224, in request
content = self._request(url, method=method, params=params, api_call=url)
File "/usr/local/lib/python2.7/dist-packages/twython/api.py", line 194, in _request
retry_after=response.headers.get('retry-after'))
twython.exceptions.TwythonAuthError: Twitter API returned a 401 (Unauthorized), An error occurred processing your request.
I the remaining 1 attempt I'm actually getting a user's friends.
I've googled a bit and corrected time on the machine (as they say one of the most common causes of this error), yet error still persists.
Also there is minimal not working example:
twitter = Twython('API key', 'API secret', oauth_version=2)
ACCESS_TOKEN = twitter.obtain_access_token()
print ACCESS_TOKEN
t = Twython('API key', access_token=ACCESS_TOKEN)
r = t.get_friends_list(user_id = 'id')
It is able to get ACCESS_TOKEN but nothing more.
Could it be, because user_id has private profile and you just can't access it's friends?
I also thought, it's problem in rate limit, but according to twitter api it returns 429 error, if limit reached
UPDATE:
I haven't tested, but found similar situation: https://dev.twitter.com/discussions/4389

python-twitter: get_oauth( ) giving unexpected error

I am new to python and I have been making codes to scrap twitter data on python.
Below are my codes:
import csv
import json
import twitter_oauth
import sys
sys.path.append("/Users/jdschnieder/Documents/Modules")
print sys.path
#gain authorization to twitter
consumer_key = 'xdbX1g21REs0MPxofJPcFw'
consumer_secret = 'c9S9YI6G3GIdjkg67ecBaCXSJDlGw4sybTv1ccnkrA'
get_oauth_obj = twitter_oauth.GetOauth(consumer_key, consumer_secret)
get_oauth_obj.get_oauth()
the error occurs at the line:
get_oauth_obj.get_oauth()
the error message is as follows:
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-36-5d124f99deb6> in <module>()
--> 1 get_oauth_obj.get_oauth()
/Users/jdschnieder/anaconda/python.app/Contents/lib/python2.7/site-packages/
twitter_oauth-0.2.0-py2.7.egg/twitter_oauth.pyc in get_oauth(self)
95 resp, content = client.request(_REQUEST_TOKEN_URL, "GET")
96 if resp['status'] != '200':
-> 97 raise Exception('Invalid response %s' % resp['status'])
98
99 request_token = dict(self._parse_qsl(content))
Exception: Invalid response 401
why is this error occurring, and what are possible solutions to the error?
thank you,
It looks like the Twitter library you're using does not support Twitter API v1.1. Instead of twitter_oauth, use one of the Python libraries listed here. For example, you can use Tweepy, following the documentation for OAuth Authentication

Categories

Resources