我在我的个人机器人上有一个根据Discord用户的提示生成图像的命令,但当我将其改为斜杠命令时,出现了错误。我已经进行了测试,图像本身是没问题的,但它从未发送回图像。
工作代码
@client.command(aliases=['gen'])async def genimage(ctx, *, ideel): print("reg: " + ideel) response = openai.Image.create( prompt=ideel, n=1, size="1024x1024") image_url = response['data'][0]['url'] print(image_url) print(" ") await ctx.send(image_url)
不工作的代码
@slash.slash(name="gen")async def gen(ctx, *, ideasl): print("slash: " + ideasl) response = openai.Image.create( prompt=ideasl, n=1, size="1024x1024") image_urll = response['data'][0]['url'] print(image_urll) print(" ") await ctx.send(image_urll)
控制台
reg: dog cathttps://oaidalleapiprodscus.blob.core.windows.net/private/org-C8Nv06yDvE0bz1w78n80B2a9/user-rzBkmNENqDdD8oHXFf9VWfNh/img-6mmEETlF8a5bA7B4hUI46nSE.png?st=2022-11-12T14%3A22%3A00Z&se=2022-11-12T16%3A22%3A00Z&sp=r&sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2022-11-11T23%3A38%3A17Z&ske=2022-11-12T23%3A38%3A17Z&sks=b&skv=2021-08-06&sig=6MuyNRj6MDOalZLJOD9/1TwX2KbJAJJSCsMvRqgaC5c%3D slash: dog cathttps://oaidalleapiprodscus.blob.core.windows.net/private/org-C8Nv06yDvE0bz1w78n80B2a9/user-rzBkmNENqDdD8oHXFf9VWfNh/img-bUNRJwcIjhFcYf3xywxE96Aw.png?st=2022-11-12T14%3A22%3A31Z&se=2022-11-12T16%3A22%3A31Z&sp=r&sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2022-11-12T03%3A02%3A46Z&ske=2022-11-13T03%3A02%3A46Z&sks=b&skv=2021-08-06&sig=cAOqhtWoe5VIq0ITY0%2BPhBRUZb%2BsLj%2BVy%2BarZe9OHsk%3D An exception has occurred while executing command `gen`:Traceback (most recent call last): File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_slash/client.py", line 1352, in invoke_command await func.invoke(ctx, **args) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_slash/model.py", line 210, in invoke return await self.func(*args, **kwargs) File "main.py", line 42, in gen await ctx.send(image_urll) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_slash/context.py", line 256, in send await self._http.post_initial_response(json_data, self.interaction_id, self._token) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 243, in request raise NotFound(r, data)discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
代码中工作的斜杠命令示例
@slash.slash(name="modapp")async def enbed(ctx: SlashContext): embed = Embed(title="Mod Applications.", url="https://www.youtube.com/watch?v=QB7ACr7pUuE", description="Click above to apply for mod.") await ctx.send(embed=embed)
我尝试运行了这两个命令,除了斜杠命令的图像返回外,其他一切正常。
完整代码
import discordimport randomimport osimport openaiimport jsonimport mathfrom discord.ext import commands, tasksfrom itertools import cyclefrom random import choicefrom math import pifrom keep_alive import keep_alivefrom discord import Client, Intents, Embedfrom discord_slash import SlashCommand, SlashContextopenai.api_key = os.getenv("teken")openai.Model.list()client = commands.Bot(command_prefix = '+',intents=Intents.default())status = cycle(['with life','with death'])slash = SlashCommand(client, sync_commands=True)#斜杠命令@slash.slash(name="modapp")async def enbed(ctx: SlashContext): embed = Embed(title="Mod Applications.", url="https://www.youtube.com/watch?v=QB7ACr7pUuE", description="Click above to apply for mod.") await ctx.send(embed=embed)@slash.slash(name="sus")async def simp(ctx: SlashContext): image="index.jpg" await ctx.send(file=discord.File(image)) @slash.slash(name="gen")async def gen(ctx, *, ideasl): print("slash: " + ideasl) response = openai.Image.create( prompt=ideasl, n=1, size="1024x1024") image_urll = response['data'][0]['url'] print(image_urll) print(" ") await ctx.send(image_urll) #事件@client.eventasync def on_ready(): change_status.start() print('我们已作为 {0.user} 登录'.format(client)) print(" ")@client.eventasync def on_command_error(ctx, error): if isinstance(error, commands.MissingRequiredArgument): await ctx.send('请输入所需的参数!') elif isinstance(error, commands.MissingPermissions): await ctx.send("请不要欺骗系统!")#任务@tasks.loop(seconds=10)async def change_status(): await client.change_presence(activity=discord.Game(next(status)))#命令@client.command()async def ping(ctx): await ctx.send(f'Pong! {round(client.latency * 1000)}ms')@client.command()async def hello(ctx): await ctx.send('嗨!')@client.command(aliases=['8ball'])async def _8ball(ctx, *, question): responses = ['绝对', '可能', '绝对不可能'] await ctx.send(f'问题: {question}\n回答: {random.choice(responses)}') print (f'问题: {question}') print(" ")@client.command(aliases=['gen'])async def genimage(ctx, *, ideel): print("reg: " + ideel) response = openai.Image.create( prompt=ideel, n=1, size="1024x1024") image_url = response['data'][0]['url'] print(image_url) print(" ") await ctx.send(image_url)@client.command()async def roll(ctx, *, dicesize): await ctx.send(f'你掷了一个d{dicesize}\n你得到了{random.randint(1,int(dicesize))}')@client.command()async def calculator(ctx): await ctx.send('https://replit.com/@Hoadi605/Calculator#main.py')@client.command()async def testss(ctx): await ctx.send('这是一个Rickroll')@client.command()async def idea(ctx, *,idean): ideeees = open('ideaas.txt', 'a+') ideeees.write(f'{idean}\n') ideeees.close@client.command()async def ideas(ctx): ideeees = open('ideaas.txt', 'r') cheeese = ideeees.read() await ctx.send(cheeese) ideeees.close@client.command()async def pylearn(ctx): await ctx.send('https://www.youtube.com/watch?v=rfscVS0vtbw&t=615s')#移动@client.command()async def start_move(ctx): move_them.start()@client.command()async def stop_move(ctx): move_them.stop()@tasks.loop(seconds=10)async def move_them(): await client.move_member(next('336185999824650242', '801605503250595844'))keep_alive()client.run(os.getenv('TOKEN'))
回答:
你必须在3秒内对交互做出响应,否则命令将失败。如果响应时间较长,因为你在进行一些缓慢/密集的操作——比如使用AI生成图像,或进行API调用——你可以使用defer
。延迟告诉Discord“我已经接收到交互,但我稍后会响应”。
注意:这个代码块适用于discord.py,而不是discord_slash
,因为我从未使用过它。然而,理念是完全相同的,你只需在文档中查找函数名称即可。
# 延迟应该是你做的第一件事await interaction.response.defer()here_be_slow_thing()# 当你的计算完成时响应await interaction.followup.send_message("...")
附注:没有必要使用discord_slash
或任何类似的东西,交互和斜杠命令已经内置于discord.py
中,你会发现官方解决方案有更多的文档/示例/帮助。