Match to the nearest command name in discord.py - python

I'm trying to create a feature for my discord.py bot that would send command names that are similar to what the user has used as a command when what they have typed in is incorrect. For example, a command called .slap exists. But the user enters .slp or something similar.
I want the bot to respond with the most similar command(s) which in this case is gonna be .slap. I'm a beginner still so I have no idea how to do this. I discovered about a lib called fuzzywuzzy and Levenshtein distance and I have no idea how to use them for my bot.
Any help would be highly appreciated!
Thanks

First of all, fuzzymatching commands and executing what it thinks is right, is not a great thing to add to your bot. It adds a point of failure, which can be pretty frustrating for the user regardless.
However, if you suggest a list of possible commands, it would probably work a lot better.
FuzzyWuzzy is a great tool for this.
The documentations for it are extremely helpful, so I really don't think you would have an issue if you actually read them.
My 2 cents for implementing would be (in pythonian pesudocode)
# user had input an invalid command
invalid_command = #userinput
command_list = [#list of your commands]
fuzzy_ratios = []
for command in command_list:
ratio = fuzzywuzzy.ratio(invalid_command, command)
fuzzy_ratios.append(ratio)
max_ratio_index = fuzzy_ratios.index(max(fuzzy_ratios))
fuzzy_matched = command_list[max_ratio_index]
return f"did you mean {fuzzy_matched}?"
Please try to implement and think why you need to implement it.
You need to actually try to implement yourself, or you will never learn.

You can try this:
disables = []
#client.command()
#commands.has_permissions(administrator=True)
async def disable(ctx, command):
command = client.get_command(command)
if not f"{command}: {ctx.guild.id}" in disables:
disables.append(f"{command}: {ctx.guild.id}")
await ctx.send(f"Disabled **{command}** for this server.")
else:
await ctx.send('This command is already disabled')
#client.command()
#commands.has_permissions(administrator=True)
async def enable(ctx, command):
command = client.get_command(command)
if f"{command}: {ctx.guild.id}\n" in disables:
await ctx.send(f"Enabled **{command}** for this server.")
else:
await ctx.send('This command is already enabled')
Now you have to add:
if "COMMAND: {ctx.guild.id}" in disables:
return
Between async def command(ctx) and your code for this command.
Warning: This is really bad way to do this. You can try to save a disables list to a json file. If you need help message me - Special unit#5323

Something you could use is aliases. Aliases are shortcuts for commands, here's an example:
#client.command(aliases=["slp","spla","spal","slpa","sap","salp"])
async def slap(ctx):
#Do whatever slap does
to create an alias you add aliases=[""] and start adding aliases. Aliases will invoke as commands. If I did .spla or whatever alias you added, it will still do what .slap does. Hope this helped!

Related

Cooldowns in discord.py with on_message

So, I basically messed up. This is the first time I've ever tried a discord bot and I've done all my code in on_message with it checking the content of the message to see if it matches with the command name (example below). I've added a few commands, which are quite long, and I don't really want to rewrite it. Is there any way around this or do I have to rewrite it?
if message.content.lower().startswith("!test"):
await message.channel.send(db[str(message.author.id)])
Simple example of what I'm doing, just a test command.
I have tried looking inside other questions but I either: don't want to do that or don't understand what people are saying.
Any help would be appreciated and since I'm new to discord.py; I might need it explained in bit easier terms please.
You can do something like this:
import asyncio
users_on_cooldown = [] # Consider renaming this if you are going to have multiple commands with cooldowns.
def on_message(msg):
if msg.content.lower().startswith("!test") and not msg.author.id in users_on_cooldown:
await msg.channel.send(db[str(msg.author.id)])
users_on_cooldown.append(msg.author.id)
await asyncio.sleep(20) # time in seconds
users_on_cooldown.remove(msg.author.id)
Since you said you are a beginner, please note that if you make another command with a separate cooldown, use another variable that users_on_cooldown, maybe something like ban_cmd_cooldown and test_cmd_cooldown.
How It Works When the command is used, the user is added to a list, and after a certain amount of seconds, they are removed. When the command is run, it is checked if the user is on the list.
Note: When the bot is reset, cooldowns will be reset too.
If you have any questions about this, feel free to ask in the comments below.
Here how to use
#client.command()
#commands.cooldown(1, 60, commands.BucketType.user)
async def test(ctx):
await ctx.send(db[str(message.author.id)])
(1, 60, commands.BucketType.user) means 1 msg per 60sec or a 60sec cooldown.
I would recommend you rewrite your bot. It may take some time but it'll be worth it.

How to skip bot from executing a command | discordpy

I have a problem. I am building a bot to filter the chat, which has two important commands. "addword" for add a word to list
But here if I want to use the "removeword" command, the bot thinks it's a word in the list and deletes it and it doesn't work properly.
Well, this might not be a perfect answer, but this might work or at least help:
#client.event
async def on_message(message):
if condition: # if this is true, the command will be executed
await client.process_commands(message)
By doing that, we can set the variable condition to whatever you want to, for example:
condition = not message.startswith('!removeword')
The example makes it so that whenever the removeword command is being typed into the chat, it won't response or run the actual command.
Make sure to replace the prefix ! with yours.

Is it possible to make a help command per command? Discord.py

What I'm looking for is to make a help command that will give info for a specific role. Basically something like this:
/help -> General help info
/help mute -> Mute help info
/help ban -> Ban help info
I tried making different commands like this:
#commands.command()
async def help(self, ctx):
await ctx.channel.send('this is a help command')
and
#commands.command()
async def help_mute(self, ctx):
await ctx.channel.send('Mute help information')
but both commands would show the first command's message. -> this is a help command. Why is that and could it be fixed?
Any answer will be appreciated!
Yes, you can use Groups and Subcommands to do it like this, however I strongly advise against this because then you'd have to create a new help command every single time you create a command, and all of them are exactly the same (await ctx.send("help_for_this_command")).
One thing you can do is add the information in the help kwarg of a command when creating it:
#commands.command(help="Mute help information")
async def mute(ctx, ...):
This way, the default help will take care of this. However, you can't really change how the text looks, as it'll just be formatted by Discord's default help implementation, so you'll have to live with the codeblock it sends.
If you don't want that, then what I do recommend is creating your own custom Help command (not just a command named "help", but a class that inherits from the HelpCommand class & overrides functions where necessary). Then you can create a database (or JSON file) with the information for every command, and just get that.
{
"mute": "Mute help information",
"ban": "Ban help information",
...
}
and a very simplified version of your help command would revolve around something like this:
async def command_callback(self, ctx, *, command=None):
if command is not None:
if command in json_file:
await ctx.send(json_file[command])
else:
await ctx.send("This is not a known command.")
Which is a lot cleaner than a huge chain of if/else statements checking which command was called.
If you want to see how the default help is implemented (to get an example of how to create yours), you can take a look at the source on the Discord.py GitHub repo. Keep in mind you only have to override the functions you want to change - if the default behaviour does what you need then there's no need to copy paste the implementation into yours (as the base class's functions will just be called automatically).
EDIT:
Łukasz Kwieciński linked a useful guide with very easy steps explaining how to create your own HelpCommand. This will probably help you out a lot as well.
Instead, you could take it as a parameter to pass with the help command. This would work by including an optional input after the help command, it would look like /help ban or /help [category]
A simple way of doing this would be, if the optional parameter wasn’t passed, it would send just the help command with no category. When the user includes a provided category, it would send help with that category. Here is it implied to your command.
#commands.command()
async def help(self, ctx, category=None):
if category == None:
await ctx.channel.send('this is a help command')
return
if category == "ban":
await ctx.channel.send('this is a ban and this is how to use it....')
return
if category == "mute":
await ctx.channel.send('this is a mute command...')
return
else:
await ctx.channel.send('Please provide a valid category')
return

