跳转到主要内容

Twitter的API和命令行工具集(twitter.com)

项目描述

Python Twitter Tools

Tests Coverage Status

Python Twitter Tools是最小化的Twitter API,是Python的API,它为忙碌的人提供最喜欢的Web 2.0风格的状态更新器。

还包括一个Twitter命令行工具,可用于获取您朋友的消息并从您最喜欢的shell的安全性和可靠性中设置您自己的消息,以及一个可以向IRC频道宣布Twitter更新的IRC机器人。

更多信息

  • 安装 pip install twitter
  • 导入twitter包并运行help()
  • 运行twitter -h获取命令行工具帮助

twitter - 命令行工具

该命令行工具让您做一些很酷的事情

  • 查看您的消息、最近的回复和列表中的消息
  • 查看公共时间线
  • 关注和取消关注(离开)朋友
  • 为消息信息提供各种输出格式

总之:输入twitter,接收消息。

twitterbot - IRC机器人

该IRC机器人与一个Twitter账户关联(您的账户或为机器人创建的账户)。机器人宣布它关注的所有朋友的消息。可以通过IRC /msg命令使机器人关注或取消关注朋友。

twitter-log

twitter-log是一个简单的命令行工具,可以将给定用户的全部公开消息以简单的文本格式输出。它有助于获取您所有消息的完整离线备份。运行twitter-log并阅读说明。

twitter-archivertwitter-follow

twitter-archiver将记录任何用户自开始发布以来发布的所有消息。twitter-follow将打印用户的所有关注者(或用户关注的所有用户)的列表。

使用Twitter API类进行编程

TwitterTwitterStream类是构建您自己的启用Twitter的应用程序的关键。

Twitter

简约却功能齐全的Twitter API类。

通过访问此类的成员获取RESTful数据。结果是解码后的Python对象(列表和字典)。

Twitter API文档位于

https://developer.twitter.com/en/docs

最易访问的函数列表在

https://developer.twitter.com/en/docs/api-reference-index

示例

from twitter import *

t = Twitter(
    auth=OAuth(token, token_secret, consumer_key, consumer_secret))

# Get your "home" timeline
t.statuses.home_timeline()

# Get a particular friend's timeline
t.statuses.user_timeline(screen_name="boogheta")

# to pass in GET/POST parameters, such as `count`
t.statuses.home_timeline(count=5)

# to pass in the GET/POST parameter `id` you need to use `_id`
t.statuses.show(_id=1234567890)

# Update your status
t.statuses.update(
    status="Using @boogheta's sweet Python Twitter Tools.")

# Send a direct message
t.direct_messages.events.new(
    _json={
        "event": {
            "type": "message_create",
            "message_create": {
                "target": {
                    "recipient_id": t.users.show(screen_name="boogheta")["id"]},
                "message_data": {
                    "text": "I think yer swell!"}}}})

# Get the members of maxmunnecke's list "network analysis tools" (grab the list_id within the url) https://twitter.com/i/lists/1130857490764091392
t.lists.members(owner_screen_name="maxmunnecke", list_id="1130857490764091392")

# Favorite/like a status
status = t.statuses.home_timeline()[0]
if not status['favorited']:
    t.favorites.create(_id=status['id'])

# An *optional* `_timeout` parameter can also be used for API
# calls which take much more time than normal or twitter stops
# responding for some reason:
t.users.lookup(
    screen_name=','.join(A_LIST_OF_100_SCREEN_NAMES), _timeout=1)

# Overriding Method: GET/POST
# you should not need to use this method as this library properly
# detects whether GET or POST should be used, Nevertheless
# to force a particular method, use `_method`
t.statuses.oembed(_id=1234567890, _method='GET')

# Send images along with your tweets:
# - first just read images from the web or from files the regular way:
with open("example.png", "rb") as imagefile:
    imagedata = imagefile.read()
# - then upload medias one by one on Twitter's dedicated server
#   and collect each one's id:
t_upload = Twitter(domain='upload.twitter.com',
    auth=OAuth(token, token_secret, consumer_key, consumer_secret))
id_img1 = t_upload.media.upload(media=imagedata)["media_id_string"]
id_img2 = t_upload.media.upload(media=imagedata)["media_id_string"]
# - finally send your tweet with the list of media ids:
t.statuses.update(status="PTT ★", media_ids=",".join([id_img1, id_img2]))

# Or send a tweet with an image (or set a logo/banner similarly)
# using the old deprecated method that will probably disappear some day
params = {"media[]": imagedata, "status": "PTT ★"}
# Or for an image encoded as base64:
params = {"media[]": base64_image, "status": "PTT ★", "_base64": True}
t.statuses.update_with_media(**params)

# Attach text metadata to medias sent, using the upload.twitter.com route
# using the _json workaround to send json arguments as POST body
# (warning: to be done before attaching the media to a tweet)
t_upload.media.metadata.create(_json={
  "media_id": id_img1,
  "alt_text": { "text": "metadata generated via PTT!" }
})
# or with the shortcut arguments ("alt_text" and "text" work):
t_upload.media.metadata.create(media_id=id_img1, text="metadata generated via PTT!")

搜索Twitter

# Search for the latest tweets about #pycon
t.search.tweets(q="#pycon")

