Reply to Tweet with Tweepy - Python - python

I can't seem to get tweepy to work with replying to a specific tweet:
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
### at this point I've grabbed the tweet and loaded it to JSON...
tweetId = tweet['results'][0]['id']
api.update_status('My status update',tweetId)
The api says it takes optional parameters and in_reply_to_status_id is the first, but it seems to be ignoring it altogether. This script will post an updated status, but it does not link it as a reply to the tweetId that I'm passing.
API for reference: http://code.google.com/p/tweepy/wiki/APIReference#update_status
Anyone have any ideas? I feel like I'm missing something simple here...
Thanks in advance.

Just posting the solution so no someone else suffers the way I did.
Twitter updated the API and added an option named auto_populate_reply_metadata
All you need to do is set that to true, and the leave the rest as should be. Here is a sample:
api.update_status(status = 'your reply', in_reply_to_status_id = tweetid , auto_populate_reply_metadata=True)
Also, the status_id is the long set of digits at the end of the tweet URL. Good Luck!

I ran into the same problem, but luckily I found the solution. You just need to include the user's screen_name in the tweet:
api.update_status('#<username> My status update', tweetId)

You can also do
api.update_status("my update", in_reply_to_status_id = tweetid)

Well then, it was something simple. I had to specify who the tweet was directed towards using the # notation.
api.update_status('My status update #whoIReplyTo',tweetId)

I discovered that I had to include the tweet's ID string (rather than actual ID number) when specifying the tweet that I was replying to
api.update_status('#whoIReplyTo my reply tweet',tweetIdString)

This seems to be a bug in Tweepy – even if you make a call to api.update_status with the correct parameters set,
api.update_status(status=your_status, in_reply_to_status=tweet_to_reply_to.id)
the tweet will not be a reply. In order to get a reply, you need to mention the user you want to reply to AND specify the correct in_reply_to_status id.
reply_status = "#%s %s" % (username_to_reply_to, your_status)
api.update_status(status=reply_status, in_reply_to_status=tweet_to_reply_to.id)
Keep in mind though – Tweepy and Twitter's servers still enforce a maximum number of 140 characters, so make sure you check that
len(reply_status) <= 140
Again, I think this is a bug because on the Twitter app, you can reply without embedding the username of the person to whom you're replying.

reply_status = "#%s %s" % (tweet.user.screen_name, "type your reply here")
api.update_status(status=reply_status, in_reply_to_status_id=tweet.id)
this is the last correct form, I just test it a few minutes ago

Related

How do i reply to a certain tweet using Tweepy?

I am trying to reply to create a code to reply to simply reply to a (given) tweet, i only know that api.update_status tweets but not how to reply to one, i did some researches but all are outdated and "in_reply_to_status_id" doesn't seem to work anymore
api = tweepy.API(auth)
api.update_status
In order to reply to a tweet using the Twitter API v2, you need to use the in_reply_to_tweet_id. This works as follows.
import tweepy
client = tweepy.Client(consumer_key='YOUR_CONSUMER_KEY',
consumer_secret='YOUR_CONSUMER_SECRET',
access_token='YOUR_ACCESS_TOKEN',
access_token_secret='YOUR_ACCESS_TOKEN_SECRET')
client.create_tweet(text='Some reply', in_reply_to_tweet_id=42)
This is described in the documentation here.
in_reply_to_tweet_id (Optional[Union[int, str]]) – Tweet ID of the Tweet being replied to.
Edit: If you are using API v1.1, then you need to include #username in the status text, where username is the author of the referenced Tweet. This is described here.
Hence, a working example looks as follows.
comment = '#usernameOfTweet Test Reply'
res = api.update_status(comment, in_reply_to_status_id=42)
It is also possible to use auto_populate_reply_metadata=True as discussed in this Github issue.
comment = 'Test reply'
api.update_status(comment, in_reply_to_status_id=42, auto_populate_reply_metadata=True)
This is also described in the documentation.
auto_populate_reply_metadata – If set to true and used with in_reply_to_status_id, leading #mentions will be looked up from the original Tweet, and added to the new Tweet from there.

Python Tweepy 280 Character Statuses

I'm trying to scrape the full 280 character tweets off of twitter but I can't get them to not trail off with '...' after 140 chars. Here's my code:
import tweepy
import datetime
auth = tweepy.OAuthHandler("", "")
auth.set_access_token("", "")
api = tweepy.API(auth)
end_date = datetime.datetime.utcnow() - datetime.timedelta(days=0)
for status in api.user_timeline(targer_user):
print(status.text)
if status.created_at > end_date:
break
I've read that adding text_mode=extendedto the function will solve this, but it's making no difference for me. If I use another suggested argument tweet_mode='extended', text is no longer an attribute of status.
How can I fix this?
It seems you need to use full_text now to get the 280 char tweet. Try something along the lines of:
print(status.extended_tweet['full_text'])
The tweet_mode='extended' can be used in user_timeline if you want, in which case you would just use below:
print(status.full_text)
This looks a bit nicer to me.
It might also be worth pointing out that - from what I've read - this might not work for a retweet (Twitter streaming API not return full tweets) but there are separate bits of the api you can use for that, so be sure to check before you print.
Twitter docs, in case you want a closer look at the update: https://developer.twitter.com/en/docs/tweets/tweet-updates.html

