You can do both of these commands (the join and leave channel commands) in two ways, one is by using on_message, and the other is by using @bot.commands. It's is best to use bot.command instead of on_message for commands as bot.commands has more features plus I think it's fast after all it was built for commands. So I'll rewrite both of your commands using bot.command and also put using on_message there incase you don't want to use bot.command.
According to your message, I'm assuming ?
is your prefix
Using on_message
@bot.event
async def on_message(message):
if (message.content.startswith('?join')):
if (message.author.voice): # If the person is in a channel
channel = message.author.voice.channel
await channel.connect()
await message.channel.send('Bot joined')
else: #But is (s)he isn't in a voice channel
await message.channel.send("You must be in a voice channel first so I can join it.")
elif message.content.startswith('?~'): # Saying ?~ will make bot leave channel
if (message.guild.voice_client): # If the bot is in a voice channel
await message.guild.voice_client.disconnect() # Leave the channel
await message.channel.send('Bot left')
else: # But if it isn't
await message.channel.send("I'm not in a voice channel, use the join command to make me join")
await bot.process_commands(message) # Always put this at the bottom of on_message to make commands work properly
Using bot.command
@bot.command()
async def join(ctx):
if (ctx.author.voice): # If the person is in a channel
channel = ctx.author.voice.channel
await channel.connect()
await ctx.send('Bot joined')
else: #But is (s)he isn't in a voice channel
await ctx.send("You must be in a voice channel first so I can join it.")
@bot.command(name = ["~"])
async def leave(ctx): # Note: ?leave won't work, only ?~ will work unless you change `name = ["~"]` to `aliases = ["~"]` so both can work.
if (ctx.voice_client): # If the bot is in a voice channel
await ctx.guild.voice_client.disconnect() # Leave the channel
await ctx.send('Bot left')
else: # But if it isn't
await ctx.send("I'm not in a voice channel, use the join command to make me join")