Discord.py - on_message() conflicting with bot command - python-3.x

Issue: When I set up on_message then the sendGif command does not work. When I comment out on_message then it works perfectly.
My Code:
bot = commands.Bot(command_prefix='!')
#----------------------------------------------------------#
#bot.event
async def on_message(message):
if message.author == bot.user:
return
content = message.content
print(content)
if "test" in content:
await message.channel.send("You test" + message.author.mention)
await message.add_reaction(":haha:")
else:
pass
#----------------------------------------------------------#
#bot.command()
async def sendGif(ctx, link):
embed = discord.Embed(title="Embed GIF")
embed.set_thumbnail(url="Gif Link here")
await ctx.send(embed=embed)

In your on_message event reference, you would have to add the line await bot.process_commands(message). The discord.py documentation explains the process_commands method:
This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.
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.
So, your on_message() event reference should look something like this:
#bot.event
async def on_message(message):
if message.author == bot.user:
return
content = message.content
print(content)
if "test" in content:
await message.channel.send("You test" + message.author.mention)
await message.add_reaction(":haha:")
await bot.process_commands(message)

hi just to the end on_message add
await bot.process_commands (message)
https://discordpy.readthedocs.io/en/latest/faq.html#why-does-on-message-make-my-commands-stop-working

Related

Discord bot bug not responding

Hello im new to stackoverflow i am developping a discord bot
but it does not react to commands in my dicsord server only in mp
here is my code
`
from discord.ext import commands
TOKEN = "X"
bot = commands.Bot(command_prefix="!")
#bot.event
async def on_ready():
print(f'{bot.user} succesfully logged in!')
#bot.event
async def on_message(message):
# Make sure the Bot doesn't respond to it's own messages
if message.author == bot.user:
return
if message.content == 'hello':
await message.channel.send(f'Hi {message.author}')
if message.content == 'bye':
await message.channel.send(f'Goodbye {message.author}')
await bot.process_commands(message)
#bot.command()
async def test(ctx, *, arg):
await ctx.send(arg)
def to_upper(argument):
return argument.upper()
#bot.command()
async def up(ctx, *, content: to_upper):
await ctx.send(content)
bot.run(TOKEN)
`
please help me
IN a server :
in a mp:
I tried a lot of thing
but nothing works i am making a nice bot for my friends and i am a noob for discord.py
ok, so, multiple #bot.event can be an issue, especially if you're looking for messages.
You need to set a listener.
I also see you do not have intents set up, so you also need to do that.
when looking for messages, you'll want something like this:
#bot.listen()#this makes the bot only listen for the messages
async def on_message(message):
# Make sure the Bot doesn't respond to it's own messages
if message.author == bot.user:
return
if message.content == 'hello':
await message.channel.send(f'Hi {message.author}')
if message.content == 'bye':
await message.channel.send(f'Goodbye {message.author}')
And just as an additional tip: use ctx.channel.send("message") instead of ctx.send("message").

Discord bot using discord.py command not working.PLZ

I just start learning how to write my own bot in discord.py. However, I followed the tutorial on Youtube, using exactly the same code but it doesn't work on my server.
import discord from discord.ext import commands
client = commands.Bot(command_prefix = '.')
#client.command(pass_context = True)
async def test(ctx):
await ctx.send('Pong!')
#client.event
async def on_ready():
print('Bot is ready')
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hello'):
await message.channel.send('Hello there.')
#client.event
async def on_member_join(member):
print(f'{member}has joined the server!!')
#client.event
async def on_member_remove(member):
print(f'Seeya,{member}. Oh wait\n can we?')
client.run('NzU1MjI2Mzk1MjM5Nzc2Mjg2.XGGNZA.s2qLVQMONMLqs1f8Zky9wtM6ZDo')
Overriding the default provided on_message forbids any extra commands from running. To fix this, add a client.process_commands(message) line at the end of your on_message.
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hello'):
await message.channel.send('Hello there.')
await client.process_commands(message)
Why does on_message make my commands stop working?

How do I get the discord bot to trigger commands on it's own message using discord.py?