Gmail API: Python Email Dict appears to be Missing Keys

I'm experiencing a strange issue that seems to be inconsistent with google's gmail API:
If you look here, you can see that gmail's representation of an email has keys "snippet" and "id", among others. Here's some code that I use to generate the complete list of all my emails:
response = service.users().messages().list(userId='me').execute()
messageList = []
messageList.extend(response['messages'])
while 'nextPageToken' in response:
pagetoken = response['nextPageToken']
response = service.users().messages().list(userId='me', pageToken=pagetoken).execute()
messageList.extend(response['messages'])
for message in messageList:
if 'snippet' in message:
print(message['snippet'])
else:
print("FALSE")
The code works!... Except for the fact that I get output "FALSE" for every single one of the emails. 'snippet' doesn't exist! However, if I run the same code with "id" instead of snippet, I get a whole bunch of ids!
I decided to just print out the 'message' objects/dicts themselves, and each one only had an "id" and a "threadId", even though the API claims there should be more in the object... What gives?
Thanks for your help!
As #jedwards said in his comment, just because a message 'can' contain all of the fields specified in documentation, doesn't mean it will. 'list' provides the bare minimum amount of information for each message, because it provides a lot of messages and wants to be as lazy as possible. For individual messages that I want to know more about, I'd then use 'messages.get' with the id that I got from 'list'.
Running get for each email in your inbox seems very expensive, but to my knowledge there's no way to run a batch 'get' command.

Twitter timeline in Python, but only getting 20ish results?

I'm a nub when it comes to python. I literally just started today and have little understanding of programming. I have managed to make the following code work:
from twitter import *
config = {}
execfile("config.py", config)
twitter = Twitter(
auth = OAuth(config["access_key"], config["access_secret"],
config["consumer_key"], config["consumer_secret"]))
user = "skiftetse"
results = twitter.statuses.user_timeline(screen_name = user)
for status in results:
print "(%s) %s" % (status["created_at"], status["text"].encode("ascii",
"ignore"))
The problem is that it's only printing 20 results. The twitter page i'd like to get data from has 22k posts, so something is wrong with the last line of code.
screenshot
I would really appreciate help with this! I'm doing this for a research sentiment analysis, so I need several 100's to analyze. Beyond that it'd be great if retweets and information about how many people re tweeted their posts were included. I need to get better at all this, but right now I just need to meet that deadline at the end of the month.
You need to understand how the Twitter API works. Specifically, the user_timeline documentation.
By default, a request will only return 20 Tweets. If you want more, you will need to set the count parameter to, say, 50.
e.g.
results = twitter.statuses.user_timeline(screen_name = user, count = 50)
Note, count:
Specifies the number of tweets to try and retrieve, up to a maximum of 200 per distinct request.
In addition, the API will only let you retrieve the most recent 3,200 Tweets.

how do i pull geotaged tweets in python

I had a python file that I used to pull geotagged tweets from twitter, but now it requires OAuth. I'm trying to work with 1.1 but I'm not sure what to do next. My code below is from the Twitter API documentation, with some minor changes since the documentation is wrong (force_auth_header=True was removed and set body="").
I searched around, but either the posts are outdated or confusing. I think I'm close, but not sure where to go next. Ultimately I'd like to use something like search_url3, but I know that format is incorrect because I can tell it is getting a 401 error.
In the mean time, if I can get the results in a json format, that'd be great.
I used to use something like this:
search = urllib.urlopen("http://search.twitter.com/search.json?q=&rpp=100&geocode=39.95256,-75.164,2mi)
for result in j["results"]:
...
My current code:
import oauth2 as oauth
consumer_key="123"
consumer_secret="345"
Access_token="567"
Access_token_secret="890"
def oauth_req(url, key, secret, http_method="GET",http_headers=None):
consumer = oauth.Consumer(key, secret)
token = oauth.Token(Access_token,Access_token_secret)
client = oauth.Client(consumer, token)
resp, content = client.request(url,method=http_method,body="",
headers=http_headers)
print resp
return content
search_url2="https://api.twitter.com/1.1/search/tweets.json?q=&geocode=39.95256,-75.164,2mi"
search_url3="https://api.twitter.com/1.1/search/tweets.json?q=%23freebandnames&since_id=24012619984051000&max_id=250126199840518145&result_type=mixed&count=4"
home_timeline = oauth_req(search_url3, consumer_key, consumer_secret)
Basically, unless this is somekind of homework, you are doing it wrong. there are terrific (and not so terrific) python-twitter libs and wrappers, unless building one is your core mission than use one of them:
python-twitter
python-twitter-tools
twython
tweepy
Etc..

Categories

Resources