Discord.py Cogs “Command [ ] is not found”

2024/11/16 2:20:15

I am recoding my discord.py bot using cogs as it wasnt very nice before.

I tried this code:

import discord
import os
import keep_alive
from discord.ext import commands
from discord.ext.commands import BucketType, cog, BadArgument, command, cooldownintents = discord.Intents().all()
bot = commands.Bot(command_prefix=',', intents=intents)
p = ','class General(commands.Cog):def __init__(self, bot):self.bot = bot@commands.command()async def test(self, ctx):await ctx.channel.send("I'm **alive**.")@commands.command()async def ping(self, ctx):await ctx.send(f'⏱|** {round(bot.latency * 1000)} ms** Latency!')await bot.add_cog(General(bot))if __name__ == '__main__':keep_alive.keep_alive()
bot.run(os.environ['token'])

But I get an error that says “Command ‘ping’ is not found”. What is wrong with the code?

Answer

If you use cogs you usually want to a have a main script. In that main script you load your cogs which are located as separate files in another folder. After you loaded your cogs you will run the bot via the main script.

Example for main script you can try to copy pasta it:

Enter your Token.

Enter your Server ID (-> right click on your server -> "Copy Server ID")

Enter your APP ID (-> right click on your Bot -> "Copy User ID")

enter image description here

import discord 
from discord.ext import commands 
import os SERVER_ID = # ENTER YOUR SERVER ID HERE (AS INT)
APP_ID = # ENTER YOUR APP ID HERE (AS INT)
TOKEN = # ENTER YOUR TOKEN HERE (AS STRING)class MyBot(commands.Bot):def __init__(self):super().__init__(command_prefix='.', intents=discord.Intents.all(), application_id=APP_ID)async def setup_hook(self):for filename in os.listdir('./cogs'):  # accessing the cogs folderif filename.endswith('.py'):  # checking if cogs inside the folderawait self.load_extension(f'cogs.{filename[:-3]}')  # loading the cogsbot.tree.clear_commands(guild=discord.Object(id=SERVER_ID))await bot.tree.sync(guild=discord.Object(id=SERVER_ID))  # syncing the tree in case you use app commandsasync def on_ready(self):synced = await self.tree.sync()print(" Slash CMDs Synced " + str(len(synced)) + " Commands")print(synced)await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name='.helpme'))bot = MyBot()
bot.run(TOKEN, reconnect=True)

Then you need to set up your cog folder, for this create a cog folder like this:

cog folder example

Now you need to put a cog script into the cog folder:

Example for your cog script:

import discord
import os
from discord.ext import commands
from discord.ext.commands import BucketType, cog, BadArgument, command, cooldownclass TestCog(commands.Cog):def __init__(self, bot: commands.Bot):self.bot = bot@commands.Cog.listener()async def on_ready(self):print('TestCog loaded.')@commands.command(pass_context=True)async def test(self, ctx):await ctx.channel.send("I'm **alive**.")@commands.command(pass_context=True)async def ping(self, ctx):await ctx.send(f'⏱|** {round(self.bot.latency * 1000)} ms** Latency!')async def setup(bot: commands.Bot):await bot.add_cog(TestCog(bot))

Now save the files and run the main script.

I tested it and it worked for me:

testresult

https://en.xdnf.cn/q/118981.html

Related Q&A

Binomial distribution CDF using scipy.stats.binom.cdf [duplicate]

This question already has answers here:Alternatives for returning multiple values from a Python function [closed](14 answers)Closed 2 years ago.I wrote below code to use binomial distribution CDF (by u…

How to get Cartesian product of two iterables when one of them is infinite

Lets say I have two iterables, one finite and one infinite:import itertoolsteams = [A, B, C] steps = itertools.count(0, 100)I was wondering if I can avoid the nested for loop and use one of the infinit…

Function to create nested dictionary from lists [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar q…

Pygame not using specified font

So I am having a problem in pygame where I specify the font and size to use, but when my program is run, the font and size are the default.Here is where I define the textdef font(self):*****FATAL - THI…

port management in python/flask application

I am writing a REST API using the micro framework Flask with python programming language. In the debug mode the application detect any change in source code and restart itself using the same host and p…

using def with tkinter to make simple wikipedia app in python

I am beginner in python. I am trying to make a python wiki app that gives you a summary of anything that you search for. My code is below:import wikipediaquestion = input("Question: ")wikiped…

Only length-1 arrays can be converted to Python scalars with log

from numpy import * from pylab import * from scipy import * from scipy.signal import * from scipy.stats import * testimg = imread(path) hist = hist(testimg.flatten(), 256, range=[0.0,1.0])[0] hist…

Deploying Django with apache using wsgi.py

Im trying to deploy a Django project on a linode server that has apache, some other django projects and a php project on it. Also my project is in a virualenv and the other django projects arent.My Dja…

Building a decision tree using user inputs for ordering goods

I am trying to program a decision tree to allow customers to order goods based on their input. So far, I have devised a nested if-elif conditional structure to decide if customer want to order what or…

How to de-serialize the spark data frame into another data frame [duplicate]

This question already has answers here:Explode array data into rows in spark [duplicate](3 answers)Closed 4 years ago.I am trying to de-serialize the the spark data frame into another data frame as exp…