本文最后更新于 2023-12-15,文章内容可能已经过时,遇到问题可以留言。

PandoraNext 更新access token脚本

效果

  1. python脚本实现自动更新token
  2. 多用户
  3. 使用api,每个用户请求1次会消耗100

代码实现pandora_tokens.py

  1. 以下代码中的Base URL是你部署服务的地址,包括域名(IP)和端口
  2. proxy_api_prefix为pandoranext设置的api前缀
  3. 脚本名pandora_tokens.py,也可以自己命名,定时任务会用到
  4. 脚本中pandora_users.json存放用户的邮箱及密码
import requests, json
from urllib.parse import urlencode


def get_token(user, username, password):
    # 登录api
    login_url = 'Base URL/proxy_api_prefix/api/auth/login'

    # 构建要发送的数据
    data = {
        'username': username,
        'password': password
    }

    # 使用urlencode对数据进行编码
    encoded_data = urlencode(data)

    # 发送POST请求
    response = requests.post(login_url, data=encoded_data, headers={'Content-Type': 'application/x-www-form-urlencoded'})

    # 检查响应
    if response.status_code == 200:
        # 获取访问令牌
        access_token = response.json().get('access_token')
        print("Access token:", access_token)
    else:
        print("Failed to retrieve access token. Status code:", response.status_code)

    # 读取tokens.json文件
    file_path = '服务器tokens.json路径,对应容器里/data/tokens.json'

    with open(file_path, 'r') as file:
        tokens_data = json.load(file)

    # 更新user的token值
    tokens_data[user]['token'] = access_token

    # 将更新后的数据保存回tokens.json文件
    with open(file_path, 'w') as file:
        json.dump(tokens_data, file, indent=4)

# 遍历pandora_users.json
# 读取tokens.json文件
user_path = '服务器pandora_users.json路径,存放登录信息'

with open(user_path, 'r') as file:
    users_data = json.load(file)

for user, data in users_data.items():
    get_token(user, data['username'], data['password'])

# Pandoranext热重载
requests.post('Base URL/proxy_api_prefix/api/setup/reload')

pandora_users.json文件模板

  1. user1/user2需要和pandoranext配置文件tokens.json里保持一致
  2. user可以根据自己需求增加
{
    "user1":{
        "username": "你的gpt账号",
        "password": "你的gpt密码"
    },
    "user2":{
        "username": "你的gpt账号",
        "password": "你的gpt密码"
    }
}

定时运行

  1. corntab执行pandora_tokens.py
  2. 宝塔或者1Panel面板上的定时任务,定时执行python3 pandora_tokens.py
  3. 用青龙面板执行task pandora_tokens.py