简体   繁体   中英

How do i send a message in a specific channel in discord using discord.js

I've tried to use

<client>.channels.cache.get('1234567890').send('Hello world.');

and

<guild>.channels.cache.find(ch => ch.name === 'general').send('Hello world.');

but neither has worked. This is the code that I have:

module.exports = {
    commands: 'strike',
    minArgs: 2,
    expectedArgs: "<Target user's @> <Role>",
    permissions: 'MANAGE_ROLES',
    callback: (message, args, client) => {
        const targetUser = message.mentions.users.first()
        if (!targetUser) {
            message.reply('Please specify someone to strike.')
            return
        }

        args.shift()

        const roleName = args.join(' ')
        const { guild } = message

        const role = guild.roles.cache.find((role) => {
            return role.name === roleName
        })
        if (!role) {
            message.reply(`There is no role with the name "${roleName}"`)
            return
        }

        const member = guild.members.cache.get(targetUser.id)
        member.roles.add(role)

        client.channels.cache.get('870165929282138153').send(`<@${member.user.id}> has been striked.`)
    },
}

Any ideas on how I can do this?

To send a message to a specific channel using its id, you can use :

message.guild.channels.cache.get(ID).send(MESSAGE);

The channels collection come from the guild object, and .cache.get() returns a channel object.

You can learn more about it here : https://discord.js.org/#/docs/main/stable/class/Guild?scrollTo=channels

Finding channel by the name:

const channel = client.channels.cache.get(channel => channel.name === "channelName")
channel.send(message)

Finding channel by the Id:

const channel = client.channels.cache.get(channel => channel.id === "ID")
channel.send(message)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM