discord.ext.commands.errors.CommandNotFound: Command is not found [solved] - discord

I finished a bot after a couple of hours and while trying to run it I get this error message 'discord.ext.commands.errors.CommandNotFound: Command "play" is not found' I don't know why/ how to fix this could anyone help?
The chunk of code with the error will be below this text:
#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
ask me if you need more of the code/more of the terminal output
I tried running the bot multiple times and I've looked around overflow for an answer and found nothing :/

(Comments mentioned you didn't load your cogs)
discord.py can't just "know" that it has to load your cogs, you have to do this yourself. This works through the process of extensions.
Extensions are loaded using load_extension. The best place to do this is setup_hook (don't use something like on_ready!). An extension is a file with a setup() method, which is invoked by the library when you call load_extension(). You can use this function to attach the cog to your bot.
Loading the extension in your bot's file:
class MyBot(commands.Bot):
...
async def setup_hook(self):
# This is typically done by looping over a directory of Cog files
# instead of 1 by 1, but this is just an example
await self.load_extension("path.to.your.extension")
Attaching the Cog in your extension's file:
class MyCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def setup(bot):
await bot.add_cog(MyCog(bot))

Related

DIscord Slash Commands Interaction Failed on discord py

async def _ping(ctx): # Defines a new "context" (ctx) command called "ping."
async def command_hi(ctx):
await ctx.defer()
await ctx.send("Pong!")
pass
I was making slash commands and first time it worked but secondtime, it does not work.
I tried await ctx.defer() but it's not working either
Hey #Justnoob I recommend you to use Pycord, It has inbuilt Buttons, Slash, Dropdowns and much more but for now the discord api with application commands is a bit complicated we usually use ctx.send but in app commands it is ctx.respond so here is the code:-
async def ping(ctx): #Don't use _ping too.
await ctx.respond("Pong!")
And I still don't understand why you created two async def in one command. There should be only one and you already specified it.

Command __ not found

I have a webhook cog for a discord bot I'm making. I want to make the embarrass command (in the webhook cog) trigger a webhook to be created with a user's name and pfp, which is working just fine. however, I also want this command to be able to be set onto a specific user, and that is where the problem arises. When I try to add a member parameter into the embarrass function, so it looks like: async def embarrass(self, ctx, member: discord.Member
it doesn't work. every time I execute the command after that I get a "command embarrass not found" error. this holds true regardless of if I pass through the paramter, and if I add member: discord.Member = None to it to make it not required; nothing I've done works. I would greatly appreciate any help on this topic.
Here is my main.py:
import random
import asyncio
import aiohttp
import json
import keep_alive
from discord import Game
from discord.ext.commands import Bot
import datetime
import re
import time
from subprocess import call
import discord
from discord.ext import commands
from discord.utils import get
import text
import os
TOKEN = os.environ['token']
bot = commands.Bot(command_prefix=".")
startup_extensions = ["Cog.Cog_Template", "Cog.webhooks"]
#bot.event
async def on_ready():
# On read, after startup
print(f"Connecting...\nConnected {bot.user}\n") # Send message on connected
if __name__ == "__main__": # When script is loaded, this will run
for extension in startup_extensions:
try:
bot.load_extension(extension) # Loads cogs successfully
except Exception as e:
exc = '{}: {}'.format(type(e).__name__, e)
print('Failed to load extension {}\n{}'.format(extension, exc))
keep_alive.keep_alive()
bot.run(TOKEN)
And here is my cog file (its called webhook.py and its in a folder called Cog:
from discord import Webhook, RequestsWebhookAdapter
from discord.ext import commands
import random
embarrasslist = ["I use and throughly like airpods","I respond with \"^\" to everything because I'm too dumb to have an original thought of my own","The only time I ever go outside is for school","I made a discord server where exactly 3 people joined, and they were were my alt accounts.","I get legitimately scared when I play five nights at freddy's","I play PC Games with a steam controller","I unironically use 69 in my usernames","I cried myself to sleep when I found out that my favourite chair had a dent in it","My parent's gave me a PS Move instead of a Wii for christmas","I unironically watch Ali-A","I spam .embarrass because I am very narcissistic and want to see my face on a bot", "I couldn't teach my son how to ride a bike cause I can't ride one myself","I own a sonic pillow and I kiss it every night before I go to sleep","I set my favorite 3ds game to system settings because I thought I was being clever","I set my favorite 3ds game to system settings because I can't buy any more games","Paul Blart: Maul Cop is my favorite movie","I thought shrek 3 wasn't bad","I have a gameinformer subscription","It took me a full day to beat the first level of super mario bros","My favorite emote is :joy:","I spent 2 hours learning how to make a new folder on my computer","I torrented fortnite"]
class WebHooks(commands.Cog, name="WebHooks"):
global embarrasslist
def __init__(self, bot):
self.bot = bot
#commands.command(name="embarrass")
async def embarrass(self, ctx, member: discord.Member = None):
"""Send a message as a webhook"""
if member != None:
user = member
elif member = None:
user = ctx.message.author
embarrassnumber = random.randint(0,21)
embarrassment = embarrasslist[embarrassnumber]
looking_webhooks = await ctx.channel.webhooks()
if looking_webhooks:
for webhook in looking_webhooks:
if webhook.name == "NexInfinite-GitHub":
await send_webhook(webhook, embarrassment, ctx, user)
return
else:
pass
webhook = await ctx.channel.create_webhook(name="NexInfinite-GitHub")
await send_webhook(webhook, embarrassment, ctx, user)
return
#commands.command(name="embaras", aliases = ["embarras","embarass"])
async def embarras(self, ctx):
"""Send a message as a webhook"""
cantspell = "I don't know how to spell *embarrass* properly"
looking_webhooks = await ctx.channel.webhooks()
if looking_webhooks:
for webhook in looking_webhooks:
if webhook.name == "NexInfinite-GitHub":
await send_webhook(webhook, cantspell, ctx)
return
else:
pass
webhook = await ctx.channel.create_webhook(name="NexInfinite-GitHub")
await send_webhook(webhook, cantspell, ctx)
return
def setup(bot):
bot.add_cog(WebHooks(bot))
async def send_webhook(webhook, message, ctx, uservar):
webhook_id = webhook.id
webhook_token = webhook.token
webhook = Webhook.partial(int(webhook_id),
f"{webhook_token}",
adapter=RequestsWebhookAdapter())
webhook.send(f'{message}', username=f"{ctx.uservar.display_name}",
avatar_url=ctx.uservar.avatar_url) # Sends the message as the author
I am running this on repl.it so thats why I import keep_alive, and I have another cog that I added with other commands but that doesn’t seem to be the issue either. I can add it if you request it however.
Thanks for the help!
I forgot to import discord at the top, so I couldn't successfully use discord.Member. Importing discord solved this issue.

Getting the URL of an attachment in Discord.py

I am trying to get the URL of the file that the user attaches so I can use it later on in my code however I'm not too sure on how to go about doing so.
#client.command(pass_context=True)
async def readURL(ctx, url):
# Do something
References:
discord.ext.commands
Attachment.url
If I'm understanding the question correctly, it would go like this:
#client.command() # context is automatically passed in rewrite
async def readURL(ctx):
attachment = ctx.message.attachments[0] # gets first attachment that user
# sent along with command
print(attachment.url)
References:
Attachment.url
Message.attachments

Push images to server from a specific folders via discord.py

I have some problems with my discord bot, I'll try to explain as much as I can.
So i have a bot's folder, which contains a bot itself, and a folder named commands, basically it's where my cogs are stored, and inside the folder commands there is a folder named images, in which i saved images for my bot to pick randomly. the problem is that i couldn't manage to tell the bot to take images from that specific folder, and instead it only works if i put images directly into bot's folder (the first folder). I've tried many things, such as:
#commands.command()
async def randomimage(self, ctx):
for list os.listdir(./commands/images/):
list = (images here)
await ctx.send('take this', file=discord.File(random.choice(list)))
but that didn't help either, i can just put /commands/images/(image) to every image but the list is huge and i don't want to write path to every image there.
bot:
#!/usr/bin/python3.6
import discord
from dotenv import load_dotenv
import random
from discord.ext import commands
import os
load_dotenv()
TOKEN = os.getenv('TOKEN')
bot = commands.Bot(command_prefix = '.')
#this script types "Connected!" in terminal if nothing has gone wrong
#bot.event
async def on_ready():
print('Connected!')
for filename in os.listdir('./commands'):
if filename.endswith('.py'):
bot.load_extension(f'commands.{filename[:-3]}')
bot.run(TOKEN)
the whole command:
import discord
import os
import random
from discord.ext import commands
class randomimage(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command()
async def randomimage(self, ctx):
#waiting for suggestion on this line
list = (image list)
await ctx.send('take this', file=discord.File(random.choice(list)))
def setup(client):
client.add_cog(randomimage(client))
I'm kind of noob here so any help would be greatly appreciated
I've figured this out. Apparently answer was as easy as changing a directory, literally
I've used os.chdir('./commands/images') and it worked.
Edit: Apparently I was wrong and that didn't work either
Update: apparently os.chdir works, but I have to specify the full path, like /home/user/discordbot/commands/images, so yes, that works

discord.py-rewrite - How to use custom checks in cogs?

So, on my bot.py main file, I have:
class Bot(commands.Bot):
# BOT ATTRIBUTES
class default_cooldown:
maxcommands = ...
seconds = ...
mode = ...
class my_exception(commmands.CommandError): pass
def my_check(self):
def predicate(ctx):
if ctx.author in a_list: return True
raise self.my_exception
bot = Bot(...)
Now I also have a cog file where I want to use the Bot().my_check() check and my Bot().default_cooldown() class:
class Cog(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command()
#self.bot.my_check()
#commands.cooldown(self.bot.default_cooldown().maxcommands, self.bot.default_cooldown().seconds, self.bot.default_cooldown().mode)
async def a_command(self, ctx):
pass
But I get an error, saying that self is not defined on my check and cooldown. Can anyone please help me fix this problem?
Methods are created once when the class object is created, not individually for each instance. You have a couple of options:
Factor out the code that need to appear in both places to a third module that contains just that code, then import that into both of your other files
Move your Bot definition into a separate module from the execution of your bot, and make my_check a staticmethod. Then you can access it through Bot.my_check instead of through the specific instance.
Define your cog inside setup so that the class is aware of the bot instance when it is created.

Resources