在 on_message 函数外部调用的变量无法在函数内部引用

Variable when called outside of an on_message function is not able to be referenced inside the function

我正在尝试创建一个名为 "saynum" 的代码,其参数为 amount(这是一个自然数。)该命令的工作方式是计算自您 运行命令,并将号码发送到discord。不过我有一个障碍。当尝试 运行 一个 async def on_message(message) (当然有 @bot.event )并调用它之外的变量时,我无法从 on_message 函数外部引用变量.有解决方法吗?这个问题可能会被否决。

如果没有解决方法,那么该命令是否可以工作?我不知道如何以另一种方式处理它。

这是我使用的代码:

import discord
from discord.ext import commands
import random
import sys
import traceback


Client = discord.Client()
client = commands.Bot(command_prefix='~', case_insensitive=True)
client.remove_command("help")

@client.command()
async def saynum(ctx, amount):
    num = 0
    if amount.isdigit():
        if int(amount) < 1:
            await ctx.send("Please put an integer greater than 1.")
        else:
    @client.event
    async def on_message(message):
        num += 1
        await ctx.send(num)

哦,最后一件事。我的 python 版本是 3.6.6,我正在使用 discord.py rewrite if you couldn't tell.

num += 1 行上方放置 nonlocal num
这让 python 知道变量的范围(在本例中为外部)