python - 全局变量不起作用或类似的东西...... discord.py
问题描述
嘿,所以我最近开始制作一个不和谐的机器人。一切都很顺利,我切换到 cogs bla bla yea,现在我正在尝试制作一个可切换的反广告命令。我使用全局变量来切换。代码是:
bruh = 'off'
@commands.Cog.listener()
async def on_message(self, message):
global bruh
if "discord.gg" in message.content.lower():
if bruh == 'on':
await message.delete()
await message.channel.send("Don't advertise your server!")
@commands.command()
async def anti_add(self, ctx):
if bruh == 'off':
bruh = 'on'
await ctx.send('Ads Detector has been Enabled.')
return bruh
else:
bruh = 'off'
await ctx.send('Ads Detector has been Disabled.')
return bruh
因为我看起来没有理由让它不工作,但它
会这样做https://prnt.sc/1sozw7t
...它说"bruh" is not defined Pylance (reportUndefinedVariable)
当我将鼠标悬停在 bruh 上if bruh == 'off:
或者if bruh == 'on'
如果有人可以帮助我会非常感激。
解决方案
在第二个函数中再次使用 global,将其更改为:
@commands.command()
async def anti_add(self, ctx):
global bruh
if bruh == 'off':
bruh = 'on'
await ctx.send('Ads Detector has been Enabled.')
return bruh
else:
bruh = 'off'
await ctx.send('Ads Detector has been Disabled.')
return bruh