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('no one is here')
voice_channel = ctx.author.voice.channel
if ctx.voice_client in None:
await voice_channel.connect()
else:
await ctx.voice_client.move_to(voice_channel)
def setup(client):
client.add_cog(music(client))
I made the main file and the music file, and this code is the command in the music file.
Commands in the main file work, but commands in the music file don't work.
And if you enter the join command, discord.ext.commands.errors.CommandNotFound: Command "join" is not found
An error occurs.
Related
I want to use a slash command in DMs. Take this simple test.py file in the folder cogs/.
import discord
from discord.ext import commands
from discord import app_commands
class Test(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
#commands.Cog.listener()
async def on_ready(self):
print("Loaded test command cog.")
#app_commands.command(name="test", description="Test command")
async def test(self, interaction: discord.Interaction):
await interaction.response.send_message(f'Hello')
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(Test(bot))
Outside the cogs folder is my launch_bot.py file which start the bot:
import discord
from discord.ext import commands
import json
with open("cogs/jsons/settings.json") as json_file:
data_dict = json.load(json_file)
guild_id = data_dict["guild_id"]
class MyBot(commands.Bot):
def __init__(self) -> None:
super().__init__(
command_prefix = "kt$",
intents = discord.Intents.all(),
tree_cls=CustomCommandTree)
async def setup_hook(self) -> None:
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await self.load_extension(f"cogs.{filename[:-3]}")
await bot.tree.sync(guild=discord.Object(id=guild_id))
async def on_ready(self):
application_info = await self.application_info()
bot_owner = application_info.owner
await bot_owner.create_dm()
self.bot_owner_dm_channel = bot_owner.dm_channel
await self.change_presence(activity=discord.Game(presence_message))
print(f"Logged in as\n\tName: {self.user.name}\n\tID: {self.user.id}")
print(f"Running pycord version: {discord.__version__}")
print(f"Synced commands to guild with id {guild_id}.")
bot = MyBot()
bot.run(bot_token)
I tried following the instructions which were described in link but I have no guild specified, so this doesn't work.
The docs says it should work but it doesn't for me any ideas?
If you are using pycord, at least for me commands were usable in dm's by default. I'll show you how to disable that if you ever need to.
#bot.command()
#commands.guild_only()
async def example(ctx):
#do things
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 just trying to get a discord bot to join a VC and play a song Pause & Stop but I am getting these errors.
*Edit: With me being new to Python I am not exactly sure how to fix this. I have read up about examples of these kinds of issues while trying to fix this and transferring them over to this problem has been uneventful with me just gaining more errors in the process.
Old Error
Traceback (most recent call last):
File "main.py", line 3, in <module>
import music
File "/home/runner/Adonnis/music.py", line 13, in <module>
async def join(self,ctx):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1432, in decorator
raise TypeError('Callback is already a command.')
TypeError: Callback is already a command.
New Error
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "join" is not found
Main.py
import discord
from discord.ext import commands
import music
print("Discord version ",discord.__version__)
print("Bot Running")
cogs = [music]
client = commands.Bot(command_prefix='?', intents = discord.Intents.all())
for i in range(len(cogs)):
cogs[i].setup(client)
client.run(Token)
Music.py
import discord
from discord.ext import commands
import youtube_dl
class music(commands.Cog):
def __innit__(self,client):
self.client = client
# #commands.command()
#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_channel.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("Audio Paused ⏸")
#commands.command()
async def resume(self,ctx):
await ctx.voice.client.resume()
await ctx.send("Audio Resumed ⏯")
def setup(client):
client.add_cog(music(client))
I've coded this off of https://www.youtube.com/watch?v=jHZlvRr9KxM
Is anyone able to assist me with the debugging of this?
*Edit: I have updated the "Error" sorry that was from an older version where I was trying what worked for someone else.
*Edit:
Packages used:
Discord
Discord.py
Youtube_DL
Pineapple
Just in case anyone wants to know what this was coded on also this was made on Replit.
i'm currently using these commands to make my bot leave/join a vc. Joining works fine, but leaving won't work.
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_channel.move_to(voice_channel)
#commands.command()
async def disconnect(self,ctx):
await ctx.voice_client.disconnect()
Any help in understanding why would be really appreciated!
try with:
#commands.command()
async def disconnect(self,arg):
await arg.voice_client.disconnect(force=True)
and also replace channel name from ctx to arg cause it takes ctx as current channel (its not possible to type in voice channel afaik)
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.