Tweepy AttributeError: 'API' object has no attribute 'search' - python

I'm trying to get tweets using tweepy but I am running into this error:
AttributeError: 'API' object has no attribute 'search'
Code:
import tweepy
# Authentication
consumerKey = "Type your consumer key here"
consumerSecret = "Type your consumer secret here"
accessToken = "Type your accedd token here"
accessTokenSecret = "Type your access token secret here"
auth = tweepy.OAuthHandler(consumerKey, consumerSecret)
auth.set_access_token(accessToken, accessTokenSecret)
api = tweepy.API(auth)
#Sentiment Analysis
def percentage(part,whole):
return 100 * float(part)/float(whole)
keyword = input("Please enter keyword or hashtag to search: ")
noOfTweet = int(input ("Please enter how many tweets to analyze: "))
tweets = tweepy.Cursor(api.search, q=keyword).items(noOfTweet)
How can I fix this?

use api.search_tweets instead of api.search
tweepy v.4.0.0 has changed it..

Use:
tweets = tweepy.Cursor(api.search(q=keyword)).items(noOfTweet)

Related

There is a problem using "since" in Tweety function to extract Covaxin related hashtag tweets from the starting time of Covid'19

It is saying unexpected parameter :since when running the below code
import tweepy
# Enter your own credentials obtained
# from your developer account
consumer_key = "wwww"
consumer_secret = "xxxx"
access_key = "yyyy"
access_secret = "zzzz"
# The above keys are mentioned correctly in the programming code
# Twitter authentication
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
# Creating an API object
api = tweepy.API(auth)
hashtag_tweets = tweepy.Cursor(api.search_tweets, q="#Covaxin", tweet_mode='extended').items(5)
date_tweets = tweepy.Cursor(api.search_tweets, q="#Covaxin", since="2020-03-31", until="2022-01-09",tweet_mode='extended').items(5)
list = []
for tweet in date_tweets:
text = tweet._json["full_text"]
#print(text)
refined_tweet = {'text' : text,
'favorite_count' : tweet.favorite_count,
'retweet_count' : tweet.retweet_count,
'created_at' : tweet.created_at}
list.append(refined_tweet)
#print(list)
import pandas as pd
df = pd.DataFrame(list)
print(df)
df.to_csv('refined_tweets.csv')
It is saying unexpected parameter :since when running the code
I was trying to get the output for all tweets satisfying date query for the particular hashtag Covaxin from the starting of Covid days till now.

twitter app closes after opening(This App has violated Twitter Rules and policies)

