Arnav
Arnav

Reputation: 115

Getting a tweet's ID with Twython?

I'm using Twython (Python wrapper for Twitter API, found here.)

Objective: I'm trying to make a simple bot that searches for a keyword and replies to tweets with the keyword in them.

Example: Send search request to search for #stackoverflow, reply to tweets that have #stackoverflow in them with "StackOverflow is the best!"

Problem: Can't reply to a tweet without the tweet id (found in the url of any permalinked tweet). An example of this would be to take any tweet and link someone to it. The number at the end of the link is the tweet id.

What I've Tried: There's not much I can try. I want this to be as simple as possible, with no complex workarounds. I'm sure there's some way to do this without having to go too far out of my way. I've exhausted Google and Twython's documentation and Twitter's API documentation. =/ Anyone

Upvotes: 2

Views: 1658

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124488

Tweets are just python dictionaries, and their contents echo the Tweet resource exactly. Each tweet thus has an id_str key:

print tweet['id_str']

You can always print data structures if things are not clear; I can recommend the pprint.pprint() function to make nested python structures extra readable:

import pprint

pprint.pprint(tweet)

Example session:

>>> from twython import Twython
>>> t = Twython()
>>> res = t.search(q='python')
>>> res.keys()
[u'next_page', u'completed_in', u'max_id_str', u'since_id_str', u'refresh_url', u'results', u'since_id', u'results_per_page', u'query', u'max_id', u'page']
>>> from pprint import pprint
>>> pprint(res[u'results'][0])
{u'created_at': u'Mon, 17 Sep 2012 21:01:12 +0000',
 u'from_user': u'Me_Craay_GOOFY',
 u'from_user_id': 230100184,
 u'from_user_id_str': u'230100184',
 u'from_user_name': u'\u06deSuperFLY_PUER\u06de\u2122',
 u'geo': None,
 u'id': 247802407529115649,
 u'id_str': u'247802407529115649',
 u'iso_language_code': u'en',
 u'metadata': {u'result_type': u'recent'},
 u'profile_image_url': u'http://a0.twimg.com/profile_images/2617747450/345616051_normal.jpg',
 u'profile_image_url_https': u'https://si0.twimg.com/profile_images/2617747450/345616051_normal.jpg',
 u'source': u'<a href="http://globalgrind.com">UncleUber for Blackberry</a>',
 u'text': u'RT @Mr_Oyato: #ViolentPrayers May the python of breakthrough swallow you and your household today.',
 u'to_user': None,
 u'to_user_id': 0,
 u'to_user_id_str': u'0',
 u'to_user_name': None}
>>> res[u'results'][0]['id_str']
u'247802407529115649'

Upvotes: 5

Related Questions