joytou commited on
Commit
a3fa62e
·
1 Parent(s): 1e03748

Fixed AttributeError: __aenter__

Browse files
Files changed (2) hide show
  1. discord_bot.py +4 -4
  2. horde.py +51 -37
discord_bot.py CHANGED
@@ -7,7 +7,7 @@ from discord import app_commands
7
  from discord.ext import commands
8
  from threading import Thread
9
  import json
10
- import horde
11
 
12
 
13
 
@@ -26,7 +26,7 @@ async def greet(interaction: discord.Interaction, name: str):
26
 
27
  @tree.command(name="get-kudos", description="The amount of Kudos this user has.")
28
  async def getKudos(interaction: discord.Interaction):
29
- async with horde.getUserDetails() as details:
30
  if "kudos" not in details:
31
  await interaction.response.send_message(f'Error: {details["code"]} {details["reason"]} {details["rc"]}')
32
  return
@@ -34,7 +34,7 @@ async def getKudos(interaction: discord.Interaction):
34
 
35
  @tree.command(name="generate-status", description="Retrieve the status of an Asynchronous generation request.")
36
  async def generateStatus(interaction: discord.Interaction, id: str):
37
- async with horde.generateCheck(id) as details:
38
  if "kudos" not in details:
39
  await interaction.response.send_message(f'Check Error: {details["code"]} {details["reason"]} {details["rc"]}')
40
  return
@@ -45,7 +45,7 @@ async def generateStatus(interaction: discord.Interaction, id: str):
45
  await interaction.response.send_message("This generation is faulted.")
46
  return
47
  if bool(details["done"]) == True:
48
- async with horde.generateStatus(id) as generationDetail:
49
  if "generations" not in generationDetail:
50
  await interaction.response.send_message(f'Status Error: {generationDetail["code"]} {generationDetail["reason"]} {generationDetail["rc"]}')
51
  for i in range(len(generationDetail["generations"])):
 
7
  from discord.ext import commands
8
  from threading import Thread
9
  import json
10
+ from horde import HordeAPI
11
 
12
 
13
 
 
26
 
27
  @tree.command(name="get-kudos", description="The amount of Kudos this user has.")
28
  async def getKudos(interaction: discord.Interaction):
29
+ async with HordeAPI.getUserDetails() as details:
30
  if "kudos" not in details:
31
  await interaction.response.send_message(f'Error: {details["code"]} {details["reason"]} {details["rc"]}')
32
  return
 
34
 
35
  @tree.command(name="generate-status", description="Retrieve the status of an Asynchronous generation request.")
36
  async def generateStatus(interaction: discord.Interaction, id: str):
37
+ async with HordeAPI.generateCheck(id) as details:
38
  if "kudos" not in details:
39
  await interaction.response.send_message(f'Check Error: {details["code"]} {details["reason"]} {details["rc"]}')
40
  return
 
45
  await interaction.response.send_message("This generation is faulted.")
46
  return
47
  if bool(details["done"]) == True:
48
+ async with HordeAPI.generateStatus(id) as generationDetail:
49
  if "generations" not in generationDetail:
50
  await interaction.response.send_message(f'Status Error: {generationDetail["code"]} {generationDetail["reason"]} {generationDetail["rc"]}')
51
  for i in range(len(generationDetail["generations"])):
horde.py CHANGED
@@ -1,48 +1,62 @@
1
  import os
2
- import requests
3
 
4
  hordeApiKey = os.environ.get("HORDE_API_KEY")
5
  baseUrl = "https://aihorde.net/api/v2/"
6
 
7
- def getResponseByGet(url):
8
- headers = {
9
- "Content-Type": "application/json",
10
- "apikey": f"{hordeApiKey}"
11
- }
12
- response = requests.get(url, headers=headers)
13
- if response.status_code == 200:
14
- return response.json()
15
- else:
16
- return {
17
- "code": response.status_code,
18
- "reason": response.reason,
19
- "rc": response.rc
20
- }
21
 
22
- def getResponseByPost(url):
23
- headers = {
24
- "Content-Type": "application/json",
25
- "apikey": f"{hordeApiKey}"
26
- }
27
- response = requests.post(url, headers=headers)
28
- if response.status_code == 200:
29
- return response.json()
30
- else:
31
- return {
32
- "code": response.status_code,
33
- "reason": response.reason,
34
- "rc": response.rc
35
  }
36
 
37
- async def getUserDetails():
38
- url = f"{baseUrl}find_user"
39
- return getResponseByGet(url)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
- async def generateCheck(id):
42
- url = f"{baseUrl}generate/check/{id}"
43
- return getResponseByGet(url)
 
 
 
 
44
 
45
- async def generateStatus(id):
46
- url = f"{baseUrl}generate/status/{id}"
47
- return getResponseByGet(url)
 
 
 
48
 
 
 
 
 
 
 
 
1
  import os
2
+ import httpx
3
 
4
  hordeApiKey = os.environ.get("HORDE_API_KEY")
5
  baseUrl = "https://aihorde.net/api/v2/"
6
 
7
+ class HordeAPI:
8
+ # 省去类初始化,直接在每个方法里创建客户端
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
+ async def _fetch(self, url, method="GET"):
11
+ headers = {
12
+ "Content-Type": "application/json",
13
+ "apikey": f"{hordeApiKey}"
 
 
 
 
 
 
 
 
 
14
  }
15
 
16
+ async with httpx.AsyncClient() as client:
17
+ if method == "GET":
18
+ response = await client.get(url, headers=headers)
19
+ elif method == "POST":
20
+ response = await client.post(url, headers=headers)
21
+
22
+ if response.status_code == 200:
23
+ return response.json()
24
+ else:
25
+ return {
26
+ "code": response.status_code,
27
+ "reason": response.reason,
28
+ }
29
+
30
+ class APIContextManager:
31
+ def __init__(self, api_call):
32
+ self.api_call = api_call
33
+ self.result = None
34
+
35
+ async def __aenter__(self):
36
+ self.result = await self.api_call()
37
+ return self.result
38
+
39
+ async def __aexit__(self, exc_type, exc_value, traceback):
40
+ pass
41
 
42
+ # 提供 API 调用方法,直接通过 async with 使用
43
+ @staticmethod
44
+ def getUserDetails():
45
+ async def api_call():
46
+ url = f"{baseUrl}find_user"
47
+ return await HordeAPI()._fetch(url)
48
+ return HordeAPI.APIContextManager(api_call)
49
 
50
+ @staticmethod
51
+ def generateCheck(id):
52
+ async def api_call():
53
+ url = f"{baseUrl}generate/check/{id}"
54
+ return await HordeAPI()._fetch(url)
55
+ return HordeAPI.APIContextManager(api_call)
56
 
57
+ @staticmethod
58
+ def generateStatus(id):
59
+ async def api_call():
60
+ url = f"{baseUrl}generate/status/{id}"
61
+ return await HordeAPI()._fetch(url)
62
+ return HordeAPI.APIContextManager(api_call)