Python(Discord Bot):将你的参数传递给一个函数
Python (Discord Bot): Passing your argument to a function
我正在尝试创建一个使用 asyncio 的 discord 机器人。
我不明白大部分语法,比如 @ 的使用或 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
,或者至少传递一个让我自己拥有可以在整个代码中无缝访问的变量的方法(也许通过连接到外部数据库?)。
再次抱歉给您带来的麻烦,但我真的很想解决这个问题,因为我真的被这个问题困扰了。
变量作用域
在这种情况下,您希望对 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
,但无论如何都会导致未定义的行为。
我正在尝试创建一个使用 asyncio 的 discord 机器人。 我不明白大部分语法,比如 @ 的使用或 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
,或者至少传递一个让我自己拥有可以在整个代码中无缝访问的变量的方法(也许通过连接到外部数据库?)。
再次抱歉给您带来的麻烦,但我真的很想解决这个问题,因为我真的被这个问题困扰了。
变量作用域
在这种情况下,您希望对 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
,但无论如何都会导致未定义的行为。