A-A+

好用的查询ChatGPT使用量的php代码:达到预定的阈值后通过微信进行推送

2023年06月28日 VPS评价 等您评论

准备工作: 

目前最简单最好用的微信推送方式

企业微信注册免费https://work.weixin.qq.com
注册后,创建个群,然后添加机器人进去,取到webhook地址,然后按文档POST提交要提醒的数据就行了。
官方文档

  1. https://developer.work.weixin.qq.com/document/path/99110

查询余额达到设定的阈值后微信通知。

  1. function sendCurlRequest($url, $headers, $data) {
  2.  
  3.     $ch= curl_init();
  4.     curl_setopt($ch, CURLOPT_URL, $url);
  5.     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  6.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  7.     curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  8.     curl_setopt($ch, CURLOPT_POST, true);
  9.     $response = curl_exec($ch);
  10.     curl_close($ch);
  11.     return $response;
  12. }
  13.  
  14. $apiKey = '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';
  15. $headers = array( 'Authorization: Bearer ' . $apiKey, 'Content-Type: application/json');
  16. $url = "https://api.openai.com/v1/dashboard/billing/usage?start_date=".date('Y-m-01')."&end_date=".date('Y-m-t');
  17. $response = sendCurlRequest($url, $headers, $data);
  18. $max_usage =100;//通知触发阈值
  19. if(strstr($response,'error')){
  20.         echo "invalid_api_key";}else{
  21.         $cost_data=json_decode($response);
  22.         $total_usage=round($cost_data->total_usage/100,2);
  23. }
  24. if( $total_usage>$max_usage){
  25. $url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=693axxx6-7aoc-4bc4-97a0-0ec2sifa5aaa';
  26. $headers = array('Content-Type: application/json');
  27. $data = array("msgtype" => "text", "text" => array("content" => "余额不足","mentioned_list" => array("mjj","@all")));
  28. $response = sendCurlRequest($url, $headers, $data);
  29. echo "余额不足";
  30. }

说明:保存为notify.php,每小时访问一次,mentioned_list为通知的微信ID列表。

  1.  
  2. 使用以下命令编辑cron任务列表:
  3.  
  4. crontab -e
  5. 在打开的文件中,添加以下行来设置每小时执行的cron任务:
  6.  
  7. 0 * * * * curl http://127.0.0.1/notify.php

给我留言