首页 > 解决方案 > discord.py 不执行数学/python 代码

问题描述

我有这个兼作 python 命令的数学代码,我希望它解决数学问题。当我说p!math 3+13时,它应该发送 16,但它会将问题 (3+13) 发送回用户。有人可以帮忙吗?

@client.command()
async def math(ctx, *, p):
    try:
        exec(p)
        await ctx.send(p)
    except Exception as e:
        await ctx.send(f"```python\nError: {e}```")

标签: pythondiscord.py

解决方案


您使用了不正确的功能。不要使用 exec,而是使用 eval。此外,您应该将返回值设置为参数并将其返回。

例如:

@client.command()
async def math(ctx, *, p):
    try:
        answer = eval(p)
        await ctx.send(answer)
    except Exception as e:
        await ctx.send(f"```python\nError: {e}```")

推荐阅读