【Python】如何高效查询ChatGPT使用剩余额度和过往使用历史(详细代码)


前言

关于chatgpt目前的火爆程度不言而喻

但是很多开发朋友,或者用来学习的朋友并不知道自己的key还剩多少额度

一、遇到的问题

官方禁用了之前的获取方式,链接如下:

https://api.openai.com/dashboard/billing/credit_grants

将会得到如下回复

Your request to GET /dashboard/billing/credit_grants must be made with a session key (that is, it can only be made from the browser). You made it with the following key type: secret.

其实是由于把一般的key换成了session key导致的

话不多说,以下是封装的目前可用的查询chatGPT剩余key的方法:

二、实操代码

1.引入库

代码如下(示例):

import datetime
import requests
# macll.cn 免费用gpt!!

def get_key(apikey):
    subscription_url = "https://api.openai.com/v1/dashboard/billing/subscription"
    headers = {"Authorization": "Bearer " + apikey,
               "Content-Type": "application/json"}
    subscription_response = requests.get(subscription_url, headers=headers)
    if subscription_response.status_code == 200:
        data = subscription_response.json()
        total = data.get("hard_limit_usd")
    else:
        return subscription_response.text
    # start_date设置为今天日期前99
    start_date = (datetime.datetime.now() - datetime.timedelta(days=99)).strftime("%Y-%m-%d")
    # end_date设置为今天日期+1
    end_date = (datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%Y-%m-%d")
    billing_url = f"https://api.openai.com/v1/dashboard/billing/usage?start_date={start_date}&end_date={end_date}"
    billing_response = requests.get(billing_url, headers=headers)
    if billing_response.status_code == 200:
        data = billing_response.json()
        total_usage = data.get("total_usage") / 100
        daily_costs = data.get("daily_costs")
        # 这个10就是指10天,可以自己调整~
        days = min(10, len(daily_costs))
        recent = f"##### 最近{days}天使用情况  \n"
        for i in range(days):
            cur = daily_costs[-i - 1]
            date = datetime.datetime.fromtimestamp(cur.get("timestamp")).strftime("%Y-%m-%d")
            line_items = cur.get("line_items")
            cost = 0
            for item in line_items:
                cost += item.get("cost")
            recent += f"\t{date}\t{(cost / 100):.2f} \n"
    else:
        return billing_response.text

    return f"\n#### 监控key为:{apikey[:-25] + '*' * 25}\n" \
           f"#### 总额:\t{total:.2f}  \n" \
           f"#### 已用:\t{total_usage:.2f}  \n" \
           f"#### 剩余:\t{total - total_usage:.2f}  \n" \
           f"\n" + recent


print(get_key(apikey="这里放入你的key"))

在这里插入图片描述
你还可以接入自己的邮箱,随时监控,方便可靠~

在这里插入图片描述

该代码实测有效!

总结

觉着有用请一键三连

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

徐浪老师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值