Discord bot not joining a voice channel (python) - python

I'm trying to connect my discord bot to a voice channel, but it's not working.
There isn't any error or anything, nothing happens when I do !join on my discord channel.
Here is my code. I tried looking for some tutorials, but most seems outdated.
Could someone help me?
import discord
from discord.ext import commands
from discord.utils import get
import os
token = os.environ.get('DISCORD_TOKEN')
client = commands.Bot(command_prefix='!')
#client.command(pass_context=True)
async def join(ctx):
channel = ctx.message.author.voice.channel
voice = get(client.voice_clients, guild=ctx.guild)
if voice and voice.is_connected():
await voice.move_to(channel)
else:
voice = await channel.connect()
await ctx.send(f'Joined {channel}')
client.run(token)
Edit:
import discord
from discord.ext import commands
from discord.utils import get
import os
import youtube_dl
token = os.environ.get('DISCORD_TOKEN')
client = commands.Bot(command_prefix='!')
#client.event
async def on_message(message):
channels = ['bot-commands']
if str(message.channel) in channels:
if message.content == '!help':
embed = discord.Embed(title='How to use the ImposterBot', description='Useful Commands')
embed.add_field(name='!help', value='Display all the commands')
embed.add_field(name='!music', value='Play a music playlist')
embed.add_field(name='!valorant', value='Get the most recent version of Valorant stats')
embed.add_field(name='!hello', value='Greet a user')
await message.channel.send(content=None, embed=embed)
elif message.content == '!hello':
await message.channel.send(f'Greeting, {message.author}!')
elif message.content == '!valorant':
await message.channel.send('This feature is not ready yet')
elif message.content == '!music':
await message.channel.send('This feature is not ready yet')
elif 'sustin' in message.content:
await message.channel.send(f"""it's sustin... {"<:monkas:392806765789446144>"} """)
#client.command(pass_context=True)
async def join(ctx):
channel = ctx.message.author.voice.channel
voice = get(client.voice_clients, guild=ctx.guild)
if voice and voice.is_connected():
await voice.move_to(channel)
else:
voice = await channel.connect()
await ctx.send(f'Joined {channel}')
client.run(token)

The error in this code is that commands will not be invoked by the bot if there is an on_message event, unless that event begins with this line:
async def on_message(message):
await bot.process_commands(message)

Related

Discord.py bot doesn't play wav/mp3 file

import discord
from discord.ext import commands
from discord import FFmpegPCMAudio
import requests
import json
from apikeys import *
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix = '!', intents=intents)
#client.event
async def on_ready():
print("The bot is now ready for use!")
print("-----------------------------")
#client.command(pass_context = True)
async def join(ctx):
if (ctx.author.voice):
channel = ctx.message.author.voice.channel
voice = await channel.connect()
source = FFmpegPCMAudio("song.wav")
player = voice.play(source)
else:
await ctx.send("You are not in a voice channel")
#client.command(pass_context = True)
async def leave(ctx):
if (ctx.voice_client):
await ctx.guild.voice_client.disconnect()
await ctx.send("I left the voice channel")
else:
await ctx.send("I am not in a voice channel")
client.run(BOTTOKEN)
Hey! I have recently started watching a tutorial series.
It works for the tutorial maker, but doesn't for me.
The bot is able to join the voice channel the user is in, but never starts playing "song.wav".
Sadly Visual Studio Code also doesn't output any Error messages.
Does anyone know a solution?

Need help discord bot command

I just started learning python recently and never coded a discord bot before. I've been trying to get the bot to connect to the voice or respond to ">hello", but it doesn't respond to my command and I don't know how to fix it. I'm using replit as hosting.
import discord
import os
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix = '>', intents=intents)
#client.event
async def on_ready():
print('Log in as {0.user}'.format(client))
print('-------------------')
#client.command()
async def hello(ctx):
await ctx.send("Hello Im Deemo Bot")
#client.command(pass_context = True)
async def join(ctx):
if (ctx.author.voice):
channel = ctx.message.author.voice.channel
await channel.connect()
else:
await ctx.send('You are not in a voice channel')
#client.command(pass_context = True)
async def leave(ctx):
if (ctx.voice_client):
await ctx.guild.voice_client.disconnect()
await ctx.send('Deemo left voice')
else:
await ctx.send('Deemo is not in voice')
keep_alive()
client.run(os.environ['TOKEN'])

I am trying to make a bot that plays an mp3 file by a command but it doesn't work with no error

