跳转至

User 模块 API 文档

User 模块提供完整的 Twitter 用户资料管理功能,支持查询用户信息、编辑个人资料、更换头像和背景图等操作。

目录

模块概述

User 模块支持两种使用方式:

方式 1: 通过 Twitter 主入口访问(推荐)

from x_api_rs import Twitter

client = Twitter(cookies)
result = await client.user.get_profile("elonmusk")

方式 2: 独立创建 UserClient

from x_api_rs.user import UserClient

user_client = UserClient(cookies, proxy_url="http://proxy:8080")
result = await user_client.get_profile("elonmusk")

功能列表

功能 方法 说明
查询用户资料 get_profile() 通过用户名查询用户信息
通过 ID 查询 get_profile_by_id() 通过用户 ID 查询用户信息
获取账号详情 get_about_account() 获取账号验证状态等详细信息
编辑资料 edit_profile() 更新当前用户的资料信息
更换头像 change_profile_image() 更换用户头像
更换背景图 change_background_image() 更换用户背景图(Banner)

UserClient 类

构造函数

UserClient(
    cookies: str,
    proxy_url: str | None = None
)

创建新的 User 客户端实例。

参数:

  • cookies (str): Twitter 账号的 cookies 字符串
  • proxy_url (str | None): 可选的代理服务器 URL

返回: UserClient 实例

异常: RuntimeError - 初始化失败

示例:

# 基础使用
client = UserClient(cookies)

# 使用代理
client = UserClient(cookies, proxy_url="http://proxy:8080")

get_profile

async def get_profile(
    screen_name: str
) -> UserResp

通过用户名查询用户资料。

参数:

  • screen_name (str): Twitter 用户名(不含 @ 符号)

返回: UserResp 对象,包含用户详细信息

异常: RuntimeError - 查询失败

示例:

result = await client.user.get_profile("elonmusk")

if result.success:
    print(f"用户名: @{result.screen_name}")
    print(f"显示名: {result.name}")
    print(f"简介: {result.description}")
    print(f"粉丝数: {result.followers_count}")
    print(f"关注数: {result.following_count}")
else:
    print(f"查询失败: {result.error_msg}")

get_profile_by_id

async def get_profile_by_id(
    rest_id: str
) -> UserResp

通过用户 ID 查询用户资料。

参数:

  • rest_id (str): Twitter 用户 REST ID

返回: UserResp 对象

异常: RuntimeError - 查询失败

示例:

# Elon Musk 的用户 ID
result = await client.user.get_profile_by_id("44196397")

if result.success:
    print(f"用户: @{result.screen_name} ({result.name})")

get_about_account

async def get_about_account(
    screen_name: str
) -> AboutAccountResult

获取账号详细信息,包括验证状态、账号来源地等。

参数:

  • screen_name (str): Twitter 用户名(不含 @ 符号)

返回: AboutAccountResult 对象

异常: RuntimeError - 查询失败

示例:

result = await client.user.get_about_account("elonmusk")

if result.success:
    print(f"用户 ID: {result.rest_id}")
    print(f"蓝V认证: {result.is_blue_verified}")
    print(f"身份认证: {result.is_identity_verified}")
    print(f"账号来源地: {result.account_based_in}")
    print(f"用户名修改次数: {result.username_change_count}")

edit_profile

async def edit_profile(
    params: EditUserParams
) -> EditUserResult

编辑当前认证用户的资料信息。

参数:

  • params (EditUserParams): 编辑参数对象,包含要更新的字段

返回: EditUserResult 对象

异常: RuntimeError - 编辑失败

示例:

from x_api_rs.user import EditUserParams

# 创建编辑参数(只需提供要修改的字段)
params = EditUserParams(
    name="New Display Name",
    description="Updated bio text",
    location="San Francisco, CA",
    url="https://example.com"
)

result = await client.user.edit_profile(params)

if result.success:
    print(f"资料已更新!")
    print(f"新名称: {result.name}")
    print(f"新简介: {result.description}")
else:
    print(f"更新失败: {result.error_msg}")

change_profile_image

async def change_profile_image(
    media_id: str
) -> ChangeProfileImageResult

更换用户头像。需要先上传图片获取 media_id

