How to enable more than one command [duplicate] - discord

This question already has answers here:
Why doesn't multiple on_message events work?
(2 answers)
Closed 3 years ago.
I'm fairly new to this format of discord.py and I can't seem to get two commands to work.
For example, I have the command; 'hello' and the command 'valid'. Whenever I activate the bot, it only responds to either 'valid' or 'hello', never both.
Is there some way to fix this?
I've tried very little as this problem is very new to me and I have no idea how to tackle it.
Here's the code that I've used for commands:
#client.event
async def on_message(message):
if message.content.startswith('!hello'):
messages= ["*tips hat* G'day ", "Yeehaw pardner, ", "Howdy, ", "Gutentag! "]
await client.send_message(message.channel, random.choice(messages) + message.author.mention)
#client.event
async def on_message(message):
if message.content.startswith('!valid'):
rannum = random.randint(0, 100)
await client.send_message(message.channel, (message.author.mention + " is",rannum,"% valid!"))
client.run(TOKEN)
No error messages show up when this happens. I will appreciate any help possible in this situation!

Like what #Patrick Haugh mentioned, you can only have 1 of on_message event.
Plus, you probably only need one of that event. Since on_message defines a event that occurs when you recieve a message from someone. You can just check what the message's content is and do actions based on that.
Like so:
#client.event
async def on_message(message):
if message.content.startswith('!valid'):
rannum = random.randint(0, 100)
await client.send_message(message.channel, (message.author.mention + " is",rannum,"% valid!"))
elif message.content.startswith('!hello'):
messages= ["*tips hat* G'day ", "Yeehaw pardner, ", "Howdy, ", "Gutentag! "]
await client.send_message(message.channel, random.choice(messages) + message.author.mention)

Related

How to set up a discord bot that replies upon mention to messages which contain certain words without prefix command?

I'm trying to create a simple discord bot that replies with mention to messages that contain certain words.
Also, I want the bot to respond only when it gets mentioned and without a prefix.
This was my try, but the bot didn't reply at all to the messages.
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='')
#client.event
async def on_message(message):
if client.user.mentioned_in(message){
if message.content == "Hi"{
await message.channel.send(f"Hello {message.author.mention}")
}
if message.content == "How are you?"{
await message.channel.send(f"I'm good {message.author.mention}")
}
}
client.run("TOKEN")
message.content contains the entirety of the message text so when you do #mybot Hi, the message.content will be something like: <#MY_BOT_ID> hi. Your code is checking that the message.content is exactly equals to either Hi or How are you? and that is not going to be the case.
You could use Python's in operator to check for certain text:
#client.event
async def on_message(message):
if client.user.mentioned_in(message):
# making the text lowercase here to make it easier to compare
message_content = message.content.lower()
if "hi" in message_content:
await message.channel.send(f"Hello {message.author.mention}")
if "how are you?" in message_content:
await message.channel.send(f"I'm good {message.author.mention}")
client.run("TOKEN")
Though, this isn't perfect. The bot will also respond to anything with the characters hi in. You could split the content of the messages by word and check that or you could use regular expressions. See this post for more info.
Additionally, your python code had some {} brackets - which is invalid syntax for if statements - I've corrected that in my example. Consider looking up python syntax.

Discord Clear Command [duplicate]

This question already has answers here:
How to make discord.py bot delete its own message after some time?
(3 answers)
Closed 9 months ago.
Trying to get the bot to clear message after waited time but i can't seem to figure out why.
It waits but then doesn't clear the bots message, i think I've got the wrong variable but I'm not sure what it is.
#client.command()
#commands.has_permissions(administrator = True)
async def clear(ctx, amount = 5):
await ctx.channel.purge(limit=amount + 1)
await ctx.send("Cleared " + str(amount) + " messages")
time.sleep(2.5)
await ctx.message.delete()
Your command should be like this. Use asyncio library
await ctx.channel.purge(limit=amount+1)
await asyncio.sleep(your_time)
await ctx.send("Done 👌", hidden=True)
You'd wanna use something like this. It's a basic clear command.
#client.command()
#commands.has_permissions(manage_messages=True)
async def clear(ctx, amout : int):
await ctx.channel.purge(limit=amout)

