📜  Python – Tweepy 中的 API.show_friendship()(1)

📅  最后修改于: 2023-12-03 15:19:04.275000             🧑  作者: Mango

Python Tweepy 中的 API.show_friendship()

当我们使用 Tweepy 库来访问 Twitter API 时,可以使用 API 类的 show_friendship() 方法来查看两个用户之间的互动情况。这个方法会返回两个用户的相关信息,包括他们是否是朋友,是否互相关注等等。

方法声明

API.show_friendship() 的方法声明如下:

API.show_friendship(source_id=None, source_screen_name=None, target_id=None, target_screen_name=None)

其中,source_id 和 source_screen_name 是要查询互动情况的第一个用户的 ID 和用户名,target_id 和 target_screen_name 则是要查询互动情况的第二个用户的 ID 和用户名。这四个参数都是可选的,但至少需要指定其中的一个。

返回值

API.show_friendship() 方法会返回一个包含两个用户互动情况的 Friendship 对象。友谊对象的结构如下:

{
    "relationship": {
        "source": {
            "id": 1234567890,
            "id_str": "1234567890",
            "screen_name": "user1",
            "following": true,
            "followed_by": true,
            "live_following": false,
            "following_received": null,
            "following_requested": null,
            "notifications_enabled": null,
            "can_dm": true,
            "blocking": false,
            "blocked_by": false,
            "muting": false,
            "want_retweets": null,
            "all_replies": null,
            "marked_spam": false
        },
        "target": {
            "id": 1234567891,
            "id_str": "1234567891",
            "screen_name": "user2",
            "following": true,
            "followed_by": false,
            "following_received": null,
            "following_requested": null,
            "notifications_enabled": null,
            "can_dm": true,
            "blocking": false,
            "blocked_by": false,
            "muting": false
        }
    }
}

其中,source 和 target 分别代表两个用户。在这个 Friendship 对象中,我们可以看到这两个用户的互相关注情况、是否互为朋友等等。

使用示例

这里是一个使用 API.show_friendship() 方法的示例代码:

import tweepy

# 设置 Twitter API 密钥
consumer_key = 'your_consumer_key'
consumer_secret = 'your_consumer_secret'
access_token = 'your_access_token'
access_token_secret = 'your_access_token_secret'

# 获得 Tweepy 的 API 对象
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

# 查看@BarackObama 和 @realDonaldTrump 之间的互动情况
friendship = api.show_friendship(source_screen_name='BarackObama', target_screen_name='realDonaldTrump')

# 输出 friendship 对象
print(friendship)

在这个示例代码中,我们使用了 Tweepy 的 OAuth 认证方式和 API 对象来获得一个 Friendship 对象,并最终将其输出到控制台上。

以上就是 Tweepy API 中的 show_friendship() 方法的介绍和使用示例。