Skip to content

求助:{'user_message': '不正确的请求。', 'message': '', 'reason': '', 'user_message_details': {}} #415

Description

@thomas666-u

(求助!)
无论如何写代码,总是请求会报错
错误信息: {'user_message': '不正确的请求。', 'message': '', 'reason': '', 'user_message_details': {}}

修了很久都修复失败

测试代码 之一:

# -*- coding: utf-8 -*-
"""
Pixiv API 可用性测试脚本 (修正版)
"""

import sys
import json
import time
import traceback
from pixivpy3 import ByPassSniApi, PixivError

# ========== 请填写您的 refresh_token ==========
REFRESH_TOKEN = ---
# ============================================

def test_pixiv_api():
    print("=" * 60)
    print("Pixiv API 可用性测试 (ByPassSniApi - 修正版)")
    print("=" * 60)

    if REFRESH_TOKEN == "请替换为您的 refresh_token":
        print("[错误] 请先编辑脚本,填入有效的 refresh_token")
        sys.exit(1)

    # ---------- 初始化 API 客户端 (严格遵循 PixivBiu) ----------
    api = ByPassSniApi()
    # 设置绕过 GFW 的域名(与 PixivBiu 联网获取的 pApiURL 一致)
    api.require_appapi_hosts(hostname="public-api.secure.pixiv.net", timeout=10)
    # 设置语言
    api.set_accept_language("zh-cn")
    # 可选:添加其他头部(有些环境需要)
    # api.set_additional_headers({'User-Agent': 'PixivIOSApp/7.13.3'})

    # 认证(重试)
    auth_success = False
    for attempt in range(3):
        try:
            print(f"\n[认证] 尝试 {attempt+1}/3 ...")
            auth_result = api.auth(refresh_token=REFRESH_TOKEN)
            if auth_result and auth_result.get("access_token"):
                print("[认证] 成功!")
                print(f"       user_id: {api.user_id}")
                print(f"       access_token: {api.access_token[:20]}...")
                auth_success = True
                break
            else:
                print(f"[认证] 响应无效: {auth_result}")
        except PixivError as e:
            print(f"[认证] PixivError: {e}")
        except Exception as e:
            print(f"[认证] 未知错误: {e}")
        if attempt < 2:
            time.sleep(3)

    if not auth_success:
        print("\n[失败] 认证失败,退出。")
        sys.exit(1)

    print("\n" + "-" * 40)
    print("开始测试 API 接口...")
    print("-" * 40)

    # 先测试一个简单的接口:用户详情(自己)
    test_user_self(api)

    # 搜索测试
    test_search_illust(api)
    test_search_novel(api)
    test_search_user(api)

    # 详情测试
    test_illust_detail(api)
    test_novel_detail(api)

    print("\n" + "=" * 60)
    print("测试完成")
    print("=" * 60)


def safe_print_response(api_name, resp):
    """安全打印响应内容"""
    print(f"    [{api_name}] 响应类型: {type(resp)}")
    if resp is None:
        print(f"    [{api_name}] 响应为 None")
    elif hasattr(resp, '__dict__'):
        try:
            # 尝试转为字典打印
            data = {k: v for k, v in resp.__dict__.items() if not k.startswith('_')}
            print(f"    [{api_name}] 响应内容: {json.dumps(data, ensure_ascii=False, indent=2)}")
        except Exception as e:
            print(f"    [{api_name}] 无法序列化响应: {e}")
    else:
        print(f"    [{api_name}] 响应: {resp}")


def test_user_self(api):
    """获取自己的用户信息,验证认证是否彻底成功"""
    print("\n[测试] 获取当前用户信息")
    try:
        # 使用 user_detail 并传入自己的 user_id
        if api.user_id:
            resp = api.user_detail(api.user_id)
            safe_print_response("user_detail", resp)
            if resp and hasattr(resp, 'user'):
                user = resp.user
                print(f"  ✅ 成功!用户名: {user.name} (@{user.account})")
            else:
                print(f"  ❌ 失败:响应中没有 user 字段")
        else:
            print("  ⚠️ 无法获取 user_id")
    except Exception as e:
        print(f"  ❌ 异常: {e}")


