#roll command

98 messages · Page 1 of 1 (latest)

sick umbra
#

In roll.py

    try:
        rolls, limit = map(int, dice.split('d'))
    except Exception:
        await ctx.send('Invalid format. Please use the format NdM, where N is the number of dice and M is the number of sides on each die.')
        return

    result = ', '.join(str(random.randint(1, limit)) for r in range(rolls))

    embed = discord.Embed(title=f"{ctx.author.display_name} rolled {dice}", description=result, color=0x00ff00)
    await ctx.send(embed=embed)```

How do I fix this

All my commands are not found
mellow schooner
#

Can you share the rest of your code?

sick umbra
#

It's in a games folder and that's it in that folder besides another file for a quiz system I'm trying to create unless you mean all other code like main.py etc

mellow schooner
#

Well from what you've shared the immediate thing that I see is that you're missing the decorator to register the command

#

@bot.command() for example

#

So I wanted to see if it was actually missing or if you'd just not shared that part of your code 🙂

sick umbra
#

I will share other codes

#

In the cogs folder

#

commands.py

    bot.db = get_database().NELKA
    directories = ['cogs', 'commands']
    for directory in directories:
        if directory == 'cogs':
            print('\nCOGS:')
        else:
            print('\nCOMMANDS:')     
        for file in os.listdir(directory):
            if file.endswith('.py'):
                try:
                    extension_path = f'{directory}.{file[:-3]}'
                    await bot.load_extension(extension_path)
                    print(f'{file} loaded')
                except Exception as e:
                    print(f"Failed to load {file}: {e}")```
#

import discord
import traceback
import sys
from discord.ext import commands

class CommandErrorHandler(commands.Cog):
def init(self, bot):
self.bot = bot

@commands.Cog.listener()
async def on_command_error(self,ctx, error):
    # if command has local error handler, return
    if hasattr(ctx.command, 'on_error'):
        return

    # get the original exception
    error = getattr(error, 'original', error)

    if isinstance(error, commands.MissingRequiredArgument):
        return await ctx.send("An argument is missing")

    if isinstance(error, commands.CommandNotFound):
        await ctx.send("command not found")
        return
    
    if isinstance(error, discord.Forbidden):
        await ctx.send("I dont have the permission to do that!")

    if isinstance(error, commands.BotMissingPermissions):
        missing = [perm.replace('_', ' ').replace('guild', 'server').title() for perm in error.missing_perms]
        if len(missing) > 2:
            fmt = '{}, and {}'.format("**, **".join(missing[:-1]), missing[-1])
        else:
            fmt = ' and '.join(missing)
        _message = 'I need the **{}**
#

permission(s) to run this command.'.format(fmt)
await ctx.send(_message)
return
if isinstance(error, commands.DisabledCommand):
await ctx.send('This command has been disabled.')
return

    if isinstance(error, commands.CommandOnCooldown):
        await ctx.send(f'This command is actually on cooldown, you can use it in {round(error.retry_after, 2)} seconds.')
        return

    if isinstance(error, commands.MissingPermissions):
            missing = [perm.replace('_', ' ').replace('guild', 'server').title() for perm in error.missing_perms]
            if len(missing) > 2:
                fmt = '{}, and {}'.format("**, **".join(missing[:-1]), missing[-1])
            else:
                fmt = ' and '.join(missing)
                _message = 'You need the **{}** permission(s) to use this command.'.format(fmt)
                await ctx.send(_message)
                return

    if isinstance(error, commands.UserInputError):
        return await ctx.send("Invalid input.")

    if isinstance(error, commands.NoPrivateMessage):
        try:
            await ctx.author.send('This command cannot be used in direct messages.')
        except discord.Forbidden:
            pass
        return

    if isinstance(error, commands.CheckFailure):
        await ctx.send("You do not have permission to use this command.")
        return

    # ignore all other exception types, but print them to stderr
    print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr)

    traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)

async def setup(bot):
await bot.add_cog(CommandErrorHandler(bot))

mellow schooner
#

So I don't waste your time having you paste all the files. Is it just commands in the same file/cog as your roll command that isn't working?

#

If so, you can probably just start by sharing that file

sick umbra
#

It's all in the same category

mellow schooner
#

Where is roll.py being loaded? You're only loading .py files in the cogs and commands directory?

sick umbra
#

Yeah I think so

#

How do I load cogs and commands

mellow schooner
#

Is this a bot that somebody else wrote and you're trying to add commands to it or something?

sick umbra
sick umbra
#

He gave the code and he has a bot but idk if he knows how to explain it well

mellow schooner
#

Did you create the games folder and all the code in it?

sick umbra
#

Yes I used chatgpt for that

mellow schooner
#

😅 okay

sick umbra
#

He didn't share games

mellow schooner
#

No problem

#

So this code here that you shared

async def setup_hook(): 
    bot.db = get_database().NELKA
    directories = ['cogs', 'commands']
    for directory in directories:
        if directory == 'cogs':
            print('\nCOGS:')
        else:
            print('\nCOMMANDS:')     
        for file in os.listdir(directory):
            if file.endswith('.py'):
                try:
                    extension_path = f'{directory}.{file[:-3]}'
                    await bot.load_extension(extension_path)
                    print(f'{file} loaded')
                except Exception as e:
                    print(f"Failed to load {file}: {e}")

It's loading cogs in .py directly inside the cogs and commands folder

#

Do you know python at all or is it all just chatgpt generated?

