I've got a problem with my music bot
It shows the same error again and again. Everytime when I type ?join or something like that (a command) it shows this message: Ignoring exception in command None:
discord.ext.command.errors.CommandNotFound: Command "(the command I've used)" is not found
Can someone help pls?
Code:
main.py:
import discord
from discord.ext import commands
import music
import os
import requests
import json
token = os.environ['botpw']
cogs = [music]
client = commands.Bot(command_prefix='?', intents = discord.Intents.all())
for i in range(len(cogs)):
cogs[i].setup(client)
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
client.run(token)
music.py:
import discord
from discord.ext import commands
import youtube_dl
class music(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
async def join(self,ctx):
if ctx.author.voice is None:
await ctx.send("Du bist nicht in einem Channel")
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)
#commands.command()
async def disconnect(self,ctx):
await ctx.voice_client.disconnect
#commands.command()
async def play(self,ctx,url):
ctx.voice_client.stop()
FFMPEG_OPTIONS = {
'before_options': '-reconnect 1 -reconnect_steamed 1 -reconnect_delay_max 5', 'options': '-vn'
}
YDL_OPTIONS = {'format':'bestaudio'}
vc = ctx.voice_client
with youtube_dl.Youtube_dl(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
url2 = info['formats'][0]['url']
source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
vc.play(source)
#commands.command()
async def pause(self, ctx):
await ctx.voice_client.pause
await ctx.send('pausiert ')
#commands.command()
async def resume(self, ctx):
await ctx.voice_client.resume
await ctx.send('play ')
def setup (client):
client.add_cog(music(client))
If your indents are same as you pasted here. The problem is here.
play, pause, etc are separated functions but not music class methods.
You should add indents to it:
class music(commands.Cog):
def __init__(self, client):
self.client = client
→→#commands.command()
→→async def join(self,ctx):
→→→→...
...
#commands.command()
async def pause(self, ctx):
...
#commands.command()
async def resume(self, ctx):
...
Related
I'm making a Discord bot, here is my code.
I don't know if the #commands.command() is right.
I tried to fix it but i couldn't do it.
And you can see the commands are right there so I don't know what is wrong whit this
main.py
import discord
from discord.ext import commands
#import all of the cogs
from music_cog import music_cog
bot = commands.Bot(command_prefix='!', intents = discord.Intents.all())
#remove the default help command so that we can write out own
bot.remove_command('help')
async def setup(bot):
await bot.add_cog(music_cog(bot))
#start the bot with our token
bot.run("TOKEN")
music_cog.py
from ast import alias
import discord
from discord.ext import commands
class music(commands.Cog):
def __init__(self,client):
self.client = client
#commands.command()
async def join(self,ctx):
if ctx.author.voice is None:
await ctx.send("Flaco, no estas en ningun canal de voz. Despertate perro")
voice_channel = ctx.author.voice.channel
if ctx.voice_client is None:
await voice_channel.connect()
else:
await ctx.voice_channel.move_to(voice_channel)
#commands.command()
async def disconnect(self,ctx):
ctx.voice_client.disconnect()
#commands.command()
async def play(self, ctx, url):
ctx.voice_client.stop()
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delax_max 5', 'options': '-vn'}
YDL_OPTIONS = {'format': 'bestaudio'}
vc = ctx.voice_client
with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download = False)
url2 = info['formats'][0]['url']
source = await discord.FFmpegOpusAudio.from_probe(url2,
**FFMPEG_OPTIONS)
vc.play(source)
#commands.command()
async def pause(self,ctx):
ctx.voice_client.pause()
await ctx.send("Dale master ahi te freno la musiquita 👍🏼")
#commands.command()
async def resume(self,ctx):
ctx.voice_client.resume()
await ctx.send("Suena como un Duna planchado al piso OAAA")
def setup(client):
client.add_cog(music(client))
And I get this error:
discord.ext.commands.errors.CommandNotFound: Command "join" is not found
I don't know how to solve it
when I run this code, it works completely fine, your imports are not at the top so I have no idea if you left those out or if you don't have them in your actual code, make sure you have your imports
the code works fine with the correct imports at the top
THIS QUESTION HAS BEEN SOLVED BY FURAS IN THE COMMENTS.
So I was following this tutorial on how to create a discord music bot like Rythm using discord.py. I had troubleshooted my code and fixed a few errors to do with coroutine.
EDIT: I have called the r function and now get this error upon running the code:
main.py:15: RuntimeWarning: coroutine 'r' was never awaited
r()
When I run the code everything boots up successfully until I try to use a command. If I put '#join' in the chat it should have joined the voice chat or said "You're not in a voice channel!". Instead I get this error:
2022-09-02 20:07:08 ERROR discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "join" is not found
I have tried swapping out #commands.command for #client.command (whilst also defining client in music.py) but more of the same. Any help would be much appreciated.
I have two files, main.py and music.py.
MAIN.PY
import discord
from discord.ext import commands
import music
cogs = [music]
client = commands.Bot(command_prefix='#', intents=discord.Intents.all())
async def r():
for i in range(len(cogs)):
await cogs[i].setup(client)
r()
client.run(
"my token")
MUSIC.PY
import discord
from discord.ext import commands
import youtube_dl
class music(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
async def join(self, ctx):
if ctx.author.voice is None:
await ctx.send("You're not in a voice channel!")
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)
#commands.command()
async def disconnect(self, ctx):
await ctx.voice_client.disconnect()
#commands.command()
async def play(self, ctx, url):
ctx.voice_client.stop()
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -
reconnect_delay_max 5', 'options': '-vn'}
YDL_OPTIONS = {'format': "bestaudio"}
vc = ctx.voice_client
with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
url2 = info['formats'][0]['url']
source = await discord.FFmpegOpusAudio.from_probe(
url2, **FFMPEG_OPTIONS)
vc.play(source)
#commands.command()
async def pause(self, ctx):
await ctx.voice_client.pause()
await ctx.send("Paused")
#commands.command()
async def resume(self, ctx):
await ctx.voice_client.resume()
await ctx.send("Resumed")
async def setup(client):
await client.add_cog(music(client))
When you define async function like async def r() then you would have to run it await r(). Problem is that you can't run await outside functions. You would have to run it in some async function - but it make the same problem with running this async function.
You may try to run it in event on_ready() which is async function.
#client.event
async def on_ready():
for item in cogs:
await item.setup(client)
I'm having issues building my music bot. It's accepting any of my commands.
I tried to making the Bot join the voice chat, and subsequently play music, but it doesn't work for some reason.
Here's my code:
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
bot = commands.Bot(command_prefix='.', description="L's very own Jukebox", intents=discord.Intents.all())
#bot.event
async def on_ready():
print(f"Logged in as {bot.user} ({bot.user.id})")
print("-----")
async def on_load():
print(f"Starting to load cogs...")
for cog in os.listdir("cog"):
if cog.endswith(".py"):
try:
await bot.load_extension(f"cog.{cog.strip('py')}")
print("{cog} cog has been loaded")
except Exception as e:
print(e)
print("{cog} cog can't be loaded.")
load_dotenv('development.env')
on_ready()
on_load()
TOKEN = os.getenv('TOKEN')
bot.run(TOKEN)
Here's also the code for the cog I'm using. It's under the 'cog' folder:
import youtube_dl
from discord.ext import commands
import YTDLSource
youtube_dl.utils.bug_reports_message = lambda: ''
class Music(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command()
async def ping(self, ctx):
await ctx.send('Ping!')
#commands.command()
async def join(self, ctx):
if ctx.author.voice is None:
await ctx.send("You're currently not in a voice channel!")
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)
#commands.command()
async def disconnect(self, ctx):
await ctx.voice_client.disconnect()
#commands.command()
async def play(self, ctx, *, url):
async with ctx.typing():
player = await YTDLSource.from_url(url, loop=self.bot.loop)
ctx.voice_client.play(player, after=lambda e: ctx.send(f'Player error: {e}') if e else None)
await ctx.send(f'Now playing {player.title}')
#commands.command()
async def stream(self, ctx, *, url):
async with ctx.typing():
player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True)
ctx.voice_client.play(player, after=lambda e: print(f'Player error: {e}') if e else None)
await ctx.send(f'Now playing: {player.title}')
#commands.command()
async def volume(self, ctx, volume: int):
if ctx.voice_client is None:
return await ctx.send("Not connected to a voice channel.")
ctx.voice_client.source.volume = volume / 100
await ctx.send(f"Changed volume to {volume}%")
#commands.command()
async def pause(self, ctx):
await ctx.voice_client.pause()
await ctx.send("Paused ⏸")
#commands.command()
async def resume(self, ctx):
await ctx.voice_client.resume()
await ctx.send("Resuming ▶")
#commands.command()
async def stop(self, ctx):
await ctx.voice_client.disconnect()
#play.before_invoke
#stream.before_invoke
async def ensure_voice(self, ctx):
if ctx.voice_client is None:
if ctx.author.voice:
await ctx.author.voice.channel.connect()
else:
await ctx.send("You aren't connected to a voice channel!")
raise commands.CommandError("Author is not connected to a voice channel.")
elif ctx.voice_client.is_playing():
ctx.voice_client.stop()
def setup(client):
client.add_cog(Music(client))
Anything that can help me fix my bot would help.
Thanks in advance.
Thanks to you guys, you helped me find the issue. As it turns out, I don't need await in on_ready() method. I also fixed the on_ready() method overall.
There was also a typo in the code. I wrote py, instead of .py for the bot.load_extension(f"cog.{cog.strip('.py')}").
So the code for the method looks like this:
#bot.event
async def on_ready():
print(f"Logged in as {bot.user} ({bot.user.id})")
print("-----")
print(f"Starting to load cogs...")
for cog in os.listdir("cog"):
if cog.endswith(".py"):
try:
bot.load_extension(f"cog.{cog.strip('.py')}")
print("{cog} cog has been loaded")
except Exception as e:
print(e)
print("{cog} cog can't be loaded.")
I am trying to code a discord music bot but i am getting errors.
Discord.py library doesn't work for me.
The errors like "discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'stop'."
These type error for almost every attribute for voice_client. Can someone correct my code. Because i can't see my fault.
My Code is (in music.py);
import discord
from discord.ext import commands
import youtube_dl
import ffmpeg
class music(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
async def join(self, ctx):
if ctx.author.voice is None:
await ctx.send("Ses kanalına gir")
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)
#commands.command()
async def disconnect(self, ctx):
await ctx.voice_client.disconnect()
#commands.command()
async def play(self, ctx, url):
ctx.voice_client.stop()
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -
reconnect_delay_max 5',
'options': '-vn'}
YDL_OPTIONS = {'format': "bestaudio"}
vc = ctx.voice_client
with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
url2 = info['formats'][0]['url']
source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
vc.play(source)
#commands.command()
async def pause(self, ctx):
await ctx.voice_client.pause()
await ctx.send("paused")
#commands.command()
async def resume(self, ctx):
await ctx.voice_client.resume()
await ctx.send("resumed")
def setup(client):
client.add_cog(music(client))
My code is (in main.py);
import discord
from discord.ext import commands
import music
cogs = [music]
client = commands.Bot(command_prefix='?', intents = discord.Intents.all())
for i in range(len(cogs)):
cogs[i].setup(client)
client.run("My_Token")
ctx.voice_client doesn't have the stop property.
Solutions:
Either CTX or ctx.voice_client is None
Or, voice_client doesn't have the stop() function.
Hi guys, for some reason my bot can actually join, but is not able to play audio.
Actually I am totally new to that and I was trying to get it to work like 2 hours and managed just to set up join but not play (or leave) command.
import os
import random
from dotenv import load_dotenv
import youtube_dl
import discord
from discord.ext import commands
from discord.ext import commands
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
players={}
bot = commands.Bot(command_prefix='!')
#bot.event
async def on_ready():
print(f'{bot.user.name} has connected to Discord!')
#bot.command(name="Ja_som_to_nebol.")
async def sranda(ctx):
sranda_quotes = ["Not gonna lie, kinda sus",
("Not gonna lie, kinda sus"), ]
response = random.choice(sranda_quotes)
await ctx.send(response)
##bot.event
#async def on_command_error(ctx, error):
# if isinstance(error, commands.errors.CheckFailure):
# await ctx.send('You do not have the correct role for this command.')
#bot.command(name="join")
async def join(ctx):
channel = ctx.author.voice.channel
await channel.connect()
#bot.command(name="leave")
async def leave(ctx):
channel = ctx.author.voice.channel
await channel.disconnect()
#bot.command(name="play")
async def play(ctx, url):
guild = ctx.author.voice.channel
voice_client = discord.utils.find(lambda c: c.guild.id == server.id, client.voice_client)
player = await voice_client.create_ytdl_player(url)
players=[server.id] = player
player.start()
bot.run(TOKEN)
instead of playing like this use my code which I uses you must have FFmpeg installed.
#commands.command(name='play', aliases=['p'])
async def _play(self, ctx: commands.Context, *, search: str):
if not ctx.voice_state.voice:
await ctx.invoke(self._join)
async with ctx.typing():
try:
source = await YTDLSource.create_source(ctx, search, loop=self.bot.loop)
except YTDLError as e:
await ctx.send('An error occurred while processing this request: {}'.format(str(e)))
else:
song = Song(source)
await ctx.voice_state.songs.put(song)
await ctx.send('Enqueued {}'.format(str(source)))
I am using some Cogs here you can edit to normal code by yourself.