gpt.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package public
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "time"
  6. "github.com/eryajf/chatgpt-dingtalk/config"
  7. "github.com/go-resty/resty/v2"
  8. )
  9. func InitAiCli() *resty.Client {
  10. return resty.New().SetTimeout(30*time.Second).SetHeader("Authorization", fmt.Sprintf("Bearer %s", config.LoadConfig().ApiKey)).SetProxy(config.LoadConfig().HttpProxy)
  11. }
  12. type Billing struct {
  13. Object string `json:"object"`
  14. TotalGranted float64 `json:"total_granted"`
  15. TotalUsed float64 `json:"total_used"`
  16. TotalAvailable float64 `json:"total_available"`
  17. Grants struct {
  18. Object string `json:"object"`
  19. Data []struct {
  20. Object string `json:"object"`
  21. ID string `json:"id"`
  22. GrantAmount float64 `json:"grant_amount"`
  23. UsedAmount float64 `json:"used_amount"`
  24. EffectiveAt float64 `json:"effective_at"`
  25. ExpiresAt float64 `json:"expires_at"`
  26. } `json:"data"`
  27. } `json:"grants"`
  28. }
  29. func GetBalance() (Billing, error) {
  30. var data Billing
  31. url := "https://api.openai.com/dashboard/billing/credit_grants"
  32. resp, err := InitAiCli().R().Get(url)
  33. if err != nil {
  34. return data, err
  35. }
  36. err = json.Unmarshal(resp.Body(), &data)
  37. if err != nil {
  38. return data, err
  39. }
  40. return data, nil
  41. }