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')
Related
I cant start my discord bot in replti.com
Is their any fault in my code?
import os
client = discord.Client()
#client.event
async def on_ready():
print("I'm in")
print(client.user)
#client.event
async def on_message(message):
if message.author != client.user:
await message.channel.send(message.content[::-1])
my_secret = os.environ['TOKEN']
client.run(my_secret)
The method you are using is not good.
Rather do this from discord.ext import commands
and then insert commands as such:
#client.commands()
async def hello("")
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
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?
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))
I need to make a bot that listen for messages written in a server, and at the same time accept commands.
# Create the Discord client
client = discord.Client()
client = commands.Bot(command_prefix = '!')
client.remove_command('help')
#client.event
async def on_ready():
print('ready')
#client.event #ricerca messaggi
async def on_message(message):
# Ignore messages made by the bot
if(message.author == client.user):
return
a = ''
a += message.embeds[0]["description"]
if a == 'abcdef':
print(' aaaaa ')
#client.command()
async def hello():
await client.say('hello')
client.run('token')
How can I make it works?
I think the problem is that the bot continue cycling in the first event...
I read about sub_process but I do not understand how to use it.
You will need to add process_commands() at the end of your on_message. This is because overriding the default on_message forbids commands from running.
#client.event #ricerca messaggi
async def on_message(message):
# Ignore messages made by the bot
if(message.author == client.user):
return
a = ''
a += message.embeds[0]["description"]
if a == 'abcdef':
await message.channel.send(' aaaaa ')
await client.process_commands(message)
instead of #client.event() just do #client.listen() and it should work and remove client = discord.Client()