Search code examples
discorddiscord.js

How do you delete certain messages from a specific username not ID


twitchClient.on('timeout', async (channel, username, user, reason, duration) => {

    discordClient.on('message', async (message, messages) => {
        async function deleteMessage() {
            await discordClient.channels.cache.get("901568598538063932")
            .messages.fetch({limit: null})
            .then(message.delete(messages.first(user["display-name"]).author.name))
        }
        await deleteMessage()
    })
        
    async function sendMessage() {
        const request = new XMLHttpRequest();
        request.open("POST", "API url");
        
        request.setRequestHeader('Content-type', 'application/json');

        const users = { 
        username: "User Timed Out",
        avatar_url: 'https://i.imgur.com/GUrbNsB.jpg',
        content: `**${username} has been timed out for ${duration} seconds.**`
        }
        request.send(JSON.stringify(users));
    }

    await sendMessage()
});

I have this code for twitch chat to sync in discord and I want to do on event timeout on twitch I want it to delete the messages of a certain name on the channel is it possible without ID I am lost on how to do it like I can delete the last message but not from a specific user and I only have one webhook so the id of all usernames will be the same

TypeError: Cannot read properties of undefined (reading 'first')


Solution

  • Note: This code is for Discord.js v13.3.0


    As stated by the error, you're trying to access an undefined variable called messages. This is because you did not define it in the then() arguments, you instantly went to a callback.

    then() is a function that allows for you to provide parameters to add. You can simply put the collection of messages as one variable called messages and pass it to the callback accordingly.

    // DON'T do this
    messages.fetch({limit: null})
                .then(message.delete(messages.first(user["display-name"]).author.name))
    
    // DO this
    messages.fetch({limit: null})
                .then((messages) => message.delete(messages.first(user["display-name"]).author.name))