Cooldowns in discord.py with on_message - python

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.

Related

Match to the nearest command name in discord.py

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!

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.

Running multiple commands with discord.py

Using discord.py and python:
Ok so basically I have this bot that updates the best prices for a certain game every minute. However, while I am doing that, other people cannot access the bot. For example, lets just say I have a command called "hello" that when called prints hello out in the chat. Since the code always runs, the user cant call the command hello because the code is too busy running the code that updates every minute. Is there any way to like make it so that the updateminute code runs while others can input commands as well?
import discord
import asyncio
import bazaar
from discord.ext import commands, tasks
client = commands.Bot(command_prefix = '.')
#client.command()
async def calculate(ctx):
while True:
await ctx.send(file2.calculate())
await asyncio.sleep(210)
#client.command()
async def hello(ctx):
await ctx.send("Hello")
client.run(token)
In file2.py:
def updateminute():
for product in product_list:
#Grab Api and stuff
#check to see whether it is profitable
time.sleep(0.3) #cause if i don't i will get a key error
#calculate the stuff
#return the result
To sum up, since the bot is too busy calculating updateminute and waiting, other people cannot access the bot. Is there any way I can try to fix this so that the bot calculates its stuff and so people can use the bots commands? Thanks!
You can look into threading! Basically, run two separate threads: one for taking requests and one for updating the prices.
You could also look into turning it into an async function, essentially making it easier to run things concurrently.
So your standard def will become async def and then to call the function you simply add an await before it so await file2.calculate()
Hope it helps and is also somewhat easier to understand

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

Discord.py async function does not give any output and does not do anything

here is the code:
print('hmm1') #testing, this one prints
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='&')
client.run('my token', bot=False)
async def testFunction():
print('hmm') #<- this one does not print.
channel = await client.get_channel(708848617301082164)
message_id=715307791379595275
msg = await client.get_message(channel, message_id)
await msg.edit(content="L")
await msg.edit(content="W")
print('edited message!')
testFunction()
# none of the above works. I only get "hmm1" printed in console.
I have no clue what is happening as there is quite literally no error or output of any sort in the console. does anyone know the problem?
If you're not familiar with asynchronous functions, they need to be awaited. Examples of coroutines can be seen in msg.edit(..., as edit() is a coroutine, therefore you need to await it like so: await testFunction()
Additionally, client.get_channel() and client.get_message() aren't coroutines, so they don't need to be awaited.
As Eric mentioned, you'll also want to move your client.run('... down to the last line in your file, otherwise it'll block the rest of the script. Here's how the code should be structured:
# imports
# commands, events, functions
# last line
client.run('...
It looks like you're using some old documentation too, as d.py has moved over to rewrite (v1.x), and it looks as though the client.get_message() you were using is actually from v0.16.x.
I'd recommending wanting to read up on these changes to familiarise yourself with rewrite. Try to avoid outdated tutorials as well.
As a little headstart, your await client.get_message(channel, message_id) should become await channel.fetch_message(message_id).
References:
Rewrite docs
Client.get_channel()
TextChannel.fetch_message()

Categories