Discord.py问题:Bot指定频道设置后其他命令无法读取正确值
问题解决:Discord Bot全局变量无法正确更新
你的问题核心是变量作用域问题:在setChannel命令里,你重新定义了current_channel,这是个局部变量,根本没改动全局的那个初始值为100的current_channel,所以help命令读到的始终是初始值。
解决方法
在setChannel函数里用global关键字声明要操作全局变量,代码修改如下:
client.remove_command("help") current_channel = 100 # 占位初始值 @client.event async def on_ready(): print(f"{client.user} is now running") print("----------------------------------------------------------------") @client.command() async def setChannel(ctx): global current_channel # 声明使用全局变量 current_channel = ctx.channel.id await ctx.send("channel set to here.") await ctx.send(current_channel) @client.command() async def help(ctx): if ctx.channel.id != current_channel: await ctx.send("not correct channel, channel is set to") await ctx.send(current_channel) return else: await ctx.send("```insert help message here```") return
补充说明
加上global current_channel后,函数内的赋值操作会直接修改全局变量,而非创建新的局部变量,这样help命令就能读取到更新后的频道ID了。
如果你的Bot需要支持多服务器使用,全局变量就不够用了,建议用字典存储每个服务器的独立设置,比如:
server_channels = {} # 键:服务器ID,值:频道ID @client.command() async def setChannel(ctx): server_channels[ctx.guild.id] = ctx.channel.id await ctx.send("channel set to here.") @client.command() async def help(ctx): target_channel = server_channels.get(ctx.guild.id, 100) if ctx.channel.id != target_channel: await ctx.send(f"not correct channel, channel is set to {target_channel}") return await ctx.send("```insert help message here```")
内容的提问来源于stack exchange,提问作者akinoyuu
相关产品推荐
相关产品推荐