I have a twitter app for many months
yesterday after adding "reply" feature for my app ,twitter limited my app
so i decided delete the app and creat a new one but when i set and replace api keys and passwords in my code ,my code still not work and closes after opening it in terminal
how can i solve this issue,i tried send my issue to twitter support but i have'n any helpful email
also for this issue i don't recive any email before that.
import tweepy
import time
consumer_key = "xxxxxxxxx"
consumer_secret = "xxxxxxxxx"
access_token = "xxxxxxxxxx"
access_token_secret = "xxxxxxxxxxx"
bearer_token = "xxxxxxxxxxx"
client_secret= "xxxxxxxxxxxxx"
client_id = "xxxxxxxxxxxxxxxx"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
class MyStreamListener(tweepy.StreamListener):
def on_status(self, tweet):
print(tweet.text)
try:
search = tweet.text
res = any(ele in search for ele in filter_words)
if res == True:
pass
else:
api.create_favorite(tweet.id)
if "#" in str(tweet.text):
if "مرز خسروی" in str(tweet.text):
status_id = tweet.user
username = "#" + status_id.screen_name
api.update_status(status = f"{username}مقدمتان گرامی باد،زیارتتان قبول",in_reply_to_status_id = tweet.id)
else:
pass
else:
api.retweet(tweet.id)
if "مرز خسروی" in str(tweet.text):
status_id = tweet.user
username = "#" + status_id.screen_name
api.update_status(status = f"{username}مقدمتان گرامی باد،زیارتتان قبول",in_reply_to_status_id = tweet.id)
else:
pass
except tweepy.TweepError as e:
print(e.reason)
myStreamListener = MyStreamListener()
myStream = tweepy.Stream(auth = api.auth, listener=myStreamListener)
keywords = ["کرمانشاه","kermanshah","فرامان","کرماشان","کرمانشاهی","برناج","هرسین","کنگاور","پاوه",
"روانسر","جوانرود","نوسود","نودشه","هجیج","ژاپه","هوره","سرپل ذهاب","قصرشیرین","ثلاث باباجانی",
"تنگه مرصاد","کرند غرب","تاریکه بازار","مرز خسروی","دوکل","پاساژ ارگ","طاق بستان","بیستون","کوزران",
"نان برنجی","نان خرمایی","خورشت خلال","نوبهار پلازا","بازی دراز","بزره دماغ","پارک کوهستان",
"بستنی نوبهار","آبشوران","دالاهو","تاق وه سان","سراب قنبر","کرناچی","قره سو","چقامیرزا",
"کوچه لکا","دنده کباب","ترخینه","نواله","کلانه","پراو","فرخشاد","مرز پرویزخان","چیامیرزا","چیاکو",
"تنگه کنشت","سنقر","لشگر ۸۱","ماهیدشت","نیوی","جشن انار","جوانشیر",
"پاتاق","میدان تاجگذاری","چهارراه شیرخورشید","شاباد","گرگگه","قسقوان","شهرام ناظری","حسین صفامنش",
"پوران درخشنده","رحیم معینی کرمانشاهی","کزاری","میر جلال الدین کزاری","باختران","پرتو کرمانشاهی",
"یداله بهزاد","آیت الله نجومی","تکیه معاون الملک","تکیه بیگلربیگی","هورامان","مسجد جامع شافعی",
"خانه خدیوی","کلیسای پنطی کاستی","پل چهر","تاریکه بازار","مسجد عمادالدوله","مسجد حاج شهباز خان",
"مسجد شهباز خان","آرامگاه ویس","طاق گرا","فرهاد تراش","شکارگاه خسروپرویز","معبد آناهیتا",
"مجسمه هرکول","سان رستم","مادها","دو اشکفت","گاکیه","گودین تپه","آش عباسعلی","سورانه","پاغازه",
"ونوشک","خورشت کنگر","قزانچی","سراب نیلوفر","سراب یاوری","کوه شاهو","رودخانه سیروان","مدلل","لیلیوم",
"کسگم","سراب صحنه","چهارراه نوبهار","گوران","قلخانی","عید یاران"]
filter_words = ["بازنشستگان","#تجمع_اعتراضی","احمق","بازداشت","بپاخیز","اعتراض"
,"تجمع","گوه","سگ","عوضی","بیشعور","الدنگ","الاع","جنایتکار","گاو","خر","پوفیوز","زندان","کیر","سگ",
"سیاسی","اعدام","مرگ","رژیم","آخوند","کوس","کون","جنده","مادر","حروم زاده","حرام زاده","سرنگونی",
"قیام","رجوی","شاهزاده","شورشی","کولبر","حقوق","بیشرف","ریت","سرکوبگر","شکنجه","معتاد","ایدز",
"دیکتاتور","ناموس","غارتگر","#اعتراضات_سراسری","سکس","خامنه ای","خمینی","تظاهرات","فراخوان",
"سلیمانی","جوانان","شعار","هموطن","آبادان#","خیزش","خیابان","قیام_نهایی#","بپاخاسته","مسعود رجوی",
"اسلام","آخوند","آبادان","بپاخواسته","قیام#","کومله","دموکرات","صیغه","پژاک","خاله","قتل","دستگیر",
"کور","بی سواد","حزب","دادگستری","دادستان","قوه قضاییه","تجمعات","فاشیست","کسشر","کصشر","دوزاری",
"فحش","سپاه","اظلاعات","بازجویی","مامور","اوین","جرم","سنگسار"]
myStream.filter(track=keywords,languages=["fa"])

