How to use max_concurrency() in Discord.py bot - python

I have this piece of code:
from discord.ext import commands
#bot.command()
#commands.max_concurrency(1,per=commands.BucketType.default,wait=False)
async def function(ctx,arg1,arg2,arg3):
the max_concurrency() works, but when the max concurrency is met, i want it to send a message to the author that says the bot is busy, I've tried the MaxConcurrencyReached exception handle but it simply doesn't work, anyone know how to work with this command?

I figured it out.
After defining the function I want to put the max concurrency limit:
from discord.ext import commands
#bot.command()
#commands.max_concurrency(1,per=commands.BucketType.default,wait=False)
async def function(ctx,arg1,arg2,arg3):
Then you have to handle it with on_command_error() and isinstance(). For example:
#bot.event
async def on_command_error(ctx,error):
await ctx.message.delete()
if isinstance(error, commands.MaxConcurrencyReached):
await ctx.author.send('Bot is busy! Please retry in a minute')
return

Related

how can i make my discord bot do the !say command?

I've never coded before so I'm pretty new and I'm trying python on replit, I've searched a lot and this is what I did so far but it isn't working. (ignore the reverse part)
import os
import discord
from keep_alive import keep_alive
client = discord.Client(intents=discord.Intents.default())
#client.event
async def on_ready():
print("I'm in")
print(client.user)
#client.event
async def on_message(message):
if message.content.startswith("!reverse"):
await message.channel.send(message.content[::-1])
my_secret = os.environ['DISCORD_BOT_SECRET']
client.run(my_secret)
keep_alive()
my_secret = os.environ['DISCORD_BOT_SECRET']
client.run(my_secret)
async def on_message(message):
echo = message.content.split(" ", 1)[1]
if message.content.startswith("!say"):
await message.channel.send(echo)
I want the bot to be like this:
me:!say blah blah blah
bot: blah blah blah
thanks to anyone that answers
There's a lot of problems here
Intents.default() doesn't include the message contents intent, so you won't be able to read messages. For more info on intents and how to enable them, read the docs: https://discordpy.readthedocs.io/en/stable/intents.html
You've got two on_message functions, which doesn't work. You can't have multiple functions with the same name. Combine them into one instead.
Never put any code underneath client.run() - it'll never get executed.
You've got two client.run()'s. Why?
The on_message at the bottom is missing the #client.event decorator, so even if you wouldn't have 2 of them it still wouldn't be invoked.
Why don't you use a Bot with commands instead of manually parsing everything in on_message? https://discordpy.readthedocs.io/en/stable/ext/commands/index.html
Replit isn't made to run bots on and will cause you a lot of trouble. Consider hosting it on an actual VPS (or during the development phase - just locally).
Ok, there's some other changes to make first.
You're not using commands, and are instead looking for messages(technically nothing wrong with that, but it can cause unnecessary issues)
I'll modify the code, and hopefully, it works.
import os
import discord
from keep_alive import keep_alive
client= commands.Bot(command_prefix='!', intents=discord.Intents.default())
#client.event
async def on_ready():
print("I'm in")
print(client.user)
#client.command()
async def reverse(ctx,*,message):
await ctx.message.delete()
await ctx.channel.send(message[::-1])
my_secret = os.environ['DISCORD_BOT_SECRET']
client.run(my_secret)
keep_alive()
my_secret = os.environ['DISCORD_BOT_SECRET']
client.run(my_secret)
#client.command()
async def say(ctx, *, message):
await ctx.message.delete()
await ctx.channel.send(message)

Discord.py code doesn't work! How can i fix this?

Why does not this work? When I run the code and try the !test, it doesn't even send an error to the terminal. How can i fix this?
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
bot.command()
async def test(ctx):
ctx.send("test")
bot.run(token)
You're missing the decorator symbol
#bot.command()
also, the send message instruction inside your test function needs to be awaited
#bot.command()
async def test(ctx):
await ctx.send("test")

how to make an event stop overlapping a command

