[Python] How to Create discord bot commands from the server

Discussão em 'Python' iniciado por Stack, Março 19, 2025.

  1. Stack

    Stack Membro Participativo

    I'm coding a discord bot in Python and I want to create custom commands on the server that can be created in the server, from what Ive researched, I need to add a dictonary for the values to be put into.

    I went and followed a guide that was on a older post and this is what I got so far (Credit to Furas)

    import discord
    from discord.ext import commands

    new_dict = {}


    bot = commands.Bot(command_prefix='>', intents=discord.Intents.all())

    @bot.command('create')
    async def create(ctx, *args):
    print("Hey it works")
    print('[create] ctx:', ctx)
    print('[create] args:', args)

    if len(args) >= 2:
    key = '!' + args[0]
    val = args[1]
    new_dict[key] = val

    async def on_message(msg, *args):

    if msg.author.bot:
    return

    cmd, *args = msg.content.split(' ')

    if cmd in new_dict:
    answer = new_dict[cmd]
    await msg.reply(answer)
    else:
    # send to other commands
    await bot.process_commands(msg)

    cmd, *args = msg.content.split(' ')

    if cmd in new_dict:
    answer = new_dict[cmd]
    await msg.reply(answer)
    else:
    # send to other commands - like `!create`
    await bot.process_commands(msg)

    bot.run('THE TOKEN')


    The aim:

    When I type >create and write next to the fuction, I want it to make a custom function with the 1st arg and the 2nd arg to be what the bot responds with.

    e.g. >create cat meow

    What I want it to reproduce:
    Input: >cat
    Output: meow

    However, this seems to be not working, when I use >create, the bot seems to acknowledge the args below (In the code I added an fuction that makes it print, hey it works and then prints out the args and the ctx), but it doesn't seem to save them so they can be used again and it comes with a command not found error.

    The Bot is Online

    enter image description here

    And message context is on as well.

    The Log from the terminal

    2025-03-18 23:21:38 INFO discord.client logging in using static token
    2025-03-18 23:21:39 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 996c857e3c3c141b35d24977f6a9e025).
    Hey it works
    [create] ctx: <discord.ext.commands.context.Context object at 0x000001B2BDA1F6E0>
    [create] args: ()
    Hey it works
    [create] ctx: <discord.ext.commands.context.Context object at 0x000001B2BC4DBB30>
    [create] args: ('cat', 'meow')
    2025-03-18 23:22:01 ERROR discord.ext.commands.bot Ignoring exception in command None
    discord.ext.commands.errors.CommandNotFound: Command "cat" is not found

    Continue reading...

Compartilhe esta Página