discord.ext.commands.bot: Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "ping" is not found.
How to fix it?
Main class:
import discord
from discord.ext import commands
from discord import Intents
import os
intents = Intents.all()
intents.members = True
bot = commands.Bot(command_prefix='$', intents=intents)
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
bot.load_extension(f"cogs.{filename[:-3]}")
#bot.event
async def on_ready():
print('We Have logged in as {0.user}'.format(bot))
bot.run('TOKEN')
My cog:
from discord.ext import commands
class MainCog:
def __init__(self, bot):
self.bot = bot
#commands.command(pass_context=True)
async def ping(self, ctx):
await ctx.send('pong')
async def on_message(self, message):
print(message.content)
def setup(bot):
bot.add_cog(MainCog(bot))
I think its because your class isn't inheriting commands.Cog
Changing class MainCog: to class MainCog(commands.Cog): should fix that problem for you.
Firstly, as the other comment mentioned, your Cog class is not inheriting from commands.Cog.
Second, you're loading extensions the old way. Extension loading is now asynchronous. This page in the migration guide explains how to do it: https://discordpy.readthedocs.io/en/stable/migrating.html#extension-and-cog-loading-unloading-is-now-asynchronous
Lastly, you have a random on_message method floating around in that class. This won't actually do anything. You should attach a listener to it.
Related
i'm making a discord bot for my server, but my codes continue to give me this error. My goal is to have a class with some commands, but I always get the error "discord.ext.commands.errors.CommandNotFound". These are my code:
import discord
from discord.ext import commands
class General_commands(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command()
async def message(self, ctx:commands.context, *, channel: discord.VoiceChannel):
await ctx.channel.send('message')
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix='-', intents=intents)
#bot.event
async def on_ready():
print('Logged in as {0.user}'.format(bot))
bot.add_cog(General_commands(bot))
bot.run(token)
Do you know what I do wrong? If something is unclear you can simply ask :)
I've already tried to use examples saw in github but I didn't menage to solve my problem :(
If I put the command outside the function, with some adjustments it works, but would preferably have it in the class.
Cog loading became asynchronous in 2.0, your code is very outdated. Read the migration guide: https://discordpy.readthedocs.io/en/stable/migrating.html#extension-and-cog-loading-unloading-is-now-asynchronous
ext.commands.Bot.add_cog() must now be awaited.
This isn't something most people want, but I do.
Code:
#imports
import discord
import os
from keep_alive import keep_alive
from discord.ext.commands import has_permissions, MissingPermissions
from discord.ext import commands
from discord.utils import get
#client name
client = discord.Client()
#log-in msg
#client.event
async def on_ready():
print("Successfully logged in as")
print(client.user)
#prefix and remove default help cmd
client = commands.Bot(command_prefix='H')
client.remove_command("help")
#client.command(pass_context=True)
async def ere(ctx, *, args=None):
await ctx.send("hi")
if discord.utils.get(ctx.message.author.roles, name="MEE6") != None:
if args != None:
await ctx.send("mee6 just spoke!")
else:
await ctx.send("nope")
#client.event
async def on_message(message):
print(message.author)
if "Here" in message.content:
if discord.utils.get(message.author.roles, name="MEE6") != None:
channel = await client.fetch_channel(870023245892575282)
await channel.send("yes")
await client.process_commands(message)
I figured adding "await client.process_commands(message)" to the bottom of on_message would process commands sent by other bots such as MEE6 but no luck. It appears by default on_message can hear bots but commands can not. Any way to get around this?
Any help would be greatly appreciated!
It is a feature of the Bot class to ignore other bot's messages, but #Daniel O'Brien solved it in this thread. The solution is to subclass the bot and override the function which ignores other bots, like this:
class UnfilteredBot(commands.Bot):
"""An overridden version of the Bot class that will listen to other bots."""
async def process_commands(self, message):
"""Override process_commands to listen to bots."""
ctx = await self.get_context(message)
await self.invoke(ctx)
Use ID
for commands:
# from discord.ext import commands as cmds
def is_mee6():
def predicate(ctx: cmds.Context):
return ctx.message.author.id == 159985870458322944:
# 159985870458322944 is ID of MEE6
return cmds.check(predicate)
# Use like it:
# #cmds.command()
# #is_mee6()
# async def ...
for events:
# from discord.ext import commands as cmds
mee6_id = 159985870458322944
# and use it for checks. for Example
#cmds.event
async def on_message(message):
if message.author.id == mee6_id:
# ANY
I am building a discord bot, and want to use slash commands inside cogs, but the commands don't show or work, here is the code
## cog
guild_ids = [858573429787066368, 861507832934563851]
class Slash(commands.Cog):
def __init__(self, bot):
self.bot = bot
#cog_ext.cog_slash(name="test", guild_ids=guild_ids, description="test")
async def _test(self, ctx: SlashContext):
embed = Embed(title="Embed Test")
await ctx.send(embed=embed)
## bot
bot = discord.ext.commands.Bot(command_prefix = "!")
#bot.event
async def on_ready():
print(f'{bot.user} has logged in.')
bot.load_extension('slash_music_cog')
bot.run("bot-token")
After working at this issue for myself for way longer than I'd like to admit, I've finally found the culprit:
You have to load your cogs before running the bot.
For some reason, it won't register your commands with discord, if you load the cogs in the on_ready function, so the solution here, is to move your extension-loading code to right before your bot.run("bot-token") statement.
So the finished code should look something like
## cog
guild_ids = [858573429787066368, 861507832934563851]
class Slash(commands.Cog):
def __init__(self, bot):
self.bot = bot
#cog_ext.cog_slash(name="test", guild_ids=guild_ids, description="test")
async def _test(self, ctx: SlashContext):
embed = Embed(title="Embed Test")
await ctx.send(embed=embed)
## bot
bot = discord.ext.commands.Bot(command_prefix = "!")
#bot.event
async def on_ready():
print(f'{bot.user} has logged in.')
bot.load_extension('slash_music_cog')
bot.run("bot-token")
You'll need to slightly modify the bot.py file to initialize a SlashCommand object. Take a look at the library's README for a slightly more detailed example of a bot using cogs.
# bot
from discord_slash import SlashCommand
bot = discord.ext.commands.Bot(command_prefix = "!")
slash = SlashCommand(bot)
#bot.event
async def on_ready():
print(f'{bot.user} has logged in.')
bot.load_extension('slash_music_cog')
bot.run("bot-token")
After much hassle, I've finally found out how to do it. Your main.py/bot.py should look something like this:
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'), intents=intents)
slash = SlashCommand(bot, sync_commands=True)
You need to use sync_commands=True, otherwise the commands don't appear or sync, both in the main module and the cogs.
I am running this script that I found from a YouTube tutorial, and it was working earlier. Now it seems to not be working anymore.
Script that isn't working
import asyncio
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='', help_command=None, self_bot=False)
class SelfBot(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
async def sendMessage(self, ctx):
await ctx.send("Send Message")
client.add_cog(SelfBot(client))
client.run(token, bot=False)
it seems to be as if it is getting "stuck" at #commands.command() and won't run the sendMessage function. My bot also appears to be online once the script is running. Any ideas on how to fix it?
Another thing that i found interesting is that one of my scripts that i created does work how it was intended.
Script that is working
#bot.event
async def on_message(message):
await asyncio.sleep(1)
with message.channel.typing():
await asyncio.sleep(2)
await message.channel.send("test")
return
bot.run(token, bot=False)
This will message me test once I send a message to the server.
Your command might not be working because you have a on_message event. on_message events have the priority on commands and if you don't process them, none of them will be able to be executed.
What you have to add is in your on_message event:
#bot.event
async def on_message(message):
await asyncio.sleep(1)
with message.channel.typing():
await asyncio.sleep(2)
await message.channel.send("test")
await bot.process_commands(message)
If it doesn't solve the problem, it might also come from your commands.Bot variable. For an unkown reason, you seem to have two commands.Bot variables: client and bot. You should only have one.
Also, I saw you set your prefix as '', if you don't want any error like Command not found, you should set a prefix (eg. !, $, ;, ...).
Also, as #InsertCheesyLine recommended it, you should separate your cogs in different files and put them in a folder nammed cogs, like so:
Main file (eg. bot.py)
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
extensions = ['cogs.test'] #cogs.(filename)
if __name__ == '__main__':
for extension in extensions:
bot.load_extension(extension)
#bot.event
async def on_ready():
print(f'Bot is ready to go!')
bot.run('TOKEN')
One of your cogs (eg. cogs/test.py)
from discord.ext import commands
#This is a cog example, you'll have to adapt it with your code
class Test(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.Cog.listener() #equivalent to #bot.event
async def on_message(self, message):
if 'test' in message.content:
await message.channel.send('Test Message')
await self.bot.process_commands(message)
#commands.command()
async def ping(self, ctx):
await ctx.send('Pong!')
def setup(bot):
bot.add_cog(Test(bot))
I've been trying to figure out how cogs work with the discord.py rewrite and I managed to get a bot working with only one cog. The problem is, the bot recognizes commands from one cog, but not the other.
importing the cogs in bot.py
cogs = [
'cogs.basic',
'cogs.mod']
#bot.event
async def on_ready():
print("Arthur Morgan")
print("version: "+version)
game = discord.Game("rebuilding.....")
await bot.change_presence(status=discord.Status.idle, activity=game)
for extension in cogs:
bot.load_extension(extension)
return
inside basic.py commands inside here seem to work
import discord
from discord.ext import commands
class Basic(commands.Cog):
def __init__(self,bot):
self.bot = bot
#commands.command(name='ping', aliases=['p'])
async def ping(self, ctx):
await ctx.send("Pong! :ping_pong:")
def setup(bot):
bot.add_cog(Basic(bot))
commands in mod.py output this
import discord
from discord.ext import commands
class Mod(commands.Cog):
def __init__(self,bot):
self.bot = bot
#commands.command()
async def pong(self, ctx):
await ctx.send("Ping!")
def setup(bot):
bot.add_cog(Mod(bot))
does anybody know how to fix this?
for extension in cogs:
bot.load_extension(extension)
return
The coroutine stops when it reaches return, after loading only one cog.