如何解决Discord bot python 数学
我试图在我的不和谐机器人中制作一个简单的计算器,但它不起作用, 它给出了一个错误。
顺便说一句,我使用的是 discord.py(discord bot 是用 python 编写的)
有人可以帮我吗?
这是我的代码
@bot.command()
async def calc(ctx):
await ctx.send("Number 1: ")
number_1 = await bot.wait_for("message" )
await ctx.send("Operator: ")
operator = await bot.wait_for("message" )
await ctx.send("number 2: ")
number_2 = await bot.wait_for("message" )
number_1 = float(number_1)
number_2 = float(number_2)
ouput = none
if operator == "+":
ouput = number_1 + number_2
elif operator == "-":
output = number_1 - number_2
elif operator == "/":
output = number_1 / number_2
elif operator == "*":
output = number_1 * number_2
else :
ctx.send(f"invalid input")
ctx.send(f"Answer: " + str(output))
解决方法
你误解了一些事情:
-
wait_for
函数需要check
来查看您等待的东西是否是您得到的东西, -
number_1
,number_2
&operator
将是消息对象而不是消息内容,因此您必须从该对象中获取content
属性, - 在您的代码变量中,
output
有时是名称ouput
,而您将none
分配给它,这是完全错误的,它应该是带有大写字母的None
,立> - 你最后的两个
ctx.send()
一开始没有await
- 您必须在输入无效后
return
,否则机器人无论如何都会发送“答复消息” - 您的代码中有一些不必要的
f"strings"
我想就是这样。您的代码应如下所示:
@bot.command()
async def calc(ctx):
def check(m):
return len(m.content) >= 1 and m.author != bot.user
await ctx.send("Number 1: ")
number_1 = await bot.wait_for("message",check=check)
await ctx.send("Operator: ")
operator = await bot.wait_for("message",check=check)
await ctx.send("number 2: ")
number_2 = await bot.wait_for("message",check=check)
try:
number_1 = float(number_1.content)
operator = operator.content
number_2 = float(number_2.content)
except:
await ctx.send("invalid input")
return
output = None
if operator == "+":
output = number_1 + number_2
elif operator == "-":
output = number_1 - number_2
elif operator == "/":
output = number_1 / number_2
elif operator == "*":
output = number_1 * number_2
else:
await ctx.send("invalid input")
return
await ctx.send("Answer: " + str(output))
另外 - 你在那里犯了一些非常类似于初学者的错误,首先你应该学习 python 的基础知识,而不是尝试编写一个不和谐的机器人。我知道这很酷,但当你真正知道自己在做什么时会更有趣。
,这是一种更简单的制作计算器的方法
import sympy
import numpy
@bot.command()
async def calc(ctx,arg): #arg is desired calculation(since this code is simple make sure u dont leave any spaces
answer=N(arg) #this will calculate the result
ans=np.format_float_positional(answer,trim='-') #this will remove extra zeros from float
tu=discord.Embed(title='{0}={1}'.format(arg,ans),color=0XEDAF65)
await ctx.send(embed=tu)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。