Reputation: 113
I am trying to get my discord bot to be able to imitate people, like Dad Bot does, but with custom text. My current code is:
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,
})
}
)
}
I know my way of replacing data is weird, but it works, it sends a message from the webhook with the profile and name of the mentioned user, but it only does that in one channel, set in the server webhook settings. Is there a way I can edit the webhook channel to the one that the command was executed in?
Here is an image of it: https://i.sstatic.net/pjJrD.png
Upvotes: 0
Views: 1533
Reputation: 2785
Use discord.js's WebhookClient
( implements Webhook
) Class like this:
const { Webhook } = require('discord.js');
const webhook = new Webhook('xxxxxxxxxxxxxxxxxxxxxx', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
You can then use WebHook#send
with WebhookMessageOptions
:
webhook.send(sudoreplace2, {avatarURL: webhookpfp2, username: sudoname});
Before you do that, you can change the channel with WebHook#edit
:
webhook.edit({channel: message.channel});
Final summary:
const { Webhook } = require('discord.js');
const webhook = new Webhook('xxxxxxxxxxxxxxxxxxxxxx', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
webhook.edit({channel: message.channel});
webhook.send(sudoreplace2, {avatarURL: webhookpfp2, username: sudoname});
Problems I faced with this: I ( Guild Owner ) created the Webhook, when the Bot tried to edit it, Discord API returned DiscordAPIError: 401: Unauthorized
, I fixed this by using message.channel.createWebhook('PlaceHolder');
Upvotes: 1