Discord Bot Not Responding to Commands (Python) - 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..

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)

My discord bot is not responding to any commands in replit (Python)

I am a beginner at programming and just recently started using python. I'm trying to create a discord bot in an IDE called replit. Replit doesn't seem to be detecting errors since it lets me run the code without underlining or pointing any lines out. However, when I run the bot and type the command into discord the bot does not respond. When I go back to replit, it still doesn't detect any errors or point anything out in the console. I tried making bot commands in two different formats. The first one (in which the user says hello and the bot responds) works but the other two commands after that have multiple responses in which the bot is supposed to choose a randomized response from that list. Those two commands do not work. Here is the code:
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith ('^hello'):
await message.channel.send('Hello...( ・_・)ノ')
client.run(os.getenv('TOKEN'))
import os
import random
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
#help commands
bot = commands.Bot(command_prefix='^')
#bot.command(name='help')
async def help(ctx):
omori_responses = [
'OMORI’s main command categories are: FUN, CURRENCY, OMORI, SUNNY, BASIL, MARI, HERO, KEL, AUBREY, WHITESPACE, DREAMWORLD, and BLACKSPACE. Please use the command omo help <insert command category>',
'OMORI’s main command categories are: FUN, CURRENCY, OMORI, SUNNY, BASIL, MARI, HERO, KEL, AUBREY, WHITESPACE, DREAMWORLD, and BLACKSPACE. Please use the command omo help <insert command category>'
]
response = random.choice(omori_responses)
await ctx.send(response)
client.run(os.getenv('TOKEN'))
#whitespace commands
bot = commands.Bot(command_prefix='^')
#bot.command(name='ws')
async def white_space(ctx):
omori_responses = [
'Whitespace. A single black lightbulb hangs from the ceiling above...wherever above is',
'Whitespace. You have been here since as far back as you can remember...whenever that is. Everything is bright white. There are no walls. There is a floor...it is always cold.',
'Whitespace. Everything you need is here. A laptop, sketchbook, tissue box, blanket, and MEWO, your cat.',
'Whitespace. There is a door here. Beyond this door is a colorful world, unlike here...'
]
response = random.choice(omori_responses)
await ctx.send(response)
client.run(os.getenv('TOKEN'))
Whenever you write your own on_message() event reference (overriding the default discord.py on_message()), you need to call the Bot.process_commands() method.
#bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.content.startswith ('^hello'):
await message.channel.send('Hello...( ・_・)ノ')
await bot.process_commands(message)

Keywords in discord.py

I am trying to make a bot that responds to certain keywords but for some reason I can't seem to get it to work. E.g. if I were to say "This game is so hard" it would respond with "Hehe: Hard". (Childish I know). How would I edit this code to make it work because at the moment it refuses to work. thank you
#client.event
async def on_message(message):
if "hard" in message.content.lower():
await message.channel.send('Hehe "Hard"')
return
Where is this supposed to happen? In a server? Do other functions work, is your bot functioning at all? This code seems to have worked for me:
#client.event
async def on_message(message):
if not message.author.bot and "hard" in message.content.lower():
await message.channel.send('Hehe "Hard"')
Would it be possible for you to send all of the code you currently have?

Can an event execute a command? If so, how can I make my one do so?

So I am trying to have an event where, once the user types a specific word (not a command, literally a word/string), the event will trigger an existing command. Yeah you may wonder "Why not have the user type the command itself?" well, the reason why this isn't the case it's kinda hard to explain. Check this out:
My event will work only if the person types "nothing" (literally the word nothing). Eventually, the person won't expect the bot to actually take this as a command, and so he/she won't type it as command (with the prefix and all that) This is my code:
#client.command()
async def menu(ctx)
#here, well, goes what I want the command to do but it's not the issue
#client.event
async def on_message(message):
if message.content.startswith("nothing"):
#here idk how to execute the command up there. That's my question
I hope I am being clear with my issue. Don't worry about what the command exectues, or why the message for the event is "nothing". I just really want to know how to make this work.
Some friends suggested me to invoke the command, but I didn't really know how to do that, and everytime I would try it wouldn't work. Others suggested to call the function, but I also tried that and it wouldn't work. I don't know if I typed it correctly or if it simply won't work. I hope someone helps me out here.
Thanks in advance.
get_context, this takes a message object. Then invoke. Keep in mind, there are 3 downsides to using this method.
The converters (the type hints) won't be triggered. You need to pass the correct types into the arguments.
Checks will be bypassed. You could invoke an owner only command with a non-owner and it would still work.
If you still want to run all the checks, see can_run, which will run all the checks and raise an error if any checks fail.
If ctx.invoke was invoked outside of a command (eg eval), the error handler won't fire.
#client.command()
async def menu(ctx):
await ctx.send("Hello")
#client.event
async def on_message(message):
if message.content.startswith("nothing"):
ctx = await client.get_context(message)
await ctx.invoke(menu)
await client.process_commands(message)
If your client is a Bot instance you can use Bot.get_context() to create your own context and invoke the command from there:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
#bot.command()
async def menu(ctx):
await ctx.send('bar')
#bot.event
async def on_message(message):
if message.content.startswith('foo'):
ctx = await bot.get_context(message, cls=commands.Context)
ctx.command = bot.get_command('menu')
await bot.invoke(ctx)
await bot.process_commands(message)

I can't make commands in discord.py

So I'm having a problem with discord.py.
I'd like to make a command to kick/ban people.
I tried this at first and it didn't work, so I went to check if commands worked at all for me. Apparently it doesn't. I've tried everything and nothing works.
import discord
from discord.ext import commands
client = discord.Client()
bot = commands.Bot(command_prefix='!')
Token = 'TOKEN'
#bot.command(pass_context=True)
async def test(ctx):
await ctx.send('test')
client.run(Token)
I type !test on the channel but nothing happens.
I've tried basically everything.
I've changed the prefix, done: #bot.command(name='test), basically everything you could think of. Nothing works. I'd like to know if I'm missing something crucial. Like do I have to download something first or am I missing something in the code or are there permissions I need to enable. I've looked all over the discord py API reference. Anything would be helpful thanks.
Your problem is because of bot = commands.Bot(). You can use this code instead:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="!")
#client.command()
async def test(ctx):
await ctx.send('test')
client.run(token)
So you just have to delete bot = commands.Bot() then replace the #bot.command() with #client.command.

Categories

Resources