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.
Related
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.
import discord
from discord.ext import commands
class CommandEvents(commands.cog):
def __init__(self, bot):
self.bot = bot
#commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.send("**Invalid command. Try using** `help` **to figure out commands!**")
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('**Please pass in all requirements.**')
if isinstance(error, commands.MissingPermissions):
await ctx.send("**You dont have all the requirements or permissions for using this command :angry:**")
#commands.command(name="ping")
async def ping(self, ctx: commands.Context):
await ctx.send(f"Pong! {round(self.bot.latency * 1000)}ms")
def setup(bot):
bot.add_cog(CommandEvents(bot))
thats my cog. When im trying to setup the Bot this will happen. so idk i searched so much how i can use cogs but idk. Im new to cogs this is my first time using them.
my Main Pogramm
import discord
import os
from discord.ext import commands
token = ""
bot = commands.Bot(command_prefix = '-')
bot.load_extension("CommandEvents")
bot.run(token)
what am i doing wrong?
Line 4 of your cog file: You typed commands.cog. Since Python is case sensitive, you have to type commands.Cog with the C in uppercase.
Also:
You have to put in the full path of the cog. You've just typed "CommandEvents" but it should be "cogs.CommandEvents".
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 have a discord bot with like two simple functions (client.event with client = discord.Client()) and recently I've been trying to work on commands for a music bot, but apparenly the bot doesn't even respond to the simplest commands there are. For example:
import discord
from discord.ext import commands
client = discord.Client()
bot = commands.Bot(command_prefix='!')
#bot.command()
async def hello():
print("Hello") #So when I type !hello in a channel I want "Hello" written in the console as prove that the bot is responding
#client.event
async def on_ready():
print("Online.") #Just simple if the bot is online
The function client.event works of course but the bot.command() function wont react in any way. Can anyone help me here? I am really about to break everything I own.
Try this:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
#bot.command()
async def hello(ctx):
print("Hello")
#bot.event
async def on_ready():
print("Online.")
bot.run("Token")
Firstly, why are you defining client and bot simultaneously? Secondly you don't have bot.run() in your code. Thirdly you have to always give ctx in #bot.command.
You either use discord.Client or commands.Bot, you cannot use both of them. If you take a look at your code, you're decorating the command with bot.command(), but at the end of the file you're running client. If you want commands I suggest you use commands.Bot:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
#bot.command()
async def hello(ctx):
print("Hello")
#bot.event
async def on_ready():
print("Online.")
bot.run("XXX")
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))