我该怎么做不和谐.py无法将多个参数识别为一个?

2024-10-04 01:25:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让我的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.

就这样,希望我能帮助别人;)


Tags: thetojsongetsessionbotcontextargs
1条回答
网友
1楼 · 发布于 2024-10-04 01:25:41

我没有所有的信息来解决这个问题,但有几件事我怀疑:

a)指定pass_context=False,但是brus函数的第一个参数是ctx。是不是你总是无意中把第一个词放在ctx里面?您可能需要使用调试器或打印ctxargs是什么。你知道吗

b)Yandex documentation具有以下警告:

Attention.

The source text must be URL-encoded.

我怀疑您在“args”中收到的文本只是一个普通字符串,如ola mundo,因此您可能需要对其进行转义并使其成为URL安全的:

>>> from urllib.parse import quote
>>> quote('This is the text')
'This%20is%20the%20text'

如果a)确实是问题所在,我仍然建议您添加quote()步骤,否则大量的输入可能会破坏您的bot!你知道吗

相关问题 更多 >