问题是,当您在函数中命名变量时,它不会传递给其他函数。因此变量voicebot
不会传递给其他函数(用于使bot离开或对话)
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=commands.when_mentioned_or("~"),intents=intents, owner_id=587573816360960022)
...Other functions...
@bot.command(name='join', help='Joins the voice channel you are in')
async def JoinVoiceofAuthor(ctx):
vchannel = ctx.message.author.voice
if vchannel != None:
if "voicebot" not in globals():
global voicebot
voicebot = await vchannel.channel.connect()
else:
if voicebot.is_connected():
return
if vchannel != None:
voicebot = await vchannel.channel.connect()
await ctx.send('Joining you, '+str(ctx.message.author.mention)+', in voice channel "'+str(vchannel.channel)+'"')
else:
await ctx.send('Sorry,'+str(ctx.message.author.mention)+', you are not in a voice channel')
...Other functions...
我试着把voicebot
变成一个全局变量,但发现不能从函数中更改全局变量。
所以我的下一个想法是让机器人成为一个类:
class TheBot(commands.Bot):
def __init__(self):
intents = discord.Intents.all()
super().__init__(intents=intents, command_prefix='~', owner_id=587573816360960022)
members = inspect.getmembers(self)
for name, member in members:
if isinstance(member, commands.Command):
if member.parent is None:
self.add_command(member)
...Other functions...
@commands.command(name='join', help='Joins the voice channel you are in')
async def JoinVoiceofAuthor(self, ctx):
vchannel = ctx.message.author.voice
if vchannel != None:
if "voicebot" not in globals():
self.voicebot = await vchannel.channel.connect()
else:
if self.voicebot.is_connected():
return
if vchannel != None:
self.voicebot = await vchannel.channel.connect()
await ctx.send('Joining you, '+str(ctx.message.author.mention)+', in voice channel "'+str(vchannel.channel)+'"')
else:
await ctx.send('Sorry,'+str(ctx.message.author.mention)+', you are not in a voice channel')
...Other functions...
但这也不起作用,因为上下文也被传递给了self
,而不是ctx
有人能解决这个问题吗
如果要更改函数的全局变量,必须在函数内部使用global关键字:
discord.py中的一个实现是:
正如Parasol Kirby所说,您需要使用
global
关键字。为了适应您的情况,我们需要做一些更改要使
voicebot
变量成为全局变量,只需在命令顶部添加global voicebot
。这样,您就可以从每个函数中使用这个变量然后,为了检查bot是否已经连接到语音通道,我们不需要使用
voicebot
变量。如果bot位于如下语音通道中,则可以创建一个返回True
的函数:现在,要检查bot是否没有从命令中连接到语音通道,只需使用
is_connected
函数并在上下文中“传入”因此,完整代码如下所示:
相关问题 更多 >
编程相关推荐