【发布时间】:2020-05-14 16:54:49
【问题描述】:
当特定用户移动到 afk 语音通道时,我正在尝试播放 mp3 文件。
在 discord.py 中重写:
async def on_voice_state_update(member, before, after):
user = bot.get_user("my user id")
if after.afk and user == True:
channel = bot.get_channel("the id of the channel I want the bot to connect to")
voice = await channel.connect()
voice.play(discord.FFmpegPCMAudio('directory of mp3 file'))
await asyncio.sleep(7)
await voice.disconnect()
问题
在我尝试在 if 语句中指定用户之前,这一切都有效:
user == True
但是,一旦我包含此要求,它就会停止工作。
我的尝试
我试图给用户对象一个属性,例如user.connect == True 和user.joined == True 等...但没有运气。
目标
在其完善的形式中,我不仅可以指定加入 afk 频道以使活动正常工作所需的用户,还可以获取另一个用户的频道 ID,以便机器人可以连接到该频道:
channel = bot.get_channel("the id the channel that a specified user is in")
编辑:
根据 Diggy 的回答,我将 if 语句更改为如下所示:
async def on_voice_state_update(member, prev, cur):
if member.id == 'my user id' and cur.afk:
channel = bot.get_channel('the channel id for the bot to connect to')
voice = await channel.connect()
voice.play(discord.FFmpegPCMAudio('dir of mp3 file'))
await asyncio.sleep(7)
await voice.disconnect()
else:
pass
但是,一旦我离开频道,它也会播放音频。
我尝试使用if member.id == 'my user id' and cur.afk and not prev.afk 指定一旦我离开频道就不会播放,但在我离开时它仍然会播放。
实验解决方案:
好的,所以我想让它只加入上一个频道,所以一旦我离开 afk 频道,它就会在没有问题的地方播放它。这使它可以在 afk 之前的频道中工作和播放,这很棒,但并不完美。它应该不需要加入 afk 频道:
async def on_voice_state_update(member, prev, cur):
if member.id == 'my user id' and cur.afk:
prevchannel = prev.channel.id
channel = bot.get_channel(prevchannel)
voice = await channel.connect()
voice.play(discord.FFmpegPCMAudio('dir to mp3 file'))
await asyncio.sleep('duration of mp3 file')
await voice.disconnect()
else:
pass
我认为 elif 可能会像这样工作:
elif prev.afk is not None and cur.afk is None:
pass
但它几乎只是忽略它。
-prev 和 cur 参数有时也不起作用,所以我必须切换回 before 和 after
【问题讨论】:
标签: python discord discord.py discord.py-rewrite