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".
Related
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 little problem which you can skip and does not give you a big error that doesn't let you run the bot, by it is very frustrating tho.
Code:
import asyncio
import discord
from discord.ext import commands
from main import db
^^^^ Unable to import 'main' [pylint(import-error)]
import datetime
import random
I am using cogs so that's why I am importing from main.
If you are using cogs you don't have to import main. Just give a look to the discord.py docs and you will see that cogs must be like this:
import discord
from discord.ext import commands
class MembersCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command()
#commands.guild_only()
async def joined(self, ctx, *, member: discord.Member):
"""Says when a member joined."""
await ctx.send(f'{member.display_name} joined on {member.joined_at}')
#commands.command(name='coolbot')
async def cool_bot(self, ctx):
"""Is the bot cool?"""
await ctx.send('This bot is cool. :)')
#commands.command(name='top_role', aliases=['toprole'])
#commands.guild_only()
async def show_toprole(self, ctx, *, member: discord.Member=None):
"""Simple command which shows the members Top Role."""
if member is None:
member = ctx.author
await ctx.send(f'The top role for {member.display_name} is {member.top_role.name}')
def setup(bot):
bot.add_cog(MembersCog(bot))
And in main.py: bot.load_extension('folder_name.file_name')
This is just an example.
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))
Like said in the title, if it's possible I'd like to be able to import some part of code that contains decorators in the bot code.
from discord.ext import commands
class Updates(commands.Cog):
def __init__(self, bot):
self.bot = bot
if __name__ == "__main__":
token = 'XXXXXXXXXXXXXXXXXXX'
prefix = '!'
bot = commands.Bot(command_prefix=commands.when_mentioned_or(
prefix), description='Useless - Updates')
bot.add_cog(Updates(bot))
bot.run(token)
I have like 3 or more sub-modules like that (I have a main file that check for modules that query for the class, here 'Updates') and I have a common part of code :
#commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(error, commands.CommandNotFound):
return
raise error
#commands.group(name='stop', hidden=True)
#commands.is_owner()
async def stop(self, ctx):
await ctx.message.add_reaction('\N{THUMBS UP SIGN}')
await self.bot.logout()
sys.exit()
#commands.group(name='reload', hidden=True)
#commands.is_owner()
async def reload(self, ctx):
await ctx.message.add_reaction('\N{THUMBS UP SIGN}')
await self.bot.logout()
sys.stdout.flush()
os.execv(sys.executable, [sys.executable, __file__])
Anyone ?
The most efficient way is to use cogs. These are basically classes which function as "groupings" for commands. Such classes can then be added via bot.add_cog(YourCogClass(bot))
A much more thorough explanation can be found here.
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.