def test_search_illust(api):
    print("\n[测试] 搜索插画 (关键词: 初音ミク)")
    try:
        # 按照 PixivBiu 写法,不传额外参数
        resp = api.search_illust(word="初音ミク", search_target="partial_match_for_tags")
        safe_print_response("search_illust", resp)
        if resp and hasattr(resp, 'illusts') and resp.illusts:
            first = resp.illusts[0]
            print(f"  ✅ 成功!返回 {len(resp.illusts)} 个结果")
            print(f"      首个作品: {first.title} (ID: {first.id})")
        else:
            print(f"  ❌ 失败:无结果或响应异常")
            if hasattr(resp, 'error'):
                print(f"      错误信息: {resp.error}")
    except Exception as e:
        print(f"  ❌ 异常: {e}")
        traceback.print_exc()


def test_search_novel(api):
    print("\n[测试] 搜索小说 (关键词: ファンタジー)")
    try:
        resp = api.search_novel(word="ファンタジー", search_target="keyword")
        safe_print_response("search_novel", resp)
        if resp and hasattr(resp, 'novels') and resp.novels:
            first = resp.novels[0]
            print(f"  ✅ 成功!返回 {len(resp.novels)} 个结果")
            print(f"      首个作品: {first.title} (ID: {first.id})")
        else:
            print(f"  ❌ 失败:无结果或响应异常")
    except Exception as e:
        print(f"  ❌ 异常: {e}")
        traceback.print_exc()


def test_search_user(api):
    print("\n[测试] 搜索用户 (关键词: 米山舞)")
    try:
        resp = api.search_user(word="米山舞")
        safe_print_response("search_user", resp)
        if resp and hasattr(resp, 'user_previews') and resp.user_previews:
            first = resp.user_previews[0]
            print(f"  ✅ 成功!返回 {len(resp.user_previews)} 个结果")
            print(f"      首个用户: {first.user.name} (ID: {first.user.id})")
        else:
            print(f"  ❌ 失败:无结果或响应异常")
    except Exception as e:
        print(f"  ❌ 异常: {e}")
        traceback.print_exc()


def test_illust_detail(api):
    illust_id = 80715154
    print(f"\n[测试] 获取插画详情 (ID: {illust_id})")
    try:
        resp = api.illust_detail(illust_id)
        safe_print_response("illust_detail", resp)
        if resp and hasattr(resp, 'illust'):
            illust = resp.illust
            print(f"  ✅ 成功!标题: {illust.title}")
            print(f"      作者: {illust.user.name}")
        else:
            print(f"  ❌ 失败:响应异常")
    except Exception as e:
        print(f"  ❌ 异常: {e}")
        traceback.print_exc()


def test_novel_detail(api):
    novel_id = 12438689
    print(f"\n[测试] 获取小说详情 (ID: {novel_id})")
    try:
        resp = api.novel_detail(novel_id)
        safe_print_response("novel_detail", resp)
        if resp and hasattr(resp, 'novel'):
            novel = resp.novel
            print(f"  ✅ 成功!标题: {novel.title}")
            print(f"      作者: {novel.user.name}")
        else:
            print(f"  ❌ 失败:响应异常")
    except Exception as e:
        print(f"  ❌ 异常: {e}")
        traceback.print_exc()


if __name__ == "__main__":
    test_pixiv_api()```


输出:============================================================
Pixiv API 可用性测试 (ByPassSniApi - 修正版)
============================================================

[认证] 尝试 1/3 ...
[认证] 成功!
       user_id: 106...
       access_token: w...

----------------------------------------
开始测试 API 接口...
----------------------------------------

[测试] 获取当前用户信息
    [user_detail] 响应类型: <class 'pixivpy3.utils.JsonDict'>
    [user_detail] 响应内容: {}
  ❌ 异常: 'NoneType' object has no attribute 'name'

[测试] 搜索插画 (关键词: 初音ミク)
    [search_illust] 响应类型: <class 'pixivpy3.utils.JsonDict'>
    [search_illust] 响应内容: {}
  ❌ 失败:无结果或响应异常
      错误信息: {'user_message': '不正确的请求。', 'message': '', 'reason': '', 'user_message_details': {}}

[测试] 搜索小说 (关键词: ファンタジー)
    [search_novel] 响应类型: <class 'pixivpy3.utils.JsonDict'>
    [search_novel] 响应内容: {}
  ❌ 失败:无结果或响应异常

[测试] 搜索用户 (关键词: 米山舞)
    [search_user] 响应类型: <class 'pixivpy3.utils.JsonDict'>
    [search_user] 响应内容: {}
  ❌ 失败:无结果或响应异常


主要就是一直报错 {'user_message': '不正确的请求。', 'message': '', 'reason': '', 'user_message_details': {}},
怎么修都修不好

大佬们能不能帮忙看一下代码哪里的有问题。。。谢谢

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions