Tech With Tim Logo
Go back

Changing Nicknames & Embedding Messages

This tutorial will cover the following:

  • How to change a members nickname is discord.py rewrite
  • How to Embed messages
  • How to delete messages using purge

How to Change A Members Nickname

It may be the case that we want to change certain members nicknames. Maybe we want to disallow them to use certain names or we just want to do it for fun.

The first thing we need to make sure of when attempting to change members nicknames is our bots permissions. If you did not setup the bot with appropriate privileges you will need to add the ability for it to manage members. To do this we can create a new role for the bot and give it that permission. Also note that the bot will not be able to change members nicknames that have a higher permission than it.

To add the permission to the bot create a new role names BOT. kuva_2023-04-23_190227082.png Next assign that role to your bot. kuva_2023-04-23_190242433.png

Now that our bot has sufficient permissions we can change members usernames.

I would like to disallow members from changing their username to anything that contains "tim" (as there can only be one!). So if a member updates their username our bot will attempt to change it back to what it was before or give them another nickname. To do this we add the following event.

@client.event # This event runs whenever a user updates: status, game playing, avatar, nickname or role
async def on_member_update(before, after): 
    n = after.nick 
    if n: # Check if they updated their username
        if n.lower().count("tim") > 0: # If username contains tim
            last = before.nick
            if last: # If they had a usernae before change it back to that
                await after.edit(nick=last)
            else: # Otherwise set it to "NO STOP THAT"
                await after.edit(nick="NO STOP THAT")

Deleting "Bad" Messages

It is likely that there are certain words we may not want to appear in our server. We can give our bot a list of these words and have it automatically delete any messages that contain them. In the on_message() function we will add the following.

@client.event
async def on_message(message):
    ...
    bad_words = ["bad", "stop", "45"]

    for word in bad_words:
        if message.content.count(word) > 0:
            print("A bad word was said")
            await message.channel.purge(limit=1)
    ...

Now if the user types any of the words in the bad_words list their message will be deleted.

Embedding Messages

To make our messages look nicer we can embed them. An embedded message looks something like the following. kuva_2023-04-23_190358929.png

I am going to have a nice embedded message appear whenever the user types !help. To do this I will add the following line to the on_message() event.

@client.event
async def on_message(message):
    ...
    if message.content == "!help":
        embed = discord.Embed(title="Help on BOT", description="Some useful commands")
        embed.add_field(name="!hello", value="Greets the user")
        embed.add_field(name="!users", value="Prints number of users")
        await message.channel.send(content=None, embed=embed)
    ...

Full Code

import discord
import time
import asyncio


messages = joined = 0

def read_token():
    with open("token.txt", "r") as f:
        lines = f.readlines()
        return lines[0].strip()

token = read_token()

client = discord.Client()


async def update_stats():
    await client.wait_until_ready()
    global messages, joined

    while not client.is_closed():
        try:
            with open("stats.txt", "a") as f:
                f.write(f"Time: {int(time.time())}, Messages: {messages}, Members Joined: {joined}\n")

            messages = 0
            joined = 0

            await asyncio.sleep(5)
        except Exception as e:
            print(e)
            await asyncio.sleep(5)


@client.event
async def on_member_update(before, after):
    n = after.nick
    if n:
        if n.lower().count("tim") > 0:
            last = before.nick
            if last:
                await after.edit(nick=last)
            else:
                await after.edit(nick="NO STOP THAT")


@client.event
async def on_member_join(member):
    global joined
    joined += 1
    for channel in member.server.channels:
        if str(channel) == "general":
            await channel.send(f"""Welcome to the server {member.mention}""")


@client.event
async def on_message(message):
    global messages
    messages += 1

    id = client.get_guild(ID HERE)
    channels = ["commands"]
    valid_users = ["Tim#9298"]
    bad_words = ["bad", "stop", "45"]

    for word in bad_words:
        if message.content.count(word) > 0:
            print("A bad word was said")
            await message.channel.purge(limit=1)

    if message.content == "!help":
        embed = discord.Embed(title="Help on BOT", description="Some useful commands")
        embed.add_field(name="!hello", value="Greets the user")
        embed.add_field(name="!users", value="Prints number of users")
        await message.channel.send(content=None, embed=embed)

    if str(message.channel) in channels and str(message.author) in valid_users:
        if message.content.find("!hello") != -1:
            await message.channel.send("Hi") 
        elif message.content == "!users":
            await message.channel.send(f"""# of Members: {id.member_count}""")


client.loop.create_task(update_stats())
client.run(token)
Design & Development by Ibezio Logo