問題描述
我正在使用 discord.py 來制作 discord 機器人.我想在用戶提到的兩個數字之間生成一個隨機數.因此,如果用戶鍵入 %rand 1 9
,我希望機器人返回 1 到 9 之間的隨機整數,比如 4.到目前為止,這是我的代碼:
I am using discord.py to make a discord bot. I would like to generate a random number between 2 numbers mentioned by the user. So if the user types %rand 1 9
, I would like the bot to return with a random integer between 1 and 9, so say 4.
Here is my code so far:
async def on_message(message):
x = str(1)
y = str(2)
if message.content.startswith('%rand ' + x + y):
NumberX = int(x)
NumberY = int(y)
msg = "Random Number Is: " + str(random.randint(NumberX,NumberY))
await client.send_message(message.channel, msg)
但是,它不起作用.我不太明白我哪里出錯了.我在其他任何地方都找不到其他解決方案.我想我需要強制機器人閱讀完整的消息或類似的東西.任何幫助將不勝感激.提前謝謝你.
However, it doesn't work. I don't quite understand where I am going wrong. I couldn't find another solution anywhere else. I assume I need to force the bot to read the full message or something similar. Any help will be appreciated. Thank you in advance.
推薦答案
問題在于您的 if 語句從未真正觸發過.您正在檢查它是否以%rand 12"開頭,這不是您想要的.你的代碼應該是這樣的:
The problem comes from the fact that your if statement is never actually triggered. You are checking whether it starts with "%rand 12" which is not what you are looking for. Here's how your code should look:
async def on_message(message):
if message.content.startswith('%rand '):
vals = message.content.split(" ")
NumberX = int(vals[1])
NumberY = int(vals[2])
msg = "Random Number Is: " + str(random.randint(NumberX,NumberY))
await client.send_message(message.channel, msg)
另外,不要忘記 import random
以使用該功能.
Also, don't forget to import random
in order to use that function.
這篇關于Python discord.py 閱讀全文的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!