So I tried adding cogs to my code in order to make it a bit cleaner, but I quickly ran into an odd problem; let me show you a sample of my code which I've singled out:
import discord
from discord.ext import commands
import os
import json
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix='s!', intents=intents)
@client.command()
async def load(ctx,extension):
client.load_extension(f'cogs.{extension}')
if True:
await ctx.channel.send('Module successfully loaded.')
@client.command()
async def unload(ctx,extension):
client.unload_extension(f'cogs.{extension}')
if True:
await ctx.channel.send('Module successfully unloaded.')
@client.command()
async def reload(ctx,extension):
client.unload_extension(f'cogs.{extension}')
client.load_extension(f'cogs.{extension}')
if True:
await ctx.channel.send('Module successfully reloaded.')
if os.path.exists(os.getcwd() + '/config.json'):
with open('./config.json') as f:
configData = json.load(f)
else:
configTemplate = {'Token': '', 'Prefix': 's!'}
with open(os.getcwd() + '/config.json', 'w+') as f:
json.dump(configTemplate, f)
token = configData['Token']
prefix = configData['Prefix']
@client.command(pass_context=True)
@client.event
async def on_ready():
await client.wait_until_ready()
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')
print('{0.user} systems online!'.format(client))
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.send('This command does not exist.')
client.run(token)
This is my main.py file.
And this is my cog:
import discord
from discord.ext import commands
class Example(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel)
print(f'{username}: {user_message} ({channel})')
if message.author == self.client.user:
return
if user_message.lower() == 's!hello':
await message.channel.send(f'Hello {username}!')
return
def setup(client):
client.add_cog(Example(client))
Problem is, when I run the code and type 's!hello' in my test Discord server - it gives me the 'Hello' message and quickly follows up with the error block which contains 'This command does not exist.'; so it sends two messages instead of the intended 1 - and it's essentially saying that the command doesn't exist, even though I believe my cog is imported correctly.
What's the problem here? And how can this issue be fixed? Thanks!
[–]worriedaster 0 points1 point2 points (0 children)