首页 > 解决方案 > 如何从命令 discord.py 更改变量

问题描述

这是我在 Stacked Overflow 上的第一篇文章,我找到了几乎所有我遇到的编码问题的答案。但是我没有找到解决这个问题的任何帮助:我制作了一个机器人,我想使用不和谐的命令来更改一个变量,如下所示: !test 1 然后将更改一个要测试的变量,这是我的代码:

@client.command()
async def test(ctx, variable):
  print(variable)
  await ctx.send(variable)

任何帮助将不胜感激:D

标签: pythondiscord.py

解决方案


您需要创建一个全局变量或机器人属性并对其进行编辑

# Global Var
var = None

@client.command()
async def test(ctx, variable):
  global var
  print("Before", variable)
  var = variable
  await ctx.send(var)


# Bot Attribute

@client.event
async def on_ready():
  print("Ready")
  client.var = None

@client.command()
async def test(ctx, variable):
  print("Before", client.var)
  client.var = variable
  await ctx.send(client.var)

推荐阅读