Tahmid Chowdhury
Tahmid Chowdhury

Reputation: 23

How would I write a bot which sends it's owner a direct message whenever a target user changes their custom status?

Here's what I have so far:

import discord

client = discord.Client(intents=discord.Intents.default())
token = 'PRETEND MY BOT TOKEN IS HERE'


@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord!')


@client.event
async def on_user_update(before, after):
    if after.id == PRETEND THE TARGET USERS ID IS HERE:
        if before.status != after.status:
            owner = client.get_user(PRETEND THE BOT OWNERS ID IS HERE)
            await owner.send(f'{after.name} has changed their status from {before.status} to {after.status}')


client.run(token)

It just doesn't seem to be working.

Here's what I've tried so far:

Based on the on_ready() function, the bot seems to be up and running. I suppose I just can't get it to detect the change in custom status. Also, I'm not sure if I'm taking the right approach when it comes to sending a direct message.

Upvotes: 2

Views: 79

Answers (1)

NpTerra
NpTerra

Reputation: 36

I believe this should work:

import discord as dc


class MyClient(dc.Client):
    ownerid = <your id here>
    targetid = <target id here>

    async def on_ready(self):
        print(f'Logged on as {self.user}!')

    async def on_presence_update(self, before: dc.Member, after: dc.Member):

        if before.id != self.targetid:
            return

        owner = await self.fetch_user(self.ownerid)

        msg = ""

        # If a user changed their name or discriminator
        if before.name != after.name or before.discriminator != after.discriminator:
            msg += f"{before.name}#{before.discriminator} has changed their name to {after.name}#{after.discriminator}\n"

        # If a user changed their status (Online, Idle, Do not disturb, Invisible)
        if before.status != after.status:
            msg += f"{after.name}#{after.discriminator} has changed their status to {after.status}\n"

        # If a user changed their activity (The emoji with some text)
        if before.activity != after.activity:
            msg += f"{after.name}#{after.discriminator} has changed their activity to:\n{after.activity}"

        if msg != "":
            await owner.send(msg)


intents = dc.Intents.default()
intents.members = True
intents.presences = True
client = MyClient(intents=intents)
client.run('<your token here>')

You just need to use the on_presence_update event and its required intents (members and presences).

Upvotes: 2

Related Questions