I am coding a discord bot and i think there has got to be a much easier/ simpler way to detect messages using the prefix for commands (and easy to expand in future), my code at the moment just scans each message to see if it contains the exact command, maybe a class will help?
#client.event
async def on_message(message):
# print message content
print(message.content)
# if the message came from the bot ignore it
if message.author == client.user:
return
# if the message starts with "!repeat" then say the message in chat
if message.content.startswith("!repeat"):
sentmessage = message.content.replace("!repeat", "")
await message.channel.send(sentmessage)
if "hello" in message.content.lower():
await message.channel.send("Hello!")
if message.content.startswith("!cleanup"):
if not message.author.guild_permissions.administrator:
await message.channel.send("You do not have permission to run this command!")
else:
num2c = 0
num2c = int(message.content.replace("!cleanup", ""))+1
print(num2c)
await message.channel.purge(limit=num2c)
num2c = num2c-1
cleanmessage = str("Cleared "+str(num2c)+" Messages.")
await message.channel.send(cleanmessage, delete_after=5)
You can use commands.Bot, it has a built-in command system, here's an example:
import discord
from discord.ext import commands
# enabling intents
intents = discord.Intents.default()
bot = commands.Bot(command_prefix='!', intents=intents)
#bot.command()
async def foo(ctx, *args):
await ctx.send('whatever')
# You also have all the functionality that `discord.Client` has
#bot.event
async def on_message(message):
# ...
# you always need to add this when using `commands.Bot`
await bot.process_commands(message)
bot.run('token')
Take a look at the introduction
Related
I am trying to make a discord bot.
I have attached the code below. When I run it there are no errors, the bot says 'Hello, world!', but doesn't answer the 'hi' (as it should answer 'Hello!').
What can I do to make it work?
import discord
client = discord.Client(intents=discord.Intents.default())
#client.event
async def on_ready():
general_channel = client.get_channel('CHANNEL ID')
await general_channel.send('Hello, world!')
#client.event
async def on_message(message):
if message.content == 'hi':
general_channel = client.get_channel('CHANNEL ID')
await general_channel.send('Hello!')
client.run ('TOKEN')
The issue is that you put intents=discord.Intents.default() in your client. This only gives you the default intents, which do not include the message_content intent.
You need this intent because you are asking the bot if message.content == 'hi':.
First, you need to enable the message_content on your bot
After that, type
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents
Now if your run the code, it should work.
i'm trying to make a discord bot and I want to add functionality that handles events like ?help, ?creator etc. I want to send a message if the command after ? is not recognised. This is my code:
import os
import discord
client = discord.Client()
unrecogcommand = "I don't recognize this command do **?help** for the list of the available
commands :3"
#client.event
async def on_ready():
print("We have logged in as {0.user}".format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('?'):
if message.content.startswith('?ownerfavOP'):
await message.channel.send("The server Owner really love Kaikai Kitan
https://www.youtube.com/watch?v=i1P-9IspBus :3")
if message.content.startswith('?creator'):
await message.channel.send("PashPash#7668 is the username of the creator and have a yt
channel https://www.youtube.com/channel/UCxJXY07JAsmJBaYf67KKk7Q")
if message.content.startswith('?help'):
await message.channel.send("Command available ```?help``` ```ownerfavOP```")
client.run(os.getenv('TOKEN'))
I would approach your command like that:
#client.event
async def on_message(message):
if message.author != client.user:
if message.content.startswith('?'):
if message.content.startswith('?ownerfavOP'):
# do something
elif message.content.startswith('?creator'):
# do something
elif message.content.startswith('?help'):
# do something
else:
print("Couldn't found that command.")
Note that I removed the return statment, since the command will automatically return if the message author equals the client user.
I hope this helps you, sheers!
import discord
from discord.ext.commands import Bot
bot = Bot(command_prefix='!')
TOKEN = 'TOKEN GOES HERE'
#bot.event
async def on_ready():
print(f'Bot connected as {bot.user}')
await bot.change_presence(activity = discord.Game('SAO'))
#Bellow this it the trouble part
#bot.command(name='test')
async def on_message(message):
if message.content == 'test':
await message.channel.send('Testing 1 2 3!')
await bot.process_commands(message)
bot.run(TOKEN)
I need help getting it to display 'Test 1 2 3!' when I type '!test'? Why the heck is it so hard to post ughhhhh they need more detail but I dint know what else to tell you.
The message comes fully as you typed it. You are checking if the user has typed in "test". Maybe change your if statement to be:
if message.content == "!test":
You are mixing the commands with the events, on_message is an event not a command. according to your example you should use commands. Here is an example
Command
#Run this using !test
#bot.command()
async def test(ctx):
await ctx.send('Testing 1 2 3!')
Event
#bot.event
async def on_message(message):
if message.content == 'hey':
await message.channel.send('Hello')
await bot.process_commands(message)
Read more on commands
I have a simple discord.py set up trying to use .ping, but in this current instance, the actual sending of ".ping" results in nothing being sent by the bot. Is there something I'm missing here?
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix = ".")
#bot.event
async def on_ready():
print("Everything's all ready to go~")
#bot.event
async def on_message(message):
author = message.author
content = message.content
print(content)
#bot.event
async def on_message_delete(message):
author = message.author
channel = message.channel
await bot.send_message(channel, message.content)
#bot.command()
async def ping():
await bot.say('Pong!')
bot.run('Token')
Ensure that you have await bot.process_commands(message) somewhere in your on_message event.
Why does on_message make my commands stop working?
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)
https://discordpy.readthedocs.io/en/latest/faq.html#why-does-on-message-make-my-commands-stop-working
I have searched around a lot for this answer, and I haven't found it. I want to use a suggestion command, that whenever someone uses it to suggest an idea, it DMs me, and me only.
You'll have to use the send_message method. Prior to that, you have to find which User correspond to yourself.
#client.event
async def on_message(message):
# we do not want the bot to reply to itself
if message.author == client.user:
return
# can be cached...
me = await client.get_user_info('MY_SNOWFLAKE_ID')
await client.send_message(me, "Hello!")
#client.event
async def on_message(message):
if message.content.startswith("#whatever you want it to be")
await client.send_message(message.author, "#The message")
Replace the hashtagged things with the words that you want it to be. eg.: #whatever you want it to be could be "!help". #The message could be "The commands are...".
discord.py v1.0.0+
Since v1.0.0 it's no longer client.send_message to send a message, instead you use send() of abc.Messageable which implements the following:
discord.TextChannel
discord.DMChannel
discord.GroupChannel
discord.User
discord.Member
commands.Context
Example
With bot.command() (recommended):
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
#bot.command()
async def suggest(ctx, *, text: str):
me = bot.get_user(YOUR_ID)
await me.send(text) # or whatever you want to send here
With on_message:
from discord.ext import commands
bot = commands.Bot()
#bot.event
async def on_message(message: discord.Message):
if message.content.startswith("!suggest"):
text = message.content.replace("!suggest", "")
me = bot.get_user(YOUR_ID)
await me.send(text) # or whatever you want to send here