I made so it connects to the voice channel by the command .join and it supposed to play a sound that i saved. This is made for a voice channel with chill music so that they don't have to copy and paste a YouTube link. I am using python 3.9
import discord
from discord.ext import commands
bot = discord.Client()
bot = commands.Bot(command_prefix=".")
#bot.command()
async def join(ctx):
if ctx.author.voice is None:
await ctx.send("You are not in a voice channel")
voice_channel = ctx.author.voice.channel
if ctx.voice_client is None:
await voice_channel.connect()
guild = ctx.guild
voice_client: discord.VoiceClient = discord.utils.get(bot.voice_clients, guild=guild)
audio_source = discord.FFmpegPCMAudio('music.mp3')
if not voice_client.is_playing():
voice_client.play(audio_source, after=None)
else:
await ctx.voice_client.move_to(voice_channel)
bot.run("token")
Try this instead:
import discord
from discord.ext import commands
from youtube_dl import YoutubeDL
bot = discord.Client()
bot = commands.Bot(command_prefix=".")
#bot.command()
async def join(ctx):
if ctx.author.voice is None:
await ctx.send("You are not in a voice channel")
return
voice_channel = ctx.author.voice.channel
if ctx.voice_client is None:
await voice_channel.connect()
else:
await ctx.voice_client.move_to(voice_channel)
audio_source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio('music.mp3'))
if not ctx.voice_client.is_playing():
ctx.voice_client.play(audio_source, after=lambda e: print('Player error: %s' % e) if e else None)
bot.run("token")

How to check is discord bot is in voice or already connected

I am building a bot where the bot needs to connect to a voice channel, here is my code:
import discord
from discord.ext import commands
from discord.utils import get
b = commands.Bot(command_prefix=".")
#b.event
async def on_ready():
print("Bot is logged in")
#b.command(pass_context=True, aliases=['j'])
async def join(ctx):
channel = ctx.message.author.voice.channel
voice = get(b.voice_clients, guild=ctx.guild)
if voice and voice.is_connected():
await voice.move_to(channel)
await ctx.send("Moved to the voice channel")
elif #Check if the user is in the voice channel and the bot is not:
voice = await channel.connect()
await ctx.send("Connected to the voice channel")
elif #Check if the user is in the voice channel
await ctx.send("**Get in a voice channel**")
elif #Check if the bot is already in the channel
await ctx.send("**Already in the channel**")
b.run("stack overflow")
So there's a couple things I want to check before entering the voice channel, I figured out how to connect and to move from different voice channel but am stuck there, I'm new to python so if my code can be simplified any suggestions would be much appreciated.
#b.command(aliases=['j'])
async def join(ctx):
bot_voice = ctx.guild.voice_client
author_voice = ctx.author.voice
if bot_voice and bot_voice.is_connected():
await voice.move_to(author_voice.channel)
await ctx.send("Moved to the voice channel")
elif author_voice and not bot_voice: # Author connected but bot not connected
voice = await author_voice.channel.connect()
await ctx.send("Connected to the voice channel")
elif not author_voice: # Author not connected
await ctx.send("**Get in a voice channel**")
elif ctx.bot.user in author_voice.channel.members # Bot and Author both connected
await ctx.send("**Already in the channel**")
btw pls don't name your bot b, it's bad practice

Discord.py error : object NoneType can't be used in "await" expression when trying to make the bot leave a voice channel

I'm currently trying to code a discord bot in python and am trying to make it join a channel, play a sound and then leave.
I came up with this code :
#bot.command()
async def sound(ctx):
channel = ctx.author.voice.channel
await join(ctx)
voice = get(bot.voice_clients, guild=ctx.guild)
source = FFmpegPCMAudio('sound.mp3')
await voice.play(source)
await channel.disconnect()
However, when I try it, after playing the sound, it doesn't disconnect and there is in my shell an error :
discord.ext.commands.errors.CommandInvokeError: Command raised an
exception: TypeError: object NoneType can't be used in 'await'
expression
I saw on forums that it could be a asyncio problem but I don't know how to resolve it.
Could someone help me please ?
Edit : my imports on my program :
import discord
import asyncio
from discord.ext import commands
from discord.utils import get
from discord import FFmpegPCMAudio
Edit v2 : the join() command :
#bot.command(pass_context=True)
async def join(ctx):
channel = ctx.author.voice.channel
voice = get(bot.voice_clients, guild=ctx.guild)
if not channel:
await ctx.send("You are not in a vocal channel.")
return
if voice and voice.is_connected():
await voice.move_to(channel)
elif voice == channel:
return
else:
await channel.connect()
You can have your join command return the VoiceClient object and use it directly to play the sound instead of using discord.utils.get. You can also get the VoiceClient object directly from the bot.voice_clients list instead of using get when checking if the bot is connected to a voice channel already.
Note that voice.play does not need await as it is not a coroutine. You also need to check if the bot stops playing audio using while voice.is_playing() before disconnecting, otherwise it will disconnect immediately after starting to play the sound.
from discord.ext import commands
from discord import FFmpegPCMAudio
bot = commands.Bot(command_prefix='?')
#bot.command()
async def join(ctx):
channel = ctx.author.voice.channel
voice = None
for vc in bot.voice_clients:
if vc.guild == ctx.guild:
voice = vc
if not channel:
await ctx.send("You are not in a vocal channel.")
return
if voice and voice.is_connected():
vc = await voice.move_to(channel)
elif voice == channel:
return
else:
vc = await channel.connect()
return vc
#bot.command()
async def sound(ctx):
voice = await join(ctx)
source = FFmpegPCMAudio('sound.m4a')
voice.play(source)
while voice.is_playing():
continue
await voice.disconnect()
bot.run('token')
The
while voice.is_playing():
continue
await voice.disconnect()
will mess up the audio.
Do this instead:
while voice.is_playing():
time.sleep(1)

Categories