Let's just say the user enters an invalid command, the bot suggests a command with (y/n)? If y, then the bot should trigger the suggested command.
I feel this can be achieved in 2 ways:
If the bot can trigger commands on its own message
If I can call the command from the other cogs
I can't seem to get either of em working.
Here is an example to help you guys help me better:
Let's just say this below code is from a cog called Joke.py:
#commands.command()
async def joke(self,ctx):
await ctx.send("A Joke")
And then there another cog "CommandsCorrection.py" that corrects wrong commands used by the user that are saved on data.json file:
#commands.Cog.listener()
async def on_message(self, message):
channel = message.channel
prefix = get_prefix(self,message)
if message.author.id == bot.id:
return
elif message.content.startswith(prefix):
withoutprefix = message.content.replace(prefix,"")
if withoutprefix in data:
return
else:
try:
rightCommand= get_close_matches(withoutprefix, data.keys())[0]
await message.channel.send(f"Did you mean {prefix}%s instead? Enter Y if yes, or N if no:" %rightCommand)
def check(m):
return m.content == "Y" or "N" and m.channel == channel
msg = await self.client.wait_for('message', check=check, timeout = 10.0)
msg.content = msg.content.lower()
if msg.content == "y":
await channel.send(f'{prefix}{rightCommand}')
elif msg.content == "n":
await channel.send('You said no.')
except asyncio.TimeoutError:
await channel.send('Timed Out')
except IndexError as error:
await channel.send("Command Not Found. Try !help for the list of commands and use '!' as prefix.")
in the above code await message.channel.send(f"Did you mean {prefix}%s instead? Enter Y if yes, or N if no:" %rightCommand) suggests the right command and await channel.send(f'{prefix}{rightCommand}') sends the right command.
So,for example:
user : !jok
bot : Did you mean !joke instead? Enter Y if yes, or N if no:
user : y
bot : !joke **I want to trigger the command when it sends this message by reading its own message or my just calling that command/function
How should I go about this?
One solution would be to separate the logic of your commands from the command callbacks and put it in it's own coroutines. Then you can call these coroutines freely from any of the command callbacks.
So you would turn code like this:
#bot.command()
async def my_command(ctx):
await ctx.send("Running command")
#bot.command()
async def other_command(ctx, arg):
if arg == "command":
await ctx.send("Running command")
Into something like this:
async def command_logic(ctx):
await ctx.send("Running command")
#bot.command()
async def my_command(ctx):
await command_logic(ctx)
#bot.command()
async def other_command(ctx, arg):
if arg == "command":
await command_logic(ctx)
#Patrick Haugh suggested this idea, he was on to something but wasn't really working but I got a way to get it working.
If you use the following method for a cog, you'll be able to read bot commands as well:
import discord
from discord.ext import commands
async def command_logic(self, ctx):
await ctx.send("Running command")
class Example(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
async def my_command(self, ctx):
await command_logic(self,ctx)
#commands.Cog.listener()
async def on_message(self, message):
if message.content == '!command':
ctx = await self.client.get_context(message)
await command_logic(self,ctx)
def setup(client):
client.add_cog(Example(client))

Get a single response from all commands

How to make bot send a specific message when users use any commands. so when user use !ping or any command it should send a default message. cozz for sometime i need to stop bot responding to all command except 1 command.
#bot.command(pass_context=True)
async def ping(ctx):
msg = "Pong {0.author.mention}".format(ctx.message)
await bot.say(msg)
You can do this in the on_message event. Example code below.
from discord.ext import commands
bot_prefix = '!'
client = commands.Bot(command_prefix=bot_prefix)
#client.event
async def on_ready():
print('client ready')
#client.command(pass_context=True)
async def ping(ctx):
msg = "Pong {0.author.mention}".format(ctx.message)
await bot.say(msg)
#client.event
async def on_message(message):
if message.startswith(bot_prefix):
await client.send_message(message.channel, 'Processing commands')
await client.process_commands(message)
client.run('TOKEN')

Discord on message and command at the same time [duplicate]

When I have on_message() in my code, it stops every other #bot.command commands from working. I've tried to await bot.process_commands(message), but that doesn't work either. Here is my code that I have:
#bot.event
#commands.has_role("Owner")
async def on_message(message):
if message.content.startswith('/lockdown'):
await bot.process_commands(message)
embed = discord.Embed(title=":warning: Do you want to activate Lock Down?", description="Type 'confirm' to activate Lock Down mode", color=0xFFFF00)
embed.add_field(name="\u200b", value="Lock Down mode is still in early development, expect some issues")
channel = message.channel
await bot.send_message(message.channel, embed=embed)
msg = await bot.wait_for_message(author=message.author, content='confirm')
embed = discord.Embed(title=":white_check_mark: Lock Down mode successfully activated", description="To deactivate type '/lockdownstop'", color=0x00ff00)
embed.add_field(name="\u200b", value="Lock Down mode is still in early development, expect some issues")
await bot.send_message(message.channel, embed=embed)
You have to place await bot.process_commands(message) outside of the if statement scope, process_command should be run regardless if the message startswith ”/lockdown”.
#bot.event
async def on_message(message):
if message.content.startswith('/lockdown'):
...
await bot.process_commands(message)
By the way, #commands.has_role(...) cannot be applied to on_message. Although there aren't any errors (because there’s checking in place), has_role wouldn't actually work as you would've expected.
An alternative to the #has_role decorator would be:
#bot.event
async def on_message(message):
if message.channel.is_private or discord.utils.get(message.author.roles, name="Admin") is None:
return False
if message.content.startswith('/lockdown'):
...
await bot.process_commands(message)
    

Resources