How to tweet images, replies and retweet with tweepy? - python

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)

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.

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.

Using tweepy to get a keyword from a specific user

I'm trying to create a listener to a very specific twitter account (mine), so I can do some automation, if I tweet something with a "special" code at the end (could be a character like "…") it will trigger an action, like adding the previous characters to a database.
So, I used Tweepy and I'm able to create the listener, filter keywords and so, but it will filter keywords from all the Tweetverse. This is my code:
import tweepy
cfg = {
"consumer_key" : "...",
"consumer_secret" : "...",
"access_token" : "...",
"access_token_secret" : "..."
}
auth = tweepy.OAuthHandler(cfg['consumer_key'], cfg['consumer_secret'])
auth.set_access_token(cfg['access_token'], cfg['access_token_secret'])
api = tweepy.API(auth)
class MyStreamListener(tweepy.StreamListener):
def on_status(self, status):
print(status.text)
return True
def on_error(self, status):
print('error ',status)
return False
myStreamListener = MyStreamListener()
myStream = tweepy.Stream(auth=auth, listener=myStreamListener)
myStream.filter(track=['…'])
It will filter all the messages containing a "…" no matter who wrote it, so I added to the last line the parameter follow='' like:
myStream.filter(follow='myTwitterName', track=['…'])
It always gives me a 406 error, if I use myStream.userstream('myTwitterName') it will give me, not just the Tweets I write, but also my whole timeline.
So, what am I doing wrong?
EDIT
I just find my first error. I was using user's screen name, not Twitter ID. Now I got rid of the 406 error, but still doesn't work. I placed the Twitter ID in the follow parameter, but does absolutely nothing. I tried both, with my account and with an account that is too "live", like CNN (ID = 759251), I see new tweets coming in my browser, but nothing on the listener.
If you're interested on knowing your own Twitter ID, I used this service: http://gettwitterid.com/
OK, solved. It was working from the very beggining, I made two mistakes:
To solve the 406 error all it has to be done, is to use Twitter id instead of Twitter name.
The listener was apparently doing nothing, because I was sending "big" tweets, that is, tweets longer than 140 chars. In this case, you shouldn't use status.text, but status.extended_tweet['full_text']
You must check for the existance of the extended_tweet, if it is not in the status received, then you should use the text

Replying to users who tweet my account using Tweepy

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

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