I am trying to make my discord.py bot disconnect 10 seconds after it has joined. So far I can make it join, play the audio file but not yet leave after a set amount of seconds. I have a leave function that leaves, but I want to add it to the existing function that does everything
import discord
from discord.ext import commands
from discord.voice_client import VoiceClient
import youtube_dl
import time
TOKEN = 'mytoken'
intents = discord.Intents.default()
intents.members = True
players = {}
client = commands.Bot(command_prefix='.')
@client.event
async def on_ready():
print('bot online')
@client.command(pass_context=True)
async def leave(ctx):
server = ctx.message.guild.voice_client
await server.disconnect()
@client.event
async def on_voice_state_update(member, before, after):
if not before.channel and after.channel and member.id == 227490621084925953:
channel = client.get_channel(967887213939523584)
await channel.send('KARAN IS HERE')
voiceChannel = client.get_channel(821051726899052624)
vc = await voiceChannel.connect()
vc.play(discord.FFmpegPCMAudio(r"C:UsersAmarnOneDrive - Da Vinci CollegeDa Vinci Collegesoftware_developenAssignmentsjaar_1periode_1own_projectsdiscordpunjabi.mp3"), after=lambda e: print('done', e))
time.sleep(10)
leave()
client.run(TOKEN)
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can’t call the command after you’ve decorated it. The closest you can get is using invoke, but that requires creating context.
Instead, just inline it. You can get the guild from the member that the voice state update is about. Instead of doing leave(), which is invalid, you can do:
await member.guild.voice_client.disconnect()
Method 2
The leave function requires that it be called inside the guild (using .leave). What you need to do is not call leave() in your on_voice_state_update.
The VoiceChannel#connect function returns a VoiceProtocol object. So, if you use await vc.disconnect() instead of leave() it should work fine
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0