In discord.py when I use more than 1 `on_message` it does not works, only the last one works

This is my code, and on_message is not working when used twice, only the 2nd one is working. Please help me.
async def on_message(message):<br>
if message.content.startswith('-coinflip'):<br>
embedVar = discord.Embed(<br>
title="Toss",<br>
description=(f'You got {random.choice(heads_tails)}'),<br>
color=(0xFF0000))<br>
print(f'-coinflip command used by {message.author}')<br>
await message.channel.send(embed=embedVar)<br>
#client.event<br>
async def on_message(message):<br>
if message.content.startswith('-help'):<br>
embedVar = discord.Embed(<br>
title="Help arrived!",<br>
description="So, it looks like you need help, let me help you",<br>
colour=0xFF0000)<br>
embedVar.add_field(name="Bot Prefix", value="-", inline=False)<br>
embedVar.add_field(name="Moderation Commands",<br>
value="-help",<br>
inline=True)<br>
embedVar.add_field(name="Fun commands", value="-coinflip", inline=True)<br>
embedVar.set_thumbnail(<br>
url=<br>
"https://media.discordapp.net/attachments/923531605660815373/974248483479494686/charizard-mega-charizard-y.gif"<br>
)<br>
print(f'-help command used by {message.author}')<br>
await message.channel.send(embed=embedVar)<br>```
Here's the answer I wrote but couldn't post:
You cannot have 2 on_message event listeners. You can merge the two event listeners and their responses by using if...elif like this instead:
#bot.event
async def on_message(message): #When any message is sent
if message.content.startswith('-coinflip'):
embedVar = discord.Embed(
title="Toss",
description=f'You got {random.choice(heads_tails)}',
color=(0xFF0000))
print(f'-coinflip command used by {message.author}')
await message.channel.send(embed=embedVar)
elif message.content.startswith('-help'):
embedVar = discord.Embed(
title="Help arrived!",
description="So, it looks like you need help, let me help you",
colour=0xFF0000)
embedVar.add_field(name="Bot Prefix", value="-", inline=False)
embedVar.add_field(name="Moderation Commands",
value="-help",
inline=True)
embedVar.add_field(name="Fun commands", value="-coinflip", inline=True)
embedVar.set_thumbnail(
url="https://media.discordapp.net/attachments/923531605660815373/974248483479494686/charizard-mega-charizard-y.gif")
print(f'-help command used by {message.author}')
await message.channel.send(embed=embedVar)
elif is the same as else if; in this case, if the message's content doesn't start with "-coinflip" and starts with "-help", it creates and sends an Embed.
I've replaced the heads_tails variable for a fully-functioning code:
from discord.ext import commands
import discord
import discord.utils
import random
intent = discord.Intents(messages=True, message_content=True, guilds=True)
bot = commands.Bot(command_prefix="", description="", intents=intent)
heads_tails = ("Heads", "Tails") #Replace this with your sequence
#bot.event
async def on_ready(): #When the bot comes online
print("It's online.")
#bot.event
async def on_message(message): #When any message is sent
if message.content.startswith('-coinflip'):
embedVar = discord.Embed(
title="Toss",
description=f'You got {random.choice(heads_tails)}',
color=(0xFF0000))
print(f'-coinflip command used by {message.author}')
await message.channel.send(embed=embedVar)
elif message.content.startswith('-help'):
embedVar = discord.Embed(
title="Help arrived!",
description="So, it looks like you need help, let me help you",
colour=0xFF0000)
embedVar.add_field(name="Bot Prefix", value="-", inline=False)
embedVar.add_field(name="Moderation Commands",
value="-help",
inline=True)
embedVar.add_field(name="Fun commands", value="-coinflip", inline=True)
embedVar.set_thumbnail(
url="https://media.discordapp.net/attachments/923531605660815373/974248483479494686/charizard-mega-charizard-y.gif")
print(f'-help command used by {message.author}')
await message.channel.send(embed=embedVar)
Also, is "-help" a moderation command? And, try searching for and solving such problems yourself. StackOverflow shouldn't be the first place to ask such questions.

how to add reaction to a specifc user?

I've been working on this piece of code:
#client.event
async def lol(message,ctx):
if ctx.author.id == <user_id>:
await message.add_reaction('❤️')
else:
return
I am pretty sure that it is developed correctly, yet I am not getting the desired results.
I am pretty sure that if you check the console, an HTTP error would have been encountered. That's because you directly pasted the emoji in the function parameter. You have to add its unicode value. In your case:
await message.add_reaction(u'\u2764')
You are using an event decorator rather than a command, unless you were trying to detect if the user reacted, but its still completely off. What it looks like, the command that is called will send a message and the bot will react to it.
#client.command()
async def lol(ctx):
message = await ctx.send(f"{ctx.author.mention}, lol")
await message.add_reaction('😂')
If you then want to detect if the user had reacted to the emoji, you can use a event, but an on_reaction_add:
#client.event
async def on_reaction_add(reaction, user):
if reaction.emoji == '😂':
await user.send("Lol")

discord.py bot repeating messages

hi i am trying to make a discord.py bot so i can have a gif chat channel but when someone types a message in that channel then my bot starts repeating his message, pls help if u know.
my code:
#client.event
async def on_message(message):
with open("gif_chater.json", "r+") as file:
data=json.load(file)
if str(message.channel.id) in data:
if message.content.startswith("https://tenor.com/"):
print("wOw")
if not message.content.startswith("https://tenor.com/") and not message.author.id == "760083241133932544":
await message.channel.send("lol pls use gifs in this channel : )")
await message.delete()
exit
The on_message event
The issue is that the bot is constantly responding to itself, and it's because the on_message event triggers not just when users send a message but also when the bot sends a message. As such, once it tells the user that they must only post tenor gifs, it reacts to its own message and goes into an infinite loop, posting and deleting its responses.
Preventing the bot from responding to itself
To prevent the bot from responding to it's own messages, you should add a check at the start of the event like in the discord.py docs:
#client.event
async def on_message(message):
if message.author == client.user:
return
...
Also, the ID check at the end
The last condition in your code before it decides to send a message is checking the ID of the messenger (not message.author.id == "760083241133932544"). I don't know whether it's meant to avoid deleting you or the bot's messages but regardless, the check itself is bugged. message.author.id returns an integer but is then being compared to a string, and due to the conflicting types, will always return False.
To fix it, change your ID to an integer by removing the quotes: not message.author.id == 760083241133932544. As well, you should use the not-equals operator != instead of not to improve readability: message.author.id != 760083241133932544.
Also, since you already checked if the message starts with the website link, you can use an elif statement instead of rechecking the condition, since else/elif guarantees that the previous condition was false (aka, that the message didn't start with the website link):
if message.content.startswith("https://tenor.com/"):
print("wOw")
elif message.author.id != 760083241133932544:
await message.channel.send("lol pls use gifs in this channel : )")
await message.delete()
Fixes combined
With the new changes, your function could look something like this:
#client.event
async def on_message(message):
# Don't respond to the bot's own messages
if message.author == client.user:
return
with open("gif_chater.json") as file:
data = json.load(file)
if str(message.channel.id) in data:
if message.content.startswith("https://tenor.com/"):
print("wOw")
elif message.author.id != 760083241133932544:
await message.channel.send("lol pls use gifs in this channel : )")
await message.delete()

Resources