khalrab27
khalrab27

Reputation: 83

How do I check if a message is sent by a bot or not in discord.py?

I made a Hello Bot using discord.py and Python v3.9.0 and I don't want my bot to read any messages from bots. How do I do that?

I tried to see other questions on Stack Overflow but they were all at least 5 years ago.

I already have it so that it doesn't read messages sent from itself. By the way, my command prefix is '

Here is my code:

import os
import discord

# * Clear the screen
def clear():
    if os.name == 'nt':
        os.system('cls')
    else:
        os.system('clear')
# * Code
clear()

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("'hello"):
        await message.channel.send("Hello!")

    if message.content.startswith("'Hello"):
        await message.channel.send("Hello!")

    if message.content.startswith("'HELLO"):
        await message.channel.send("Hello!")

    if message.content.startswith("'Hi"):
        await message.channel.send("Hello!")

    if message.content.startswith("'hi"):
        await message.channel.send("Hello!")

    if message.content.startswith("'HI"):
        await message.channel.send("Hello!")

    if message.content.startswith("'hey"):
        await message.channel.send("Hello!")

    if message.content.startswith("'Hey"):
        await message.channel.send("Hello!")

    if message.content.startswith("'Greetings"):
        await message.channel.send("Hello!")

    if message.content.startswith("'greetings"):
        await message.channel.send("Hello!")
    
    if message.content.startswith("'howdy"):
        await message.channel.send("We're not cowboys!")

    if message.content.startswith("'Howdy"):
        await message.channel.send("We're not cowboys!")

    if message.content.startswith("'Bye"):
        await message.channel.send("Bye!")

    if message.content.startswith("'bye"):
        await message.channel.send("Bye!")

    if message.content.startswith("'BYE"):
        await message.channel.send("Bye!")

# * Runs the code
client.run("my_token")

Upvotes: 0

Views: 3172

Answers (1)

Nurqm
Nurqm

Reputation: 4743

You can simply use discord.Member.bot. It returns True or False depends on whether the user is a bot or not. Also, you can use str.lower() instead of checking all uppercase and lowercase letter possibilities.

@client.event
async def on_message(message):
    if message.author.bot:
        return
    if message.content.lower().startswith("'hello"):
        await message.channel.send("Hello!")
    if message.content.lower().startswith("'hi"):
        await message.channel.send("Hello!")
    if message.content.lower().startswith("'hey"):
        await message.channel.send("Hello!")

Upvotes: 2

Related Questions