sick umbra
#

I took a python class but it's been a while and I forgot everything so I am trying to learn

#

So I use chatgpt

mellow schooner
#

Sure, no problem, so I can try to talk you through atleast getting your roll command working

#

Can you open one of the .py files directly in the cogs folder and share the code with me?

#

It probably doesn't matter which one but maybe the one that you understand most of or a shorter one

sick umbra
#

I am moving roll.py to the commands folder

mellow schooner
#

Okay, let me know if it works

#

If not, share the contents of roll.py please

sick umbra
#

It's in commands and not working

#

No output

#

Well just c:/Users/my name/Nelk-RPG/commands/roll.py

#

Did the command and didn't work

#

Same code

mellow schooner
sick umbra
#

In roll.py

    try:
        rolls, limit = map(int, dice.split('d'))
    except Exception:
        await ctx.send('Invalid format. Please use the format NdM, where N is the number of dice and M is the number of sides on each die.')
        return

    result = ', '.join(str(random.randint(1, limit)) for r in range(rolls))

    embed = discord.Embed(title=f"{ctx.author.display_name} rolled {dice}", description=result, color=0x00ff00)
    await ctx.send(embed=embed)```
mellow schooner
# sick umbra Same code

Oh okay, so based on that link I think you'd need something like this...

from discord.ext import commands

@commands.command()
async def roll(ctx, dice: str):
    try:
        rolls, limit = map(int, dice.split('d'))
    except Exception:
        await ctx.send('Invalid format. Please use the format NdM, where N is the number of dice and M is the number of sides on each die.')
        return

    result = ', '.join(str(random.randint(1, limit)) for r in range(rolls))

    embed = discord.Embed(title=f"{ctx.author.display_name} rolled {dice}", description=result, color=0x00ff00)
    await ctx.send(embed=embed)

async def setup(bot):
    bot.add_command(roll)
#

It might be an idea to look at some of the files in the commands directory that your friend created to see how they are set up and laid out

sick umbra
mellow schooner
#

Okay 👍

sick umbra
#

Do I need to add that to github

#

Or just vsc

mellow schooner
#

All the code is already on github? And it depends how you're running the bot? Are you just running it on your PC or?

#

Can you link me to the github?

sick umbra
#

All the code I have on github is the same in vsc

mellow schooner
#

Where do you run main.py? On your computer?

sick umbra
sick umbra
mellow schooner
#

Okay then edit it on your computer

sick umbra
#

I use railway as the hosting

mellow schooner
#

😅

#

So you're not running main.py on your computer? You're running it in railway?

#

Anyway, the code needs to be put wherever your bot is running

#

If that's on your computer then do it there. If it's not on your computer and railway pulls from github then you'll need to make sure the code is on github

sick umbra
#

Railway is connected to github

mellow schooner
#

If you can I'd probably run the code from your computer with a different token while you're messing around with trying to get new code to work rather than pushing it to github and deploying it to railway each time. It'll make things quicker and won't run the risk of completely breaking your bot. Do you know how to do that?

sick umbra
#

No

#

Do I create a new bot

#

For testing

mellow schooner
#

I would, yeah

#

Then you can just run it on your computer without risking breaking your existing working bot

sick umbra
#

Then do I create another category

mellow schooner
#

Another category?

#

Did you pay for this bot originally? I'm struggling to understand how you've made it this far if both you and your friend set it up if you both just used chatgpt?

sick umbra
#

Nelka rpg at the top

#

That's a category right

mellow schooner
#

When I said make another bot, I meant within the discord dev console. Then you'd get a new token and put that in the existing folder. You don't need to create a new "bot" on your PC

#

Just commit the changes to git and push to github and see what happens xD

sick umbra
mellow schooner
#

Okay, well creating a bot in developer portal is what I meant, so that you can change the token in VS code and run it in VS code for testing

#

Sorry, when you said you didn't know how to do that I took it to mean somebody else set everything up for you

sick umbra
#

I ran main.py and it says

Commands:
Failed to load roll.py: path attribute not found on 'commands' while trying to find 'commands.roll'

#

In the terminal

mellow schooner
#

I'm not 100% sure on that one. Can you try create an empty file in the commands folder called __init__.py?

#

I'm not sure if it's because you have a file called commands.py and folder called commands. It might be causing conflicts.

#

Before you tried to add this roll command, were there already some commands? Were any commands ever working?

sick umbra
#

Okay now I put roll.py in cogs and there is a new error Failed to load roll.py: Extension 'cogs.roll' has no 'setup' function.

sick umbra
queen flint
#

Seems like you're missing the setup function from that file for it to be able to be loaded as a cog

sick umbra
#

Sorry about the wait I haven't been on vsc and I recently clicked something and now I can't see the sidebar where source control is or extensions but I'll try fixing it

sick umbra
# queen flint Can you paste the full `roll.py` file into a code block?
    try:
        rolls, limit = map(int, dice.split('d'))
    except Exception:
        await ctx.send('Invalid format. Please use the format NdM, where N is the number of dice and M is the number of sides on each die.')
        return

    result = ', '.join(str(random.randint(1, limit)) for r in range(rolls))

    embed = discord.Embed(title=f"{ctx.author.display_name} rolled {dice}", description=result, color=0x00ff00)
    await ctx.send(embed=embed)```
queen flint
#

There's no command decorator, no imports, no setup function, no classes

sick umbra
#

Full code