我试图让我的discord bot使用webapi翻译一条消息,但是当我执行命令时,它只使用第一个参数(在空格之前),或者更改代码时,它只获得最后一个参数(在空格之后)
这是我的密码:
@bot.command(pass_context=False)
async def brus(ctx, args):
useragent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'
session = aiohttp.ClientSession(headers={'User-Agent': useragent})
yandexkey = 'secret key'
translatebrus = await session.get("https://translate.yandex.net/api/v1.5/tr.json/translate?text=" + args + "&lang=en&key=" + yandexkey)
translatebrusres = await translatebrus.json()
translateresult = str(translatebrusres['text'][0]) #here is where i get the translated response
embed4 = discord.Embed(title="BR-EN TRANSLATION", description=(translateresult), color=0x1aff00)
await bot.say("", embed=embed4) #i just use this to send the message already formatted to embed
await bot.say(translatebrusres) #unnecessary, just to see my response
await bot.say(translatebrus) #unnecessary, just to see my request
session.close()
以下是我对不和的回应: https://i.stack.imgur.com/SFWet.png
在图片上,你可以看到“mundo”是最后一个arg,翻译成英语的是“world”,但是“ola”是第一个args,它没有翻译
我试过使用*args、**kwargs、message和str,但没有得到任何更改 我在stackoverflow上看到过其他相关的帖子,但没有一个适合我
编辑: 使用修复它
@bot.command(pass_context=True) #It was pass context FALSE
async def brus(ctx, *, traduzir): #It was using args, was changed to custom arg name (traduzir) and added * before custom arg name to translate all arguments as just one (what i wanted to do)
#and changed the session get to this
translatebrus = await session.get(f"https://translate.yandex.net/api/v1.5/tr.json/translate?text={quote(traduzir)}&lang=pt-en&key=" + yandexkey #thanks Samuel, the quote was helpful, without quote it wont pass the arguments right to be json decoded.
就这样,希望我能帮助别人;)
我没有所有的信息来解决这个问题,但有几件事我怀疑:
a)指定
pass_context=False
,但是brus
函数的第一个参数是ctx
。是不是你总是无意中把第一个词放在ctx
里面?您可能需要使用调试器或打印ctx
和args
是什么。你知道吗b)Yandex documentation具有以下警告:
我怀疑您在“args”中收到的文本只是一个普通字符串,如
ola mundo
,因此您可能需要对其进行转义并使其成为URL安全的:如果a)确实是问题所在,我仍然建议您添加
quote()
步骤,否则大量的输入可能会破坏您的bot!你知道吗相关问题 更多 >
编程相关推荐