首页 > 解决方案 > 如何更改 webhook 通道?

问题描述

我试图让我的不和谐机器人能够模仿人,就像爸爸机器人一样,但使用自定义文本。我目前的代码是:

 else if (command === 'sudo') {
    const sudoname = message.mentions.users.first().username
    if (sudoname === null) {
        return message.channel.send ('you need to mention someone.')
    }
    //remove the command
    const sudoreplace = message.content.replace('/sudo ', "")
    //remove the mention, we are left with the message
    const sudoreplace2 = sudoreplace.replace(args[0], "")
    const webhookpfp = message.mentions.users.first()
    //get mentioned user's avatar
    const webhookpfp2 = webhookpfp.avatarURL()
    const sudochannel = message.channel.id
    
    fetch(
        'https://discord.com/api/webhooks/xxxxxxxxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
        {
          method: 'post',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            username: sudoname,
            avatar_url:
              webhookpfp2,
            content:
              sudoreplace2,
          })
        }
    )
}

我知道我替换数据的方式很奇怪,但它有效,它从 webhook 发送一条消息,其中包含提到的用户的配置文件和名称,但它只在一个通道中执行此操作,在服务器 webhook 设置中设置。有没有办法可以将 webhook 通道编辑为执行命令的通道?

这是它的图像:https ://i.stack.imgur.com/pjJrD.png

标签: javascriptdiscorddiscord.js

解决方案


像这样使用 discord.js 的WebhookClient( implements Webhook) 类:

const { Webhook } = require('discord.js');
const webhook = new Webhook('xxxxxxxxxxxxxxxxxxxxxx', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');

然后您可以使用WebHook#sendwith WebhookMessageOptions

webhook.send(sudoreplace2, {avatarURL: webhookpfp2, username: sudoname});

在此之前,您可以使用以下命令更改频道WebHook#edit

webhook.edit({channel: message.channel});

最后总结:

const { Webhook } = require('discord.js');
const webhook = new Webhook('xxxxxxxxxxxxxxxxxxxxxx', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
webhook.edit({channel: message.channel});
webhook.send(sudoreplace2, {avatarURL: webhookpfp2, username: sudoname});

我遇到的问题:我(公会所有者)创建了 Webhook,当 Bot 尝试编辑它时,Discord API 返回DiscordAPIError: 401: Unauthorized,我通过使用解决了这个问题message.channel.createWebhook('PlaceHolder');


推荐阅读