discordbot / horde.py
joytou's picture
Add optional param headers
88af923
import os
import httpx
hordeApiKey = os.environ.get("HORDE_API_KEY")
baseUrl = "https://aihorde.net/api/v2/"
headers = {
"Content-Type": "application/json",
"apikey": f"{hordeApiKey}"
}
class HordeAPI:
# 省去类初始化,直接在每个方法里创建客户端
async def _fetch(self, url, method="GET", headers=headers):
async with httpx.AsyncClient() as client:
if method == "GET":
response = await client.get(url, headers=headers)
elif method == "POST":
response = await client.post(url, headers=headers)
if response.status_code == 200:
return response.json()
else:
return {
"code": response.status_code,
"reason": response.text
}
class APIContextManager:
def __init__(self, api_call):
self.api_call = api_call
self.result = None
async def __aenter__(self):
self.result = await self.api_call()
return self.result
async def __aexit__(self, exc_type, exc_value, traceback):
pass
# 提供 API 调用方法,直接通过 async with 使用
@staticmethod
def getUserDetails():
async def api_call():
url = f"{baseUrl}find_user"
return await HordeAPI()._fetch(url)
return HordeAPI.APIContextManager(api_call)
@staticmethod
def generateCheck(id):
async def api_call():
url = f"{baseUrl}generate/check/{id}"
return await HordeAPI()._fetch(url, headers={"Content-Type": "application/json"})
return HordeAPI.APIContextManager(api_call)
@staticmethod
def generateStatus(id):
async def api_call():
url = f"{baseUrl}generate/status/{id}"
return await HordeAPI()._fetch(url, headers={"Content-Type": "application/json"})
return HordeAPI.APIContextManager(api_call)