Basically, everything appears to work fine and start up, but for some reason I can't call any of the commands. I've been looking around for easily an hour now and looking at examples/watching videos and I can't for the life of me figure out what is wrong. Code below:
import discord
import asyncio
from discord.ext import commands
bot = commands.Bot(command_prefix = '-')
#bot.event
async def on_ready():
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
#bot.event
async def on_message(message):
if message.content.startswith('-debug'):
await message.channel.send('d')
#bot.command(pass_context=True)
async def ping(ctx):
await ctx.channel.send('Pong!')
#bot.command(pass_context=True)
async def add(ctx, *, arg):
await ctx.send(arg)
The debug output I have in on_message actually does work and responds, and the whole bot runs wihout any exceptions, but it just won't call the commands.
From the documentation:
Overriding the default provided on_message forbids any extra commands from running. To fix this, add a bot.process_commands(message) line at the end of your on_message. For example:
#bot.event
async def on_message(message):
# do some extra stuff here
await bot.process_commands(message)
The default on_message contains a call to this coroutine, but when you override it with your own on_message, you need to call it yourself.
Ascertained that the problem stems from your definition of on_message, you could actually just implement debug as a command, since it appears to have the same prefix as your bot:
#bot.command()
async def debug(ctx):
await ctx.send("d")
So I am setting up a bot, and I am testing it out. A little function I have there is to kick, ban and unban users, set up in a cog, which goes as follows:
import discord
from discord.ext import commands
class Moderator(commands.Cog):
def __init__(self, bot):
self.bot = bot
#KICK command
#commands.command()
#commands.has_permissions(kick_members=True)
async def kick(self, ctx, member : discord.Member, *, reason=None):
('About to kick')
await member.kick(reason = reason)
#commands.command()
#commands.has_permissions(kick_members=False)
async def kick(self, ctx, member : discord.Member, *, reason=None):
await ctx.send(f'You do not have permission to kick any member, {ctx.message.author.mention}!')
#BAN command
#commands.command()
#commands.has_permissions(ban_members=True)
async def ban(self, ctx, member : discord.Member, *, reason=None):
await member.ban(reason = reason)
await ctx.send(f'Banned {member.mention}')
#commands.command()
#commands.has_permissions(kick_members=False)
async def ban(self, ctx, member : discord.Member, *, reason=None):
await ctx.send(f'You do not have permission to ban any member, {ctx.message.author.mention}!')
#UNBAN command
#commands.command()
#commands.has_permissions(ban_members=True)
async def unban(self, ctx, *, member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.send(f'Unbanned {user.mention}')
return
#commands.command()
#commands.has_permissions(kick_members=False)
async def unban(self, ctx, member : discord.Member, *, reason=None):
await ctx.send(f'You do not have permission to unban any member, {ctx.message.author.mention}!')
#CLEAR MESSAGES
#commands.command()
#commands.has_permissions(manage_messages=True)
async def clear(self, ctx, amount=2):
await ctx.channel.purge(limit=amount)
#commands.command()
#commands.has_permissions(manage_messages=False)
async def clear(self, ctx, amount=2):
await ctx.send(f'You do not have permission to delete messages in this way, {ctx.message.author.mention}!')
def setup(bot):
bot.add_cog(Moderator(bot))
Now I have formatted the above code with some spaces so that it fits in one codeblock, so you might face indentation errors if you copy paste it elsewhere.
Moving on, the bot itself has Administrator rights and separate Kicking and Banning rights too. It is also placed at the top of the role hierarchy, which is seen as:
The name of my bot is JunkBot.
Now, whenever I, being the server owner, try using the command .kick #user, it pops up the following error:
The textual form of the error is:
Ignoring exception in command kick:
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 777, in prepare
if not await self.can_run(ctx):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 1087, in can_run
return await discord.utils.async_all(predicate(ctx) for predicate in predicates)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\utils.py", line 348, in async_all
for elem in gen:
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 1087, in <genexpr>
return await discord.utils.async_all(predicate(ctx) for predicate in predicates)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 1790, in predicate
raise MissingPermissions(missing)
discord.ext.commands.errors.MissingPermissions: You are missing Kick Members permission(s) to run this command.
Similar errors are raised for the ban, unban and clear messages commands.
Interesting part is, I, being the owner, get this error, but supposing another user, a friend of mine who does not have the kicking, banning or message managing role, runs their lines of codes perfectly, where she gets the message from the bot that she does not have permission to kick, ban or clear messages. The screenshot is enclosed.
I don't know where I went wrong. Please help me debug it.
Your problem is in rewriting the functions. I'm assuming that you are hoping to make an errorhandler. However, this isn't the way to do so.
Instead of rewriting the functions with different has_permissions arguments, you will need to make a proper version of an error handler.
First, delete all the duplicate functions. These are the functions that require False on the has_permissions arguments.
Next, make a errorhandler function. You can make one for the Cog commands only, for all commands, or a specific command. If its for all commands, you will use the event on_command_error, (I suggest using it in the main file or as a listener). If it's for the Cog, then you will have to use cog_command_error. If it's for a specific command, you should make the Command.error decorator.
I will be showing the Cog specific handler, but switching back and forth shouldn't take too long.
# Indent into Cog level
async def cog_command_error(self, ctx, error):
# Allows us to check for original exceptions raised and sent to CommandInvokeError.
# If nothing is found. We keep the exception passed to on_command_error.
error = getattr(error, 'original', error)
if isinstance(error, commands.BotMissingPermissions): # Check if bot is missing permissions
await ctx.send(f'I am missing these permissions to do this command:\n{self.lts(error.missing_perms)}')
elif isinstance(error, commands.MissingPermissions): # Check if user is missing permissions
await ctx.send(f'You are missing these permissions to do this command:\n{self.lts(error.missing_perms)}')
#staticmethod
def lts(list_: list): # Used to make reading the list of permissions easier.
"""List to string.
For use in `self.on_command_error`"""
return ', '.join([obj.name if isinstance(obj, discord.Role) else str(obj).replace('_', ' ') for obj in list_])
Here is the list of exceptions you can use in the handler: Exceptions
FYI, the lts function I have isn't required for the handler. It's used to make the list of permissions readable in one string. You can always remove it or change it to your needs.
That is not how error handling works. You should check out the error handling section of the docs for how to deal with missing permissions.
EDIT because people reminded me to give some more information
You shouldn't be handling errors through has_permissions. From what I can tell from your code, you are looking to send a message when the invoker doesn't have the permissions required to use the command. This can be achieved with an error handler. THe error handler will catch the MissingPermissions exception and do something based on that. Here is an example:
#commands.Cog.listener()
async def on_command_error(self, ctx, error): #this is the event that catches errors
if isinstance(error, commands.MissingPermissions): #seeing if the error is the missing permissions error
await ctx.send(f"You do not have the permission to do this, {ctx.author.mention}!")
This uses a global error handler, meaning that whenever an error is caught, this will catch it. However if you want an error handler for each command, all you have to change is the decorater and function name. EX:
#kick.error
async def on_kick_error(self, ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send(f"You do not have the permission to kick any member, {ctx.author.mention} ")
This one will only trigger on the kick command error, none of the others.
#f spam
async def on_message(message):
if message.author.bot:
return
elif message.content.lower() == 'f':
await message.channel.send('f')
await bot.process_commands(message)
this is my current code for an f spam or sends an f each time a user does.
I was wanting to make this command toggleable and also server/guild limited if possible.
for example someone says !fspam and it gets toggled and switched off and when done the same again it gets turned on. OR it could be !fspam on/ !fspam off
You can use Command.enable, where you can use command.update to. This will raise the DisabledCommand error.
Also please dont just copy and paste the code, try understanding what I did.This will disable it for all the guilds to. If you want it per server then you will need to use a database.
For example:
#client.command()
async def enable(ctx,*,command):
command = client.get_command(command)
command.update(enabled=True)
await ctx.send(f"{command} enabled!")
#client.command()
async def disable(ctx,*,command):
command = client.get_command(command)
command.update(enabled=False)
await ctx.send(f"{command} disabled!")
I've been working on this piece of code:
#client.event
async def lol(message,ctx):
if ctx.author.id == <user_id>:
await message.add_reaction('❤️')
else:
return
I am pretty sure that it is developed correctly, yet I am not getting the desired results.
I am pretty sure that if you check the console, an HTTP error would have been encountered. That's because you directly pasted the emoji in the function parameter. You have to add its unicode value. In your case:
await message.add_reaction(u'\u2764')
You are using an event decorator rather than a command, unless you were trying to detect if the user reacted, but its still completely off. What it looks like, the command that is called will send a message and the bot will react to it.
#client.command()
async def lol(ctx):
message = await ctx.send(f"{ctx.author.mention}, lol")
await message.add_reaction('😂')
If you then want to detect if the user had reacted to the emoji, you can use a event, but an on_reaction_add:
#client.event
async def on_reaction_add(reaction, user):
if reaction.emoji == '😂':
await user.send("Lol")
I am writing a Discord bot but whenever I use this ,rockpaperscissors command, after the game has finished I can't use any of my other commands like ,help. Why is this?
elif message.content == ",rockpaperscissors":
await message.channel.send("```\nRock Paper Scissors\n~~~~~~~~~~~~~~~~~~~~~\nSend your move in the format ,[move] e.g. ,rock\n```")
#client.event
async def on_message(message):
_ = str(message.content).lower()[1::]
computer = random.choice(RPS)
await rockPaperScissorsChecker(message, _, computer)
return
It's not possible to tell from the code that you've given, but here are a couple possibilities of what might be causing it.
Scenario #1
You have multiple on_message events.
When using events, you don't need to write multiple ones - you can use if/elif statements to your advantage. If you do choose to have multiple, then the one that's been defined the latest in the script will be the "active" one.
Here's how to separate commands in on_message:
#client.event
async def on_message(message):
if message.author.bot:
return
elif message.content.lower().startswith(",rockpaperscissors"):
# code for the cmd here
elif message.content.lower().startswith(",cmd2"):
# second cmd code here
# etc. etc.
Scenario #2
You're using command decorators and on_message without processing the commands.
When overriding (writing your own) on_message event, you need to call Bot.process_commands() in order for the registered commands to work. Behind the scenes there's a default on_message event which has this already done, but because you're rewriting your own, you'll need to add it:
#client.event
async def on_message(message):
await client.process_commands(message)
# rest of your on_message code
References:
on_message()
Bot.process_commands() - "By default, this coroutine is called inside the on_message() event. If you choose to override the on_message() event, then you should invoke this coroutine as well."
commands.Command() - The command decorator.