Command raised an exception: OpusNotLoaded: - python

I just started programming a discord bot with discord.py and everything is perfect.
Except one thing: I can't let the bot play music.
Here is my code:
#client.command(pass_context=True)
async def yt(ctx, url):
author = ctx.message.author
voice_channel = author.voice_channel
vc = await client.join_voice_channel(voice_channel)
player = await vc.create_ytdl_player(url)
player.start()
My error:
discord.ext.commands.errors.CommandInvokeError:
Command raised an exception:
OpusNotLoaded:
Why is it happening?

You need to use discord.opus.load_opus to load the Opus library.

Related

Discord Member Join

I'm creating a bot that when entering the server appears in a specific channel the name of the user who entered together with a message
I researched and made this code below but the same when I ran it didn't work and no error appeared, could you help me?
import discord
from discord.ext import commands
class Member(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.Cog.listener()
async def on_member_join(self, member):
try:
channel = self.bot.get_channel(Channel_ID)
try:
embed = discord.Embed(colour=discord.Colour.green())
embed.set_author(name=member.name, icon_url=member.avatar_url)
embed.add_field(name="Welcome" ,value=f"**Hey,{member.mention}! Welcome to {member.guild.name}\nI hope you enjoy your stay here!\nThanks for joining**", inline=False)
embed.set_thumbnail(url=member.guild.icon_url)
await channel.send(embed=embed)
except Exception as e:
raise e
except Exception as e:
raise e
def setup(bot):
bot.add_cog(Member(bot))
I found out what was going wrong in my code, python was not recognizing the "on_member_join" function and for it to work I needed to add this command
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot("!", intents=intents)
I added the same in the file that I run the bot, I did the test and it worked

Make a discord bot say something on voice channel

i couldn't find a solution for this so here i am.
I made a bot in discord.py rewrite for my discord server and i wanted to implement the feature where my bot says something when a user joins the voice channel.
I couldn't even make the bot join the voice chat because it gives every error possible. Thanks in advance.
These is what i tried:
#bot.command()
async def join_voice(self, ctx):
connected = ctx.author.voice
if connected:
await connected.channel.connect()
and this
#bot.command(pass_context=True)
async def join(ctx):
author = ctx.message.author
channel = author.voice_channel
await bot.join_voice_channel(channel)
they both give this error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception:
AttributeError: 'Member' object has no attribute 'voice_channel'
SOLUTION
Ok big news. I figured out how to connect.
You need to have PyNaCl (which i didn't install).
I also debugged a little and found out voice_channel didn't exist in author and i replaced it with voice.channel.
#bot.command()
async def join(ctx):
author = ctx.message.author
channel = author.voice.channel
await channel.connect()
print("i'm in the voice channel")
#bot.command()
async def leave(ctx):
await ctx.voice_client.disconnect()
print("i'm out of the voice channel")
Try installing discord.py with voice support:
# Linux/macOS
python3 -m pip install -U "discord.py[voice]"
# Windows
py -3 -m pip install -U discord.py[voice]
change author.voice_channel to author.voice.channel
you need to join the voice channel before you use the command.

How can I deafen a discord bot?

I want my music bot to be deafen when joining the channel. But I still want it to play music. I already tried with a await change_voice_state(*, channel, self_mute=False, self_deaf=False) function and with the discord.py docs, but nothing helped. I work with the commands.command method. Here is the relevant part of my source code:
async def play(self, ctx, *, url):
"""Plays a song from a URL"""
client = ctx.guild.voice_client
state = self.get_state(ctx.guild) # get the guild's state
send_message = state.now_playing is not None
# connect to author's voice channel
if not client:
if ctx.author.voice is None:
raise commands.CommandError("You have to be in a voice channel.")
else:
channel = ctx.author.voice.channel
client = await channel.connect()
await channel.connect seems to be the relevant part. I hope I can get help here.
I have seen other docs on the side which work with:
await voice_client.main_ws.voice_state(ctx.guild.id, channel.id, self_deaf=True)
but I get the following error message: AttributeError: 'VoiceClient' object has no attribute 'main_ws'
My code then looks like:
if not client:
if ctx.author.voice is None:
raise commands.CommandError("Du musst in einem Sprachkanal sein, um dies zu tun.")
else:
channel = ctx.author.voice.channel
client = await channel.connect()
voice_client = ctx.guild.voice_client
channel = voice_client.channel
await voice_client.main_ws.voice_state(ctx.guild.id, channel.id, self_deaf=True)
Maybe I somewhere made a mistake?
In your case you can try to use the following:
await ctx.guild.change_voice_state(channel=channel, self_deaf=True)
I would also recommend to add and set self_mute to Trueto guarantee that the bot is playing music if that is what you want.
To sum it up here is the code you can try:
await ctx.guild.change_voice_state(channel=channel, self_mute=False, self_deaf=True)

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)

Catching CommandOnCooldown Error

I am making a discord bot that has a cooldown and I am attempting to make an event that when the CommandOnCooldown Error occurs, the bot will DM them how much longer they have to wait. Here is my code and it all looks okay, but it doesn't know what retry_after means:
#bot.event
async def on_CommandOnCooldown():
await bot.send_message(ctx.message.channel, 'You are on cooldown. Try again in {:.2f}s'.format(retry_after))
#bot.command(pass_context = True)
#commands.cooldown(1, 30, commands.BucketType.user)
async def getalt(ctx):
msg = ["a list of stuff"]
await bot.send_message(ctx.message.author, random.choice(msg))
await bot.send_message(ctx.message.channel, "Alt Has Been Seen To Your DMs")
await bot.purge_from(ctx.message.channel, limit=2)
await bot.send_message(ctx.message.author, "Please Wait 30 Seconds Before Using This Command Again. If you do not wait the full time then you won't be sent an alt.")
I am using references from https://git.radiobrony.fr/MKody/discord.py/commit/cd0de57d13b15f709aaacf78ce611dd87e0784ce
This is the general format for catching exceptions when using discord.py:
from discord.ext import commands
bot = commands.Bot('$')
#bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.send('This command is on a %.2fs cooldown' % error.retry_after)
raise error # re-raise the error so all the errors will still show up in console
#commands.cooldown(1, 30)
#bot.command()
async def getalt(ctx):
await ctx.send('in getalt')
bot.run('token')
The getalt is the command, which has a 30-second cooldown, is caught by the on_command_error event, in turns will send a message to the channel. If you have anything else that you’re unclear about, please refer to the detailed documentation here.

Categories