1

我正在尝试创建一个使用 asyncio 的不和谐机器人。我不懂大部分语法,比如@的使用或异步本身,所以请原谅我的无知。我不知道如何在谷歌中表达这个问题。

import discord
from discord.ext.commands import Bot
from discord.ext import commands

Client = discord.Client()

bot_prefix = "&&"

client = commands.Bot(command_prefix=bot_prefix)

@client.event
async def on_ready():
    print("Bot online")
    print("Name:", client.user.name)
    print("ID:", client.user.id)

@client.command(pass_context=True)
async def ToggleSwitch(ctx):
    theSwitch = not theSwitch

@client.event
async def on_message(message):
    await client.process_commands(message)
    if message.author.id == "xxxxx" and theSwitch == True:
        await client.send_message(message.channel, "Switch is on and xxxxx said something")

我稍微过分简化了这个问题,但我想了解的是如何将theSwitch变量从ToggleSwitch函数传递on_message给外部数据库?)。

再次抱歉,我很抱歉,但我真的很想解决这个问题,因为我真的受到这个问题的影响。

4

1 回答 1

1

变量范围

在这种情况下,您希望使用全局范围 for theSwitch,这意味着可以从任何地方访问该变量。定义一个全局变量很简单;之后Client = discord.Client()(另外,您应该将其client用作变量名),放置theSwitch = True(或False)。

然后,在ToggleSwitch(应该命名为toggleSwitch...):

@client.command(pass_context=True)
async def ToggleSwitch(ctx):
    global theSwitch
    theSwitch = not theSwitch

请注意,您需要指定全局范围,否则默认情况下会创建一个新的局部变量。

on_message,您现在可以访问theSwitch(尽管在这里声明全局范围也很好,但除非您修改theSwitch,否则这不是绝对必要的,您不应该这样做)。请注意,此方法不一定适用async于两个事件同时发生的奇怪情况,但无论如何都会导致未定义的行为。

于 2017-09-26T00:34:04.453 回答