2012-09-17 51 views
2

我使用Twython(Python包裝Twitter的API,發現here。)使用Twython獲取推特ID?

目的:我試圖做一個簡單的機器人,搜索關鍵字,並回答與他們的關鍵字的鳴叫。

示例:發送搜索請求以搜索#stackoverflow,回覆其中含有「StackOverflow is best!」的#stackoverflow的推文。

問題:如果沒有推特ID(可在任何固定推文的網址中找到),不能回覆推文。這方面的一個例子是採取任何推文並將某人鏈接到它。鏈接末尾的數字是推特ID。

我試過了:沒有多少我可以試試。我希望這樣做盡可能簡單,沒有複雜的解決方法。我確信有一些方法可以做到這一點,而不必過分偏離我的路。我已經用盡了Google和Twython的文檔和Twitter的API文檔。 = /任何人

回答

5

推文只是python字典,它們的內容完全反映了Tweet resource。因此,每個鳴叫有一個id_str鍵:

print tweet['id_str'] 

您可以隨時打印數據結構,如果事情是不明確;我可以推薦pprint.pprint() function使嵌套蟒蛇結構額外可讀:

import pprint 

pprint.pprint(tweet) 

舉例會議:

>>> 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'