参数:

  • media_id (str): 已上传图片的 media_id(来自 upload.image 返回的 media_id_string

返回: ChangeProfileImageResult 对象

异常: RuntimeError - 更换失败

示例:

# 1. 上传头像图片
with open("avatar.jpg", "rb") as f:
    image_bytes = f.read()

upload_result = await client.upload.image(image_bytes, "banner_image")

if upload_result.success:
    # 2. 更换头像
    result = await client.user.change_profile_image(upload_result.media_id_string)

    if result.success:
        print(f"头像已更换!")
        print(f"新头像 URL: {result.profile_image_url}")
    else:
        print(f"更换失败: {result.error_msg}")

change_background_image

async def change_background_image(
    media_id: str
) -> ChangeBannerResult

更换用户背景图(Banner)。需要先上传图片获取 media_id

参数:

  • media_id (str): 已上传图片的 media_id(来自 upload.image 返回的 media_id_string

返回: ChangeBannerResult 对象

异常: RuntimeError - 更换失败

示例:

# 1. 上传背景图
with open("banner.jpg", "rb") as f:
    image_bytes = f.read()

upload_result = await client.upload.image(image_bytes, "banner_image")

if upload_result.success:
    # 2. 更换背景图
    result = await client.user.change_background_image(upload_result.media_id_string)

    if result.success:
        print(f"背景图已更换!")
        print(f"新背景图 URL: {result.banner_url}")
    else:
        print(f"更换失败: {result.error_msg}")

类型定义

UserResp

用户资料响应。

属性:

  • success (bool): 请求是否成功
  • user_id (str | None): 用户 ID
  • screen_name (str | None): 用户名(不含 @)
  • name (str | None): 显示名称
  • description (str | None): 个人简介
  • location (str | None): 位置
  • url (str | None): 个人网站 URL
  • profile_image_url (str | None): 头像 URL
  • background_image (str | None): 背景图 URL
  • following_count (int | None): 关注数
  • followers_count (int | None): 粉丝数
  • following (bool): 是否正在关注该用户
  • protected (bool | None): 是否为私密账号
  • profile_interstitial_type (str | None): 资料插页类型
  • error_msg (str): 错误消息
  • http_status (int): HTTP 状态码

示例:

result = await client.user.get_profile("elonmusk")

if result.success:
    print(f"User ID: {result.user_id}")
    print(f"Screen Name: @{result.screen_name}")
    print(f"Display Name: {result.name}")
    print(f"Bio: {result.description}")
    print(f"Location: {result.location}")
    print(f"Website: {result.url}")
    print(f"Followers: {result.followers_count}")
    print(f"Following: {result.following_count}")
    print(f"Is Private: {result.protected}")
    print(f"Am I following: {result.following}")

AboutAccountResult

账号详细信息结果。

属性:

  • success (bool): 请求是否成功
  • rest_id (str | None): 用户 REST ID
  • account_based_in (str | None): 账号来源地
  • location_accurate (bool | None): 位置是否准确
  • learn_more_url (str | None): 了解更多链接
  • source (str | None): 来源信息
  • username_change_count (str | None): 用户名修改次数
  • username_last_changed_at_msec (str | None): 最后修改用户名的时间戳
  • is_identity_verified (bool | None): 是否身份认证
  • is_blue_verified (bool | None): 是否蓝V认证
  • error_msg (str): 错误消息
  • http_status (int): HTTP 状态码

示例:

result = await client.user.get_about_account("elonmusk")

if result.success:
    print(f"蓝V: {result.is_blue_verified}")
    print(f"身份认证: {result.is_identity_verified}")
    print(f"账号来源: {result.account_based_in}")

EditUserParams

编辑用户资料参数。

属性:

  • name (str | None): 显示名称
  • description (str | None): 个人简介
  • location (str | None): 位置
  • url (str | None): 个人网站 URL

示例:

from x_api_rs.user import EditUserParams

# 只更新部分字段
params = EditUserParams(name="New Name")

# 更新多个字段
params = EditUserParams(
    name="New Name",
    description="New bio",
    location="New York",
    url="https://example.com"
)

EditUserResult

编辑用户资料结果。

属性:

  • success (bool): 请求是否成功
  • name (str | None): 更新后的显示名称
  • description (str | None): 更新后的个人简介
  • location (str | None): 更新后的位置
  • url (str | None): 更新后的网站 URL
  • error_msg (str): 错误消息
  • http_status (int): HTTP 状态码

ChangeProfileImageResult

更换头像结果。

属性:

  • success (bool): 请求是否成功
  • profile_image_url (str | None): 新头像 URL
  • error_msg (str): 错误消息
  • http_status (int): HTTP 状态码

ChangeBannerResult

更换背景图结果。

属性:

  • success (bool): 请求是否成功
  • banner_url (str | None): 新背景图 URL
  • error_msg (str): 错误消息
  • http_status (int): HTTP 状态码

使用示例

查询用户资料

import asyncio
from x_api_rs import Twitter

async def main():
    client = Twitter(cookies)

    # 通过用户名查询
    result = await client.user.get_profile("elonmusk")

    if result.success:
        print(f"👤 @{result.screen_name}")
        print(f"📛 {result.name}")
        print(f"📝 {result.description}")
        print(f"📍 {result.location}")
        print(f"👥 粉丝: {result.followers_count:,}")
        print(f"👁️ 关注: {result.following_count:,}")

asyncio.run(main())

批量查询用户

async def batch_get_profiles():
    client = Twitter(cookies)

    usernames = ["elonmusk", "BillGates", "satloading"]
    users = []

    for username in usernames:
        result = await client.user.get_profile(username)
        if result.success:
            users.append({
                "username": result.screen_name,
                "name": result.name,
                "followers": result.followers_count
            })
        await asyncio.sleep(0.5)  # 避免限流

    # 按粉丝数排序
    users.sort(key=lambda x: x["followers"] or 0, reverse=True)

    for user in users:
        print(f"@{user['username']}: {user['followers']:,} followers")

编辑个人资料

async def update_my_profile():
    client = Twitter(cookies)

    from x_api_rs.user import EditUserParams

    # 更新资料
    params = EditUserParams(
        name="Python Developer 🐍",
        description="Building cool stuff with Python and Rust",
        location="San Francisco, CA"
    )

    result = await client.user.edit_profile(params)

    if result.success:
        print("资料更新成功!")
        print(f"新名称: {result.name}")
        print(f"新简介: {result.description}")
    else:
        print(f"更新失败: {result.error_msg}")

更换头像和背景图

async def update_profile_images():
    client = Twitter(cookies)

    # 更换头像
    with open("avatar.jpg", "rb") as f:
        avatar_bytes = f.read()

    avatar_upload = await client.upload.image(avatar_bytes, "banner_image")
    if avatar_upload.success:
        avatar_result = await client.user.change_profile_image(
            avatar_upload.media_id_string
        )
        if avatar_result.success:
            print(f"头像更换成功: {avatar_result.profile_image_url}")

    # 更换背景图
    with open("banner.jpg", "rb") as f:
        banner_bytes = f.read()

    banner_upload = await client.upload.image(banner_bytes, "banner_image")
    if banner_upload.success:
        banner_result = await client.user.change_background_image(
            banner_upload.media_id_string
        )
        if banner_result.success:
            print(f"背景图更换成功: {banner_result.banner_url}")

检查用户认证状态

async def check_verification():
    client = Twitter(cookies)

    result = await client.user.get_about_account("elonmusk")

    if result.success:
        print(f"用户 ID: {result.rest_id}")

        if result.is_blue_verified:
            print("✅ 已蓝V认证")
        else:
            print("❌ 未蓝V认证")

        if result.is_identity_verified:
            print("✅ 已身份认证")
        else:
            print("❌ 未身份认证")

        if result.account_based_in:
            print(f"📍 账号来源: {result.account_based_in}")

最佳实践

1. 验证操作结果

result = await client.user.get_profile("username")

# 始终检查 success 状态
if result.success:
    # 成功处理
    print(f"Found: @{result.screen_name}")
else:
    # 失败处理
    print(f"Error: {result.error_msg}")
    print(f"HTTP Status: {result.http_status}")

2. 处理私密账号

result = await client.user.get_profile("username")

if result.success:
    if result.protected:
        print("这是一个私密账号,部分信息可能受限")
    else:
        print(f"粉丝数: {result.followers_count}")

3. 上传头像/背景图时使用正确的类别

# 头像和背景图都使用 banner_image 类别
upload_result = await client.upload.image(image_bytes, "banner_image")

# 不要使用其他类别
# ❌ await client.upload.image(image_bytes, "tweet_image")  # 错误
# ❌ await client.upload.image(image_bytes, "dm_image")     # 错误

4. 批量操作添加延迟

usernames = ["user1", "user2", "user3", ...]

for username in usernames:
    result = await client.user.get_profile(username)
    # 处理结果...
    await asyncio.sleep(0.5)  # 避免限流

5. 编辑资料时只传递需要修改的字段

from x_api_rs.user import EditUserParams

# ✅ 好:只传递需要修改的字段
params = EditUserParams(name="New Name")

# ✅ 也可以:传递多个字段
params = EditUserParams(
    name="New Name",
    description="New bio"
)

# 不需要传递空字符串来"清空"字段

常见问题

Q1: 如何获取用户 ID?

可以通过 get_profile() 获取用户 ID:

result = await client.user.get_profile("elonmusk")
if result.success:
    user_id = result.user_id  # "44196397"

Q2: 查询用户时出现 "User not found" 错误?

可能的原因:

  • 用户名拼写错误
  • 用户已被封禁或注销
  • 用户设置了隐私保护

Q3: 头像/背景图上传后尺寸不对?

Twitter 会自动调整图片尺寸:

  • 头像:建议 400x400 像素,会被裁剪为圆形
  • 背景图:建议 1500x500 像素(3:1 比例)

Q4: 编辑资料时如何清空某个字段?

传递空字符串即可:

params = EditUserParams(
    location=""  # 清空位置信息
)
result = await client.user.edit_profile(params)

Q5: 为什么 following 字段有时为 False?

following 表示当前认证用户是否关注目标用户:

  • True: 你正在关注该用户
  • False: 你没有关注该用户

如果查询的是自己的资料,该字段可能没有意义。

Q6: 如何判断用户是否被封禁?

被封禁的用户查询时可能返回:

  • success = False
  • error_msg 包含相关错误信息
  • profile_interstitial_type 有特定值
result = await client.user.get_profile("username")

if not result.success:
    print("用户可能被封禁或不存在")
elif result.profile_interstitial_type:
    print(f"账号状态异常: {result.profile_interstitial_type}")

下一步