Replying to users who tweet my account using Tweepy - python

I want to reply to users who tweet me a specific keyword (only when they tweet me) using Tweepy but I'm not sure how to go on about it, most of the examples I've seen use api.search which isn't convenient in this situation:
def tweetIt():
text = tweet.status
sn = tweet.user.screen_name
reply_to = tweet.in_reply_to_screen_name
if reply_to == "myuser":
if text == "#myuser keyword":
# reply to user with an image from a specific folder
tweetIt()
time.sleep(90) # to keep it running

Related

Stream a twitter list using Tweepy

I have a problem while I want to stream a specific public Twitter list using Tweepy. I can stream a specific user, but the filter follow doesn't work in this case. I have quite a long list of accounts I would like to stream to do further analysis, so I prepared a list with all of them on twitter. Does anyone know how to handle that?
My code is as follows:
import tweepy
import sys
class MyStreamListener(tweepy.StreamListener):
def on_status(self, status):
print(status.id_str)
# if "retweeted_status" attribute exists, flag this tweet as a retweet.
is_retweet = hasattr(status, "retweeted_status")
# check if text has been truncated
if hasattr(status,"extended_tweet"):
text = status.extended_tweet["full_text"]
else:
text = status.text
# check if this is a quote tweet.
is_quote = hasattr(status, "quoted_status")
quoted_text = ""
if is_quote:
# check if quoted tweet's text has been truncated before recording it
if hasattr(status.quoted_status,"extended_tweet"):
quoted_text = status.quoted_status.extended_tweet["full_text"]
else:
quoted_text = status.quoted_status.text
# remove characters that might cause problems with csv encoding
remove_characters = [",","\n"]
for c in remove_characters:
text.replace(c," ")
quoted_text.replace(c, " ")
with open("out.csv", "a", encoding='utf-8') as f:
f.write("%s,%s,%s,%s,%s,%s\n" % (status.created_at,status.user.screen_name,is_retweet,is_quote,text,quoted_text))
def on_error(self, status_code):
print("Encountered streaming error (", status_code, ")")
sys.exit()
consumer_key = "..."
consumer_secret = "..."
access_token = "..."
access_token_secret = "..."
auth = tweepy.OAuthHandler(consumer_key,consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
if (not api):
print("Authentication failed!")
sys.exit(-1)
myStreamListener = MyStreamListener()
myStream = tweepy.Stream(auth = api.auth, listener=myStreamListener,tweet_mode='extended')
with open("out.csv", "w", encoding='utf-8') as f:
f.write("date,user,is_retweet,is_quote,text,quoted_text\n")
myStream.filter(follow=['52286608'])
You should be able to use the follow parameter with a comma-separated list of user IDs. From the Twitter API documentation:
follow
A comma-separated list of user IDs, indicating the users whose Tweets should be delivered on the stream. Following protected users is not supported. For each user specified, the stream will contain:
- Tweets created by the user.
- Tweets which are retweeted by the user.
- Replies to any Tweet created by the user.
- Retweets of any Tweet created by the user.
- Manual replies, created without pressing a reply button (e.g. “#twitterapi I agree”).
The stream will not contain:
- Tweets mentioning the user (e.g. “Hello #twitterapi!”).
- Manual Retweets created without pressing a Retweet button (e.g. “RT #twitterapi The API is great”).
- Tweets by protected users.
You can follow up to 5000 IDs this way.
Note that the API you are connecting has been superseded by the v2 filtered stream API, but Tweepy does not currently support that.

How to tweet images, replies and retweet with tweepy?

I have a small script (not created by me) in python to tweet, in this way however I can only tweet text, there is a way to also tweet images, videos, retweets and replies. The script work with tweepy
Here is the script:
import tweepy
auth = tweepy.OAuthHandler("API KEY", "API SECRET")
auth.set_access_token("ACCESS TOKEN", "ACCESS TOKEN SECRET")
api = tweepy.API(auth)
tweet = input("What Would You Like To Tweet? ")
api.update_status(status =(tweet))
print ("Done!")
In order to tweet images, videos, retweets etc. indeed you need other functions of the api to call (otherwise how it could differ between different commands?)
You need the checkout the tweepy documentation to get comprehensive answers but:
Tweet with Media:
filename = "image_to_be_sent.png"
status = "Hello World!"
api.update_with_media(filename = filename, status = status)
Retweet:
api.retweet(id) # you should now the tweet id you want to retweet
Reply:
In order to reply you can use either api.update_status() or api.update_with_media() depending on if, you want to attach an image or video or not. You should only set the optional argument in_reply_to_status_id.
e.g:
filename = "image_to_be_sent.png"
status = "Hello World!"
api.update_with_media(filename = filename, status = status, in_reply_to_status_id = in_reply_to_status_id)

Obtain tweets with hashtags in them - Teepy

I have a basic program working using the Tweepy API. It essentially grabs tweets from a user and outputs it to a terminal. Ideally, I'd like this to be automated, so when the user tweets, the program will see it and display the tweet. But that's a question for another time.
What I'd like to do now, however, is grab the tweets with only a hashtag in it.
How do I go about this? I'm hoping it's a parameter I can add with inside the timeline function..?
Here is a snippet of the code I have at the moment:
import tweepy
import twitter_credentials
auth = tweepy.OAuthHandler(twitter_credentials.CONSUMER_KEY, twitter_credentials.CONSUMER_SECRET)
auth.set_access_token(twitter_credentials.ACCESS_TOKEN, twitter_credentials.ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)
stuff = api.user_timeline(screen_name = 'XXXXXX', count = 10, include_rts = False)
for status in stuff:
print(status.text)
For a simple use case you can use # in the search string, for example:
api = tweepy.API(auth,wait_on_rate_limit=True)
tweet in tweepy.Cursor(api.search,q="#",count=100).items():
print(tweet)
This will give you tweets which contain any hastags.

Get count of reply to a particular tweets

I am using the Python tweepy library.
I was successfully able to extract the 'liked' and 're-tweet' counts of a tweet using the below code:
# Get count of handles who are following you
def get_followers_count(handle):
user = api.get_user(handle)
return user.followers_count
# Get count of handles that you are following
def get_friends_count(handle):
user = api.get_user(handle)
return user.friends_count
# Get count of tweets for a handle
def get_status_count(handle):
user = api.get_user(handle)
return user.statuses_count
# Get count of tweets liked by user
def get_favourite_count(handle):
user = api.get_user(handle)
return user.favourits_count
However, I couldn't find a way to get the reply counts of a particular tweet.
Is it possible to get reply count of a tweet using tweepy or any other library like twython or even twitter4j?
The example code below shows how you could implement a solution to finding all replies for a single tweet. It utilizes the twitter search operator to:<account> and grabs all tweets that have replies to that account. By using since_id=tweet_id, the tweets returned from api.search are restricted to those created after the time the post was created. After these tweets are obtained, the in_reply_to_status_id attribute is used to check if the tweet captured is a reply to the tweet of interest.
auth = tweepy.OAuthHandler(API_KEY, API_SECRET_KEY)
api = tweepy.API(auth)
user = 'MollyNagle3'
tweet_id = 1368278040300650497
t = api.search(q=f'to:{user}', since_id=tweet_id,)
replies = 0
for i in range(len(t)):
if t[i].in_reply_to_status_id == tweet_id:
replies += 1
print(replies)
The limitation of this code is that is inefficient. It grabs more tweets than necessary. However, it seems that it is the best way to do this. Also, if you want to get replies of a very old tweet, you can implement the parameter max_id in api.search to limit the length of time you search over for replies.

Get usernames for a retweet?

How can I view the usernames for each retweet from my timeline using Python-Twitter? Here is what I have so far which brings back the timeline without the re-tweet usernames:
import twitter
api = twitter.Api(xxxxxx)
statuses = api.GetUserTimeline('username', include_rts=True)
for tweet in statuses:
print tweet
The method that I think you would use is GetTweets which requires a statusID, I am not sure how you would pass the status ID from the timeline call to the GetRetweets call?
Thanks in advance!
Try this:
import twitter
t = twitter.Api(...)
statuses = t.GetUserTimeline('username', include_rts=True)
for tweet in statuses:
retweets = t.GetRetweets(tweet.GetId())
users = [retweet.GetUser().GetScreenName() for retweet in retweets]
print tweet.GetId(), users
Hope that helps.
I wanted to add to #alecxe's answer but with a comment I can't paste much code. In my application I found it useful to check if the tweet had retweets prior to getting those retweets. This saves a little when it comes to the API quota. I've modified #alecxe's code to fit my needs:
import twitter, json
t = twitter.Api(...)
statuses = t.GetUserTimeline('username', include_rts=True)
for tweet in statuses:
json_tweet = json.loads(str(tweet))
rts = 0
try:
rts = json_tweet['retweet_count']
except:
rts = 0
if rts > 0:
retweets = t.GetRetweets(tweet.GetId())
users = [retweet.GetUser().GetScreenName() for retweet in retweets]
print tweet.GetId(), users
Or you can try this too.
import twitter
t = twitter.Api(...)
statuses = t.GetUserTimeline('username', include_rts=True)
for tweet in statuses:
retweets = t.GetRetweets(tweet.GetId())
users = [retweet.GetUser().GetScreenName() for retweet in retweets]
print tweet.GetId(), users
print tweet.GetRetweets()

Categories

Resources