gpt.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package public
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "time"
  6. "github.com/go-resty/resty/v2"
  7. )
  8. func InitAiCli() *resty.Client {
  9. if Config.HttpProxy != "" {
  10. return resty.New().SetTimeout(30*time.Second).SetHeader("Authorization", fmt.Sprintf("Bearer %s", Config.ApiKey)).SetProxy(Config.HttpProxy).SetRetryCount(3).SetRetryWaitTime(5 * time.Second)
  11. }
  12. return resty.New().SetTimeout(30*time.Second).SetHeader("Authorization", fmt.Sprintf("Bearer %s", Config.ApiKey)).SetRetryCount(3).SetRetryWaitTime(5 * time.Second)
  13. }
  14. type Billing struct {
  15. Object string `json:"object"`
  16. TotalGranted float64 `json:"total_granted"`
  17. TotalUsed float64 `json:"total_used"`
  18. TotalAvailable float64 `json:"total_available"`
  19. Grants struct {
  20. Object string `json:"object"`
  21. Data []struct {
  22. Object string `json:"object"`
  23. ID string `json:"id"`
  24. GrantAmount float64 `json:"grant_amount"`
  25. UsedAmount float64 `json:"used_amount"`
  26. EffectiveAt float64 `json:"effective_at"`
  27. ExpiresAt float64 `json:"expires_at"`
  28. } `json:"data"`
  29. } `json:"grants"`
  30. }
  31. func GetBalance() (Billing, error) {
  32. var data Billing
  33. url := "https://api.openai.com/dashboard/billing/credit_grants"
  34. resp, err := InitAiCli().R().Get(url)
  35. if err != nil {
  36. return data, err
  37. }
  38. err = json.Unmarshal(resp.Body(), &data)
  39. if err != nil {
  40. return data, err
  41. }
  42. t1 := time.Unix(int64(data.Grants.Data[0].EffectiveAt), 0)
  43. t2 := time.Unix(int64(data.Grants.Data[0].ExpiresAt), 0)
  44. msg := fmt.Sprintf("💵 已用: 💲%v\n💵 剩余: 💲%v\n⏳ 有效时间: 从 %v 到 %v\n", fmt.Sprintf("%.2f", data.TotalUsed), fmt.Sprintf("%.2f", data.TotalAvailable), t1.Format("2006-01-02 15:04:05"), t2.Format("2006-01-02 15:04:05"))
  45. // 放入缓存
  46. UserService.SetUserMode("system_balance", msg)
  47. return data, nil
  48. }