'create discord bot commands from server

i'm new at programming, i'm coding a bot in python and i want my discord friends to be able to create custom commands

e.g:

user: !create

bot: write the first word that will be the command and the second word or phrase that will be the answer, separated by a comma.

user: hello, goodbye

bot: command successfully created

user: !hello

bot: goodbye



Solution 1:[1]

You can create global dictionary - ie. my_commands - and in !create put values as my_commands["!hello"] = "goodbye".

And you need to use on_message to check message (!hello) in this dictionary and send back value from dictionary (goodbye)

    # split message into list - so you could send with some arguments (but I don't use it
    cmd, *args = msg.content.split(' ')
    
    if cmd in my_commands:
        answer = my_commands[cmd]
        await msg.reply(answer) 
    else:
        # send to other commands - like `!create`
        await bot.process_commands(msg)

Minimal working code:

I made simpler version. You have to put all values in one line without ,

!create hello goodbye

but this version still has few disadvances:

  • you can add own command create and it will block original !create
  • new hello will replace existing hello
  • doesn't test who can add commands

import os
import discord
from discord.ext import commands, tasks

TOKEN = os.getenv('DISCORD_TOKEN')

bot = commands.Bot(command_prefix="!")

@bot.event
async def on_connect():
    print("[on_connect] connected as", bot.user.name)

@bot.event
async def on_ready():
    print("[on_ready] ready as", bot.user.name)

# global dictionary with example command.
my_commands = {
    '!test': 'Hello World!'
}

@bot.command('create')
async def create(ctx, *args):
    #print('[create] ctx:', ctx)
    #print('[create] args:', args)
    
    if len(args) >= 2:
        key = '!' + args[0]
        val = args[1]
        my_commands[key] = val
    
@bot.event
async def on_message(msg, *args):
    #print("[on_ready] msg:", msg)
    #print("[on_ready] args:", args)
    
    #print("[on_message] got message as", bot.user.name)
    #print("[on_message] msg.author:", msg.author)
    #print("[on_message] msg.author.bot:", msg.author.bot)
    #print("[on_message] msg.content:", msg.content)

    # skip messages from bots
    if msg.author.bot:
        return

    cmd, *args = msg.content.split(' ')
    
    if cmd in my_commands:
        answer = my_commands[cmd]
        await msg.reply(answer) 
    else:
        # send to other commands
        await bot.process_commands(msg)

bot.run(TOKEN)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1