joytou commited on
Commit
400b811
·
1 Parent(s): cb390bc

Improve code

Browse files
Files changed (2) hide show
  1. discord.json +3 -9
  2. discord_bot.py +31 -154
discord.json CHANGED
@@ -13,16 +13,10 @@
13
  {
14
  "type": "equals",
15
  "content": "get kudos",
16
- "function": "getKudos"
17
  }
18
  ],
19
  "command": [
20
- {
21
- "name": "hello",
22
- "description": "Sends a greeting!",
23
- "function": "hello",
24
- "parameters": []
25
- },
26
  {
27
  "name": "greet",
28
  "description": "Greets the specified user",
@@ -38,13 +32,13 @@
38
  {
39
  "name": "get_kudos",
40
  "description": "The amount of Kudos this user has.",
41
- "function": "getKudos",
42
  "parameters": []
43
  },
44
  {
45
  "name": "generate_status",
46
  "description": "Retrieve the status of an Asynchronous generation request.",
47
- "function": "generateStatus",
48
  "parameters": [
49
  {
50
  "name": "id",
 
13
  {
14
  "type": "equals",
15
  "content": "get kudos",
16
+ "function": "get_kudos"
17
  }
18
  ],
19
  "command": [
 
 
 
 
 
 
20
  {
21
  "name": "greet",
22
  "description": "Greets the specified user",
 
32
  {
33
  "name": "get_kudos",
34
  "description": "The amount of Kudos this user has.",
35
+ "function": "get_kudos",
36
  "parameters": []
37
  },
38
  {
39
  "name": "generate_status",
40
  "description": "Retrieve the status of an Asynchronous generation request.",
41
+ "function": "generate_status",
42
  "parameters": [
43
  {
44
  "name": "id",
discord_bot.py CHANGED
@@ -11,12 +11,6 @@ from horde import HordeAPI
11
  import inspect
12
 
13
 
14
- TYPE_MAPPING = {
15
- "str": str,
16
- "int": int,
17
- "float": float
18
- }
19
-
20
 
21
  # 创建一个字典,将规则类型映射到相应的条件检查函数
22
  check_functions = {
@@ -27,18 +21,23 @@ check_functions = {
27
  }
28
 
29
 
 
30
  intents = discord.Intents.default()
31
  intents.message_content = True
32
  bot = commands.Bot(command_prefix='>', intents=intents)
33
  tree = bot.tree
34
 
35
 
 
36
  with open("discord.json", "r") as f:
37
  json_data = json.load(f)
38
 
 
39
  # 自动生成调用函数
40
- commandNamePrefix="discord_bot_call_"
41
- file_content="\n\n".join([f"async def {commandNamePrefix}{command['name']}(interaction: discord.Interaction"
 
 
42
  +''.join([f", {param['name']}: {param['type']}" for param in command["parameters"]])
43
  +f"):\n\
44
  await interaction.response.defer()\n\
@@ -47,162 +46,48 @@ file_content="\n\n".join([f"async def {commandNamePrefix}{command['name']}(inter
47
  +f")\n\
48
  if result is not None:\n\
49
  await interaction.followup.send(result)\n\
50
- tree.add_command(app_commands.Command(name=\"{command['name']}\", description=\"{command['description']}\", callback={commandNamePrefix}{command['name']}))"
 
 
 
 
51
  for command in json_data["command"]])
52
- exec(file_content)
53
-
54
-
55
-
56
-
57
- """
58
- @tree.command(name="hello", description="Sends a greeting!")
59
- async def hello(interaction: discord.Interaction):
60
- await interaction.response.send_message(f"Hello, {interaction.user.mention}!")
61
-
62
- @tree.command(name="greet", description="Greets the specified user")
63
- async def greet(interaction: discord.Interaction, name: str):
64
- await interaction.response.send_message(f"Hello, {name}!")
65
-
66
- @tree.command(name="get-kudos", description="The amount of Kudos this user has.")
67
- async def getKudos(interaction: discord.Interaction):
68
- await interaction.response.defer()
69
- async with HordeAPI.getUserDetails() as details:
70
- if "kudos" not in details:
71
- await interaction.followup.send(f'Error: {details["code"]} {details["reason"]}')
72
- return
73
- await interaction.followup.send(f'The amount of Kudos this user has is {details["kudos"]}')
74
-
75
- @tree.command(name="generate-status", description="Retrieve the status of an Asynchronous generation request.")
76
- async def generateStatus(interaction: discord.Interaction, id: str):
77
- await interaction.response.defer()
78
- async with HordeAPI.generateCheck(id) as details:
79
- if "kudos" not in details:
80
- await interaction.followup.send(f'Check Error: {details["code"]} {details["reason"]}')
81
- return
82
- if bool(details["is_possible"]) == False:
83
- await interaction.followup.send("This generation is impossible.")
84
- return
85
- if bool(details["faulted"]) == True:
86
- await interaction.followup.send("This generation is faulted.")
87
- return
88
- if bool(details["done"]) == True:
89
- async with HordeAPI.generateStatus(id) as generationDetail:
90
- if "generations" not in generationDetail:
91
- await interaction.followup.send(f'Status Error: {generationDetail["code"]} {generationDetail["reason"]}')
92
- for i in range(len(generationDetail["generations"])):
93
- await interaction.followup.send(generationDetail["generations"][i]["img"])
94
- return
95
- if int(details["processing"]) > 0:
96
- total = int(details["finished"]) + int(details["processing"]) + int(details["queue_position"]) + int(details["restarted"]) + int(details["waiting"])
97
- await interaction.followup.send(f'Processing image: {details["processing"]}/{total}')
98
- return
99
- await interaction.followup.send(f'Position in queue: {details["queue_position"]}, wait time: {details["wait_time"]}s')
100
- """
101
-
102
- print(discord.version_info)
103
- print(discord.__version__)
104
- print(inspect.signature(app_commands.Command))
105
 
106
- async def hello():
107
- return f"Hello, {interaction.user.mention}!"
108
 
109
  async def greet(name: str):
110
  return f"Hello, {name}!"
111
 
112
- async def getKudos():
113
  async with HordeAPI.getUserDetails() as details:
114
  if "kudos" not in details:
115
  return f'Error: {details["code"]} {details["reason"]}'
116
  return f'The amount of Kudos this user has is {details["kudos"]}'
117
 
118
- async def generateStatus(id: str):
119
  async with HordeAPI.generateCheck(id) as details:
120
  if "kudos" not in details:
121
  return f'Check Error: {details["code"]} {details["reason"]}'
122
- if bool(details["is_possible"]) == False:
123
  return "This generation is impossible."
124
- if bool(details["faulted"]) == True:
125
  return "This generation is faulted."
126
- if bool(details["done"]) == True:
127
- async with HordeAPI.generateStatus(id) as generationDetail:
128
- if "generations" not in generationDetail:
129
- return f'Status Error: {generationDetail["code"]} {generationDetail["reason"]}'
130
- for i in range(len(generationDetail["generations"])):
131
- return generationDetail["generations"][i]["img"]
132
  if int(details["processing"]) > 0:
133
- total = int(details["finished"]) + int(details["processing"]) + int(details["queue_position"]) + int(details["restarted"]) + int(details["waiting"])
 
 
 
 
134
  return f'Processing image: {details["processing"]}/{total}'
135
  return f'Position in queue: {details["queue_position"]}, wait time: {details["wait_time"]}s'
136
 
137
 
138
- """
139
- # 根据 json 数据动态创建命令
140
- for command in json_data["command"]:
141
- @tree.command(name=command["name"], description=command["description"])
142
- async def dynamic_command(interaction: discord.Interaction, **kwargs):
143
- print(kwargs)
144
- await interaction.response.defer()
145
- # 动态调用命令对应的函数
146
- function_name = command["function"]
147
- function = globals()[function_name]
148
- result = await function()
149
- await interaction.followup.send(result)
150
-
151
- # 动态创建参数
152
- #params = [app_commands.Parameter(name=param["name"], display_name=param['name'], description=param["description"], type=TYPE_MAPPING[param["type"]], autocomplete=False, required=True)
153
- # for param in command["parameters"]]
154
-
155
-
156
-
157
- # 动态创建命令并注册
158
- tree_command = app_commands.Command(
159
- name=command["name"],
160
- description=command["description"],
161
- callback=dynamic_command
162
- )
163
-
164
- # 将命令添加到 bot 的 command tree
165
- bot.tree.add_command(tree_command)
166
- """
167
-
168
-
169
- """
170
- class MyClient(discord.Client):
171
- def __init__(self, **kwargs):
172
- # 从 kwargs 中获取 intents,或者使用默认 intents
173
- intents = kwargs.pop('intents', discord.Intents.default())
174
-
175
- # 调用 discord.Client 的 __init__,并将 intents 作为关键字参数传递
176
- super().__init__(intents=intents, **kwargs)
177
-
178
- self.tree = app_commands.CommandTree(self)
179
-
180
- async def setup_hook(self):
181
- # 在这里你可以注册动态生成的命令
182
- self.tree.add_command(app_commands.Command(name="test", callback=self.test, description="test"))
183
- await self.tree.sync() # 同步命令
184
-
185
- async def test(self, interaction: discord.Interaction, x: str, y: int):
186
- print(self)
187
- print(interaction)
188
- print(x)
189
- print(y)
190
- await interaction.response.send_message(f"x: {x}, y: {y}")
191
- MyClient(bot)
192
- """
193
-
194
-
195
- """
196
- @tree.command(name="test", description="test")
197
- async def test(interaction: discord.Interaction, *args):
198
- print(interaction)
199
- print(args)
200
- await interaction.response.send_message(f"{args}")
201
- #tree.add_command(app_commands.Command(name="test", description="test", callback=test))
202
- """
203
-
204
-
205
-
206
  @bot.command()
207
  async def ping(ctx):
208
  await ctx.send('pong')
@@ -220,13 +105,6 @@ async def on_message(message):
220
  if message.author == bot.user:
221
  return
222
 
223
- """
224
- if message.content == 'ping':
225
- await message.channel.send('pong')
226
-
227
- if message.content.startswith('$hello'):
228
- await message.channel.send('Hello!')
229
- """
230
  for rule in json_data["message"]:
231
  rule_type = rule["type"]
232
  content = rule["content"]
@@ -238,12 +116,11 @@ async def on_message(message):
238
  if "function" in rule:
239
  function_name = rule["function"]
240
  function = globals()[function_name]
241
- await function(message)
242
- break
243
  # 否则发送预定义的响应消息
244
  elif "response" in rule:
245
- await message.channel.send(rule["response"])
246
- break
247
 
248
  # 确保命令系统正常工作
249
  await bot.process_commands(message)
 
11
  import inspect
12
 
13
 
 
 
 
 
 
 
14
 
15
  # 创建一个字典,将规则类型映射到相应的条件检查函数
16
  check_functions = {
 
21
  }
22
 
23
 
24
+ # 定义bot和tree
25
  intents = discord.Intents.default()
26
  intents.message_content = True
27
  bot = commands.Bot(command_prefix='>', intents=intents)
28
  tree = bot.tree
29
 
30
 
31
+ # 读取json
32
  with open("discord.json", "r") as f:
33
  json_data = json.load(f)
34
 
35
+
36
  # 自动生成调用函数
37
+ COMMAND_NAME_PREFIX="discord_bot_call_"
38
+ FILE_CONTENT="\n\n".join([
39
+ f"async def {COMMAND_NAME_PREFIX}{command['name']}"
40
+ +"(interaction: discord.Interaction"
41
  +''.join([f", {param['name']}: {param['type']}" for param in command["parameters"]])
42
  +f"):\n\
43
  await interaction.response.defer()\n\
 
46
  +f")\n\
47
  if result is not None:\n\
48
  await interaction.followup.send(result)\n\
49
+ tree.add_command(app_commands.Command(\
50
+ name=\"{command['name']}\", \
51
+ description=\"{command['description']}\", \
52
+ callback={COMMAND_NAME_PREFIX}{command['name']}\
53
+ ))"
54
  for command in json_data["command"]])
55
+ exec(FILE_CONTENT)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
 
 
57
 
58
  async def greet(name: str):
59
  return f"Hello, {name}!"
60
 
61
+ async def get_kudos():
62
  async with HordeAPI.getUserDetails() as details:
63
  if "kudos" not in details:
64
  return f'Error: {details["code"]} {details["reason"]}'
65
  return f'The amount of Kudos this user has is {details["kudos"]}'
66
 
67
+ async def generate_status(id: str):
68
  async with HordeAPI.generateCheck(id) as details:
69
  if "kudos" not in details:
70
  return f'Check Error: {details["code"]} {details["reason"]}'
71
+ if bool(details["is_possible"]) is False:
72
  return "This generation is impossible."
73
+ if bool(details["faulted"]) is True:
74
  return "This generation is faulted."
75
+ if bool(details["done"]) is True:
76
+ async with HordeAPI.generateStatus(id) as generation_detail:
77
+ if "generations" not in generation_detail:
78
+ return f'Status Error: {generation_detail["code"]} {generation_detail["reason"]}'
79
+ for i in range(len(generation_detail["generations"])):
80
+ return generation_detail["generations"][i]["img"]
81
  if int(details["processing"]) > 0:
82
+ total = int(details["finished"])
83
+ + int(details["processing"])
84
+ + int(details["queue_position"])
85
+ + int(details["restarted"])
86
+ + int(details["waiting"])
87
  return f'Processing image: {details["processing"]}/{total}'
88
  return f'Position in queue: {details["queue_position"]}, wait time: {details["wait_time"]}s'
89
 
90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  @bot.command()
92
  async def ping(ctx):
93
  await ctx.send('pong')
 
105
  if message.author == bot.user:
106
  return
107
 
 
 
 
 
 
 
 
108
  for rule in json_data["message"]:
109
  rule_type = rule["type"]
110
  content = rule["content"]
 
116
  if "function" in rule:
117
  function_name = rule["function"]
118
  function = globals()[function_name]
119
+ result = await function(message)
120
+ await message.channel.send(result)
121
  # 否则发送预定义的响应消息
122
  elif "response" in rule:
123
+ await message.channel.send(response)
 
124
 
125
  # 确保命令系统正常工作
126
  await bot.process_commands(message)