user17723683
user17723683

Reputation:

Discord.py - Handling user to mentioning other users

My Goals

When the user tried to use the command but mentioning a other members, it will sends an errors to the users.

MY Current Codes

@bot.command()
async def tell(ctx, *, text):
    if text in ctx.guild.members:
       await ctx.send("Mentioning other's members not allowed")
       return

Upvotes: 1

Views: 476

Answers (1)

Bagle
Bagle

Reputation: 2346

There are a number of ways to tackle this, and here I will show you two possible methods that may interest you. The first method is, as Anu said, to use Regex. You can check if anything starts with <@ and ends with >, as this is how most user and role mentions are laid out, and this is how the bot sees mentions. The second method is not as good as using regex, where you check if the ctx.message has any mentions in it via message.mentions. Do view both of these methods and some further explanation below.

# Method 1: Recommended and Regex
# Checks if 'tell' has mentions via regex
# I will link other questions on regex below to help you
import re # Don't forget to import this!

@bot.command()
async def tell(ctx, *, tell):
    x = re.search('<@(.*)>', tell)
    # User mentions are usually in the form of
    # <@USERID> or <@!USERID>
    if not x:
        await ctx.send(tell)
        return
    await ctx.send("Don't mention other users")


# Method 2: Not recommended but working
# Check if the original command message has mentions in it via message.mentions
# Will backfire if the user uses a mention prefix (@Bot tell)
@bot.command()
async def tell(ctx, *, text):
    if ctx.message.mentions:
        await ctx.send("Mentioning other's members not allowed")
        return
    await ctx.send(text)

[Image for Method 1]

Working Method 1

[Image for Method 2]

Working Method 2

[Image for how Bots see mentions (id blocked for privacy reasons)]

How bots see mentions

Other links:

Upvotes: 2

Related Questions