Capturing user input as a string in Discord.py rewrite and returning said input in a message

I'm trying to capture a users input, what they say in a message, and have it returned to them in a message from the bot. More specifically, when they run a command, it'll return what ever text they have entered after that.
So far, I'm here:
async def on_message(message):
if message.content.startswith["=ok"]:
await client.send_message(message.channel, message.content[6:])
...unfortunately, I believe this was valid for the previous version of Discord.py before the rewrite. Essentially I want someone to be able to run the command =pressf and have the bot return the message "Everyone, lets pay respects to (string)!" An event probably isn't the best way to go about this but I'm stumped.
I've been struggling to find a specific answer online for my issue so I greatly appreciate anyone who could point me in the proper direction. Thanks!
I would recommend using the newer Commands Extension, it is much simpler to implement what you are wanting. See this bit specifically for passing everything a user types after the command into a variable.
There is an official example I would recommend looking at here: https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py
You should use commands instead of on_message event. Here is a simple command:
#client.command()
async def test(ctx):
await ctx.send('A Simple Command')
ctx parameter is the parameter that all commands must have. So, when you type =test, it will send to that channel A Simple Command.
If we come to what you try to do, you can use more parameters than ctx. Here is how you can do it:
#client.command()
async def pressf(ctx, *, mess):
await ctx.send(mess)
In this code, you have 1 more parameter called mess and also there's a *. That means mess parameter includes every message after =pressf. So when a user type =pressf Hello, it will send the channel Hello.

Conditional commands in discord.py

I want a user to be able to find out about something by, for example, saying something like !ask [___]. I would have a certain list of things that it could ask. Specifically, what notes are in a certain musical scale. So they would ask !scale Cmajor and get a response of "the notes in C major are C,D,E,F,G,A,B." I'm an absolute beginner and have no idea how to do this. I've made one bot before, but that's all my python experience.
You can view how to do such a task from the discord.py documentation
Specifically something like this could work, assuming you're using the latest version of discord.py, and following the appropriate setup:
# This is assuming your prefix is already defined, and you have a general bot setup
#bot.command()
async def scale(ctx, arg): # assuming the prefix is !, the command will be !scale argument
if arg.lower() == "cmajor":
await ctx.send("The notes in C major are C,D,E,F,G,A,B.")
else:
await ctx.send("Invalid scale.") # add more scales as needed

Categories