Python(Discord Bot):将您的参数传递给函数

时间:2017-09-26 00:01:33

标签: python discord.py

我正在尝试创建一个使用asyncio的discord bot。 我不理解大多数语法,比如使用@或async本身,所以请原谅我的无知。我不知道如何在Google中说出这个问题。

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,或者至少是我自己有变量可以在整个代码中无形地访问(也许通过连接到外部数据库?)。

再一次,对于这种说法感到抱歉,但我真的想把这个放在一边,因为我真的被这个问题所困扰。

1 个答案:

答案 0 :(得分:1)

变量范围

在这种情况下,您希望使用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,否则不一定非常必要。 T)。请注意,在奇怪的情况下,此方法不一定适用于async两个事件恰好同时发生,但无论如何都会导致未定义的行为。