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!
Related
I have tried to search the web for ways to do this, but I've had no luck. I know this is seems very easy, but I am just starting with discord.py and I'm looking for some help. Thanks.
You can add this to your bot code.
#client.event
async def on_message(message):
if message.content == ‘verify’:
await message.channel.send(“A message”)
Here
#client.event
async def on_message(message):
if message.content == "verify":
#Your code
import discord
token = '<insert-token-here>'
# Make sure to enable the Message Content intent in the Discord developer portal
client = discord.Client(intents=discord.Intents.all())
#client.event
async def on_ready():
print(f"Logged on as {client.user}")
#client.event
async def on_message(message: discord.Message):
if message.author == client.user:
# skip message from self
return
print(f"Message: {message.content}")
await message.channel.send(message.content)
if __name__ == '__main__':
client.run(token)
So, basically i was trying to make a bot for discord using python and this is my first project so i was trying out new stuffs
here's my code
import discord
from http import client
from discord.ext import commands
client = discord.Client()
client = commands.Bot(command_prefix='`')
#client.event
async def on_ready():
print("Bot is online")
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content == 'hello':
await message.channel.send('Welcome to the server, human')
#client.command
async def info(ctx):
await ctx.send(ctx.guild)
client.run(#mytokenishereicantshareit)
as you can see i am completely new to programming in general, so if you may help me out, the bot is saying "Bot is online" in output and it's getting online in my server its not showing any errors either. but it's none of my commands are working, like the "hello" and `info.
Edit : This issue has been fixed, There are two possible solutions for this either you can replace the #client.event with #client.listen or just add a await bot.process_commands(message) after
if message.content == 'hello':
await message.channel.send('Welcome to the server, human')
Part like
if message.content == 'hello':
await message.channel.send('Welcome to the server, human')
await bot.process_commands(message)
and you're done.
Firstly, remove the client = discord.Client() bit because the bot already does that, and secondly, add a bracket after the #client.command so it's #client.command()
This bot that I am making on Discord is just a hangman game. I've been able to do the most basic part of the bot and now am trying to add a 2nd command. But there is an error on line 24 that pops up saying "redefinition of unused 'on_message' from line 13".
The 2nd command is supposed to print something once a person sends "$start". However, it does not work when I do so.
This is my current code:
import discord
import random
import os
client = discord.Client()
#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("$help"):
await message.channel.send("To start your game, type '$start'")
client.run(os.getenv("TOKEN"))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("$start"):
await message.channel.send("You will have to guess a month. Have fun :) (The first letter will be always capital)")
This is where the problem lies:
#client.event
async def on_message(message): #this is line 24
if message.author == client.user:
return
if message.content.startswith("$start"):
await message.channel.send("You will have to guess a month. Have fun :) (The first letter will be always capital)")
Issue:
You have redefined the on_message function. This means, there are 2 functions with the same name on_message.
Solution:
Since you have been using some if statements to decide which function to execute on which command, you can group all if statements into one function, so your code would look like:
import discord
import random
import os
client = discord.Client()
#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("$help"):
await message.channel.send("To start your game, type '$start'")
if message.content.startswith("$start"):
await message.channel.send("You will have to guess a month. Have fun :) (The first letter will be always capital)")
client.run(os.getenv("TOKEN"))
The error states what it means literally: you are redefining the on_message event for the same Client.
Typically you would use the commands.Bot client from discord.ext branch instead of the native Client when implementing bots with commands.
So this piece of code:
client = discord.Client()
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("$help"):
await message.channel.send("To start your game, type '$start'")
would be replaced with this:
client = commands.Bot("$")
#client.command()
async def help(ctx):
if ctx.author == client.user:
return
await message.channel.send("To start your game, type '$start'")
However FYI, you can have multiple on_message listeners in your code through the Bot.listen() decorator.
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
import discord
import asyncio
client = discord.Client()
#client.event
async def on_ready():
print ("I’m Now Online")
#client.event
async def on_message(message):
if message.author == client.user:
return
elif message.content.startswith("deletethis"):
I’m wonder how I could be able to add to this to delete the above command when the author of the message sends the command above.
May someone help create one? I’ve tried my self by brain and didn’t find anything online so I’m looking for some help maybe.
for async just do
await client.delete_message(message)
otherwise for rewrite just do
await message.delete()
Finished code:
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("deletethis"):
await asyncio.sleep(1)
await message.delete()