I am current trying to make a Discord bot that joins VC when a certain person joins and then leaves VC when they leave.
The bot should ONLY be in VC when the specific user is in VC, and then leave instantly when said user disconnects.
The problem I am having is trying to figure out how to make the bot detect the user leaving and leave.
@bot.event
async def on_voice_state_update(member, before, after):
targetID = bot.get_user(USERID)
if after.channel is not None and member.id == targetID.id:
await member.voice.channel.connect()
This is what I use to make the bot join the VC and there seem to be no issues, but no matter what I try I cannot figure out how to make the bot leave once the said user leaves VC.
Any help is appreciated, thank you.
Any time i’ve been able to make the bot leave, it leaves the instant is joins, I know the reason for this but I just cant figure out how to prevent it, or do it another way to make the bot only leave when the user leaves.
RS F is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
- Your
bot.get_user(USERID)
returned a NoneType, which would of course not have an ID to compare with themember.id
. So, I usedawait
withbot.fetch_user
. But if it works on your end, then that’s that. - Because getting the id of the user didn’t work for me, I stuck to comparing the user objects.
- The actual answer to your question is as simple as using a list to store the VC the user joins, and then exiting from the VC when they leave. The reason why you need a list is because there isn’t a way (at least that I know of) to find the last VC a user was in. Having a list also means that you could potentially make the code watch for multiple people in different VCs.
Here’s my code:
VCs = {} #VC list
@bot.event
async def on_voice_state_update(member, before, after):
target = await bot.fetch_user(USERID)
if after.channel is not None and member == target:
VCs[member.id] = member.voice.channel
await member.voice.channel.connect()
elif after.channel is None and member == target:
for i in bot.voice_clients: #Check through all VCs bot is currently in
if i.channel == VCs[member.id]: #If VC is the one the user was in
VCs.pop(member.id) #Remove the VC from the list
await i.disconnect(force=False) #Disconnect from the VC