I've had this problem for a while, trying to use both commands and events in one file.
I know that there's a function called process_commands(), but the bot doesn't seem to have this function. Is there anything I need to import though? (else than discord.ext and commands)
picture of code: https://i.stack.imgur.com/Gdvj8.png
you should add await client.process_commands(message) on top of the on_message event
#client.event
async def on_message(message):
await client.process_commands(message)
# do other stuff
also message.send('...') in your command doesnt work, it must be awaited since its a coroutine. (Docs)
#client.command()
async def test(ctx): # ctx instead of message
await ctx.send("test")

Discord Bot Not Responding to Commands (Python)

I've just gotten into writing discord bots. While trying to follow online instructions and tutorials, my bot would not respond to commands. It responded perfectly fine to on_message(), but no matter what I try it won't respond to commands. I'm sure it's something simple, but I would appreciate the help.
import discord
from discord.ext.commands import Bot
from discord.ext import commands
bot = commands.Bot(command_prefix='$')
TOKEN = '<token-here>'
#bot.event
async def on_ready():
print(f'Bot connected as {bot.user}')
#bot.event
async def on_message(message):
if message.content == 'test':
await message.channel.send('Testing 1 2 3')
#bot.command(name='go')
async def dosomething(ctx):
print("command called") #Tried putting this in help in debugging
await message.channel.send("I did something")
bot.run(TOKEN)
Picture of me prompting the bot and the results
I made the same mistake at first.
#bot.event
async def on_message(message):
if message.content == 'test':
await message.channel.send('Testing 1 2 3')
This function overiding the on_message event so it is never sent to bot.command()
To fix it you just have to add await bot.process_commands(message) at the end of the on_message function:
async def on_message(message):
if message.content == 'test':
await message.channel.send('Testing 1 2 3')
await bot.process_commands(message)
Haven't tested yet but that should fix your issue.
Ok. First of all, the only import statement that you need at the top is from discord.ext import commands. The other two are not necessary.
Second of all, I tried messing around with your code myself and found that the on_message() function seems to interfere with the commands so taking that out should help.
Third of all, I only found this out when I duplicated one of my own working bots and slowly changed all of the code until it was identical to yours. For some reason python didn't like it when I just copied and pasted your code. I have never seen something like this before so I honestly don't know what to say other than that your code is correct and should work as long as you take the on_message() function out.
Here's the final code that I got working:
from discord.ext import commands
bot = commands.Bot(command_prefix="$")
TOKEN = "<token-here>"
#bot.event
async def on_ready():
print(f'Bot connected as {bot.user}')
#bot.command()
async def dosomething(ctx):
await ctx.send("I did something")
bot.run(TOKEN)
As you can see the only things that I have changed from your code are that I removed the redundant imports at the top, and I deleted the on_message() function. It works perfectly like this on my end so I would suggest that you re-type it out like this in a new file and see if that works.
If that doesn't work for you then my next guess would be that there is a problem with your installation of discord.py so you might try uninstalling it and then reinstalling it.
If none of that helps let me know and I will see if I can help you find anything else that might be the cause of the problem.
just put client.process_commands(message)
in on_message event at last..

Discord bot with async error

When ever I run the code I get an error with async, I have imported asyncio to attempt to fix this but the errors keep flooding in
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
bot = command.Bot(command_prefix="=")
#bot.event
async def on_ready():
print ("Bot Onine!")
print ("Hello I Am " + bot.user.name)
print ("My ID Is " + bot.user.id)
The error I get:
async def on_ready():
^
SyntaxError: invalid syntax
Please if anyone knows a fix
To use the async keyword you need python 3.5 or above. If you're using python 3.4 or below you can't use async.
the alternative is to decorate the method with coroutine. This code
#bot.event
async def on_ready():
...
Becomes:
#bot.event
#asyncio.coroutine
def on_ready():
....
Since discord events already need the bot.event decorator, discord.py api provides the async_event decorator to do both the coroutine and the event decoration in a single call, so you can also write it like this:
#bot.async_event
def on_ready():
....
In the same vein, you can't use await either, so you must use yield from instead.
await bot.say('Some response')
becomes
yield from bot.say('Some response')

Categories

Resources