# Search for the latest tweets about #pycon, using [extended mode](https://developer.twitter.com/en/docs/tweets/tweet-updates)
t.search.tweets(q="#pycon", tweet_mode='extended')

达到API速率限制后的重试

只需使用带有参数retry=TrueTwitter实例创建,然后HTTP错误代码429502503504将导致重试最后一次请求。

如果retry是一个整数,它定义了最大重试次数。

使用返回的数据

Twitter API调用返回解码后的JSON。这被转换成一系列Python列表、字典、整数和字符串。例如

x = twitter.statuses.home_timeline()

# The first 'tweet' in the timeline
x[0]

# The screen name of the user who wrote the first 'tweet'
x[0]['user']['screen_name']

获取原始XML数据

如果您希望以XML格式获取Twitter数据,在实例化Twitter对象时传递format="xml"

twitter = Twitter(format="xml")

输出将不会被以任何方式解析。它将是一个原始的XML字符串。

TwitterStream

TwitterStream对象是Twitter流API的接口。这可以几乎与Twitter类相同的方式使用,除了调用方法的结果将是一个迭代器,它会产生从流中解码的对象。例如:

twitter_stream = TwitterStream(auth=OAuth(...))
iterator = twitter_stream.statuses.sample()

for tweet in iterator:
    ...do something with this tweet...

默认情况下,TwitterStream对象使用公共流。如果您想使用其他流式API之一,请手动指定URL。

迭代器将yield直到TCP连接中断。当连接中断时,迭代器产生{'hangup': True}(如果再次迭代,将引发StopIteration)。

类似地,如果流在90秒内没有产生心跳,迭代器产生{'hangup': True, 'heartbeat_timeout': True}(如果再次迭代,将引发StopIteration)。

timeout参数控制yield之间的最大时间。如果它不为零,则迭代器将在超时期间产生流数据或{'timeout': True}。如果你想在等待推文之间做其他事情,这将很有用。

block参数将流设置为完全非阻塞。在此模式下,迭代器始终立即产生。它返回流数据或None

请注意,timeout优先于此参数,因此也应将其设置为None以使用此模式,并且非阻塞可能会导致100%的CPU使用率。

Twitter Response对象

来自Twitter请求的响应。根据请求的格式表现得像列表或字符串,但它有一些其他有趣的属性。

headers允许你通过httplib.HTTPHeaders实例访问响应头。使用response.headers.get('h')来检索头。

身份验证

你可以用三种方式在Twitter上身份验证:NoAuth、OAuth或OAuth2(仅限应用)。获取这些类的help()来了解如何使用它们。

OAuth和OAuth2可能是最有用的。

使用OAuth

访问Twitter开发者页面并创建一个新的应用程序

https://dev.twitter.com/apps/new

这将为你提供一个CONSUMER_KEYCONSUMER_SECRET

当用户运行你的应用程序时,他们必须使用他们的Twitter账户来验证你的应用程序。需要进行几个HTTP调用到Twitter来完成此操作。请参阅twitter.oauth_dance模块以了解如何进行此操作。如果你正在制作命令行应用程序,可以直接使用oauth_dance()函数。

执行“oauth dance”将为你提供一个oauth令牌和oauth密钥,以使用户通过Twitter进行身份验证。你应该保存这些以便以后使用,这样用户就不必再次进行oauth dance。

read_token_filewrite_token_file是读取和写入OAuth tokensecret密钥值的实用方法。这些值以字符串形式存储在文件中。并不那么令人兴奋。

最后,你可以使用OAuth验证器来连接到Twitter。在代码中是这样的

from twitter import *

MY_TWITTER_CREDS = os.path.expanduser('~/.my_app_credentials')
if not os.path.exists(MY_TWITTER_CREDS):
    oauth_dance("My App Name", CONSUMER_KEY, CONSUMER_SECRET,
                MY_TWITTER_CREDS)

oauth_token, oauth_secret = read_token_file(MY_TWITTER_CREDS)

twitter = Twitter(auth=OAuth(
    oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET))

# Now work with Twitter
twitter.statuses.update(status='Hello, world!')

使用OAuth2

Twitter只支持某些API端点的应用仅流OAuth2。此OAuth2验证器目前只支持应用仅流。

要使用OAuth2进行身份验证,请访问Twitter开发者页面并创建一个新的应用程序

https://dev.twitter.com/apps/new

这将为你提供一个CONSUMER_KEYCONSUMER_SECRET

使用oauth2_dance函数交换CONSUMER_KEYCONSUMER_SECRET以获取访问令牌。

最后,你可以使用OAuth2验证器和你的访问令牌来连接到Twitter。在代码中是这样的:

twitter = Twitter(auth=OAuth2(bearer_token=BEARER_TOKEN))

# Now work with Twitter
twitter.search.tweets(q='keyword')

许可证

Python Twitter Tools在MIT许可证下发布。

项目详情


下载文件

下载适用于您平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源代码分布

twitter-1.19.6.tar.gz (53.1 kB 查看哈希值)

上传时间 源代码

构建分布

twitter-1.19.6-py2.py3-none-any.whl (50.3 kB 查看哈希值)

上传时间 Python 2 Python 3

由以下支持