How to specify more than one coordinates for geocode parameter of API.search in Tweepy

I want to search tweets based on more than one coordinates. So, I tried this but it doesn't return any results:
total = 0
for status in tweepy.Cursor(api.search, q='cricket', lang="en",
geocode="24.8607,67.0011,25mi OR 40.7128,74.0060,20mi"
).items(10):
total+=1
print(total)
It's been a while since #Tayyap Mazhar shared the post, but just in case, the code below will work as expected. Just remember, do not put comma while declaring geoc variable!
import tweepy
import pandas as pd
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)
auth.secure = True
api = tweepy.API(auth, wait_on_rate_limit=True,
wait_on_rate_limit_notify=True)
if (not api):
print ("Can’t Authenticate")
sys.exit(-1)
tweet_lst=[]
geoc=[('41.0,28.9499962,1km'),('41.1062629083,29.0264182277,1km'),('41.072833042,29.022833242,1km'),('41.05,28.91,1km')]
for geocode in geoc:
for tweet in tweepy.Cursor(api.search,geocode=geocode).items(1000):
tweetDate = tweet.created_at.date()
if(tweet.coordinates !=None):
tweet_lst.append([tweetDate,tweet.id,tweet.
coordinates['coordinates'][0],
tweet.coordinates['coordinates'][1],
tweet.user.screen_name,
tweet.user.name, tweet.text,
tweet.user._json['geo_enabled']])
tweet_df = pd.DataFrame(tweet_lst, columns=['tweet_dt', 'id', 'long','lat','username', 'name', 'tweet','geo'])```

I want to have all the tweets of a userid not the latest 200 from twitter in python

I am using the python-twitter module to get the tweets of my friends. I used the following code:
import twitter
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
OAUTH_TOKEN = ''
OAUTH_TOKEN_SECRET = ''
auth = twitter.oauth.OAuth(OAUTH_TOKEN, OAUTH_TOKEN_SECRET,
CONSUMER_KEY, CONSUMER_SECRET)
twitter_api = twitter.Twitter(auth=auth)
count = 0
for tweets in twitter_api.statuses.user_timeline(screen_name="thekiranbedi",count=500):
try:
print tweets['text']
count += 1
except Exception:
pass
print count
But as the result says, the value of count remains 200, so I am getting only the 200 recent tweets from the id with screen_name='thekiranbedi. But I want all the tweets. How can that be done?
That is a limitation of Twitter API, not of python-twitter module:
https://dev.twitter.com/rest/reference/get/statuses/user_timeline
count - Specifies the number of tweets to try and retrieve, up to a maximum of 200 per distinct request.
So as I understood you have to use 'since_id' and 'max_id' arguments to collect next portion of tweets.

Python tweepy find user of search

import time
import tweepy
from auth import consumer_key, consumer_secret, access_token, access_token_secret
string_to_search = 'new car ideas'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
past_status_ids = set()
while True:
tweets = api.search(q=string_to_search)
tweet_id_list = set([tweet.id for tweet in tweets])
new_tweet_ids = tweet_id_list - past_status_ids
past_status_ids = tweet_id_list | past_status_ids
for tweet_id in new_tweet_ids:
print "Retweeting " + str(tweet_id)
api.retweet(tweet_id)
#username = tweets.user.screen_name
#api.create_friendship(username)
#print "Followed " + str(username)
limits = api.rate_limit_status()
remain_search_limits = limits['resources']['search']['/search/tweets']['remaining']
print("Limit left is " + str(remain_search_limits))
print("")
time.sleep(150)
In a nutshell I am trying to find a string, then take that string retweet on my feed and follow that person.
My issue is how am I to find the Twitter ID to follow them via the search string?
I have been searching all around and can't find too many examples in Python tweepy for this.
If you want the User ID of the user who tweeted the tweet with status id tweet_id.
Use this
tweet = api.get_status(tweet_id)
user_id = tweet.user.id
# Now follow that user
api.create_friendship(user_id)

Categories