This is my code for a webhook discord alert bot. I used discord.js and the channel's webhooks. I used readline-sync for the input at the console but when I iterate through the answer at console to determine the embed colour, all signals show yellow from the last iteration for some reason.
const { MessageEmbed, WebhookClient } = require('discord.js');
const readline = require('readline-sync')
const webhookClient = new WebhookClient({ id: '', token: '' });
var signal = readline.question("Signal: ")
if (signal.content === "SELL")
{
const embed = new MessageEmbed()
.setTitle(signal)
.setColor('RED')
.setFooter({
text: "test"
})
webhookClient.send({
content: 'Webhook test',
username: "Logan's Signals",
avatarURL: 'https://i.imgur.com/AfFp7pu.png',
embeds: [embed],
});
}
else if (signal.content === "BUY")
{
const embed = new MessageEmbed()
.setTitle(signal)
.setColor('GREEN')
.setFooter({
text: "test"
})
webhookClient.send({
content: 'Webhook test',
username: "Logan's Signals",
avatarURL: 'https://i.imgur.com/AfFp7pu.png',
embeds: [embed],
});
}
else
{
const embed = new MessageEmbed()
.setTitle(signal)
.setColor('YELLOW')
.setFooter({
text: "test"
})
webhookClient.send({
content: 'Webhook test',
username: "Logan's Signals",
avatarURL: 'https://i.imgur.com/AfFp7pu.png',
embeds: [embed],
});
}
Related
I am back again with a question :). I am building my own ticket function, and I just started but if I create a channel for a ticket, its only saying ticket-(Discord account ID) And thats also the case by the embed. Anyone who can look at it?
const discord = require("discord.js");
const { MessageEmbed, Collection, Permissions} = require('discord.js');
const { execute } = require("./ticket");
module.exports = {
name: 'create',
description: 'create your own ticket.',
execute(message, client, args){
if(message.guild.channels.cache.find(channel => channel.name === "Ticket from <#" + message.author + ">")) {
message.reply(`${message.member.user.toString()} **You have successfully created a ticket, Please click on ${channel} to view your ticket**`).then(m => m.delete({ timeout: 14000 }).catch(e => {}));
if(message.guild.channels.cache.find(channel => channel.name === `ticket-${message.author.id}`)) {
return message.reply('<a:no:784463793366761532> **You already have a ticket, please close your exsisting ticket first before opening a new one**');
}
message.delete();
message.guild.channels.create(`Ticket ${message.author}`, {
permissionOverwrites: [
{
id: message.author.id,
allow: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
},
{
id: message.guild.roles.everyone,
deny: ['VIEW_CHANNEL'],
},
],
type: 'text',
}).then(async channel => {
const embed = new MessageEmbed()
.setTitle("<#" + message.author + "> Ticket")
.setDescription(`**${message.author}, Welcome to your channel! Support will be arriving soon**\n**While you wait please tell us what your problem is**\n**If you want to close the ticket please type .close\`**`)
.setColor("BLUE")
channel.send({ embeds: [embed] })
});
}
}
}
I cleaned up the code a fair bit, less is more. Text channels do not have spaces in them so I replaced them with what Discord uses, hypens. The below code will check if a channel already exists and create one if it doesn't.
const {
MessageEmbed,
} = require('discord.js');
module.exports = {
name: 'create',
description: 'create your own ticket.',
async execute(message, client, args) {
const channelName = `ticket-${message.author.username}`
const existing = message.guild.channels.cache.find(channel => channel.name === channelName.toLowerCase());
if (existing) {
return message.reply({
content: `<a:no:784463793366761532> **You already have a ticket, please close your exsisting ticket first before opening a new one**\n${existing}.`,
}).then((m) => {
setTimeout(() => {
m.delete();
}, 14000);
})
}
message.delete();
message.guild.channels.create(channelName, {
type: 'GUILD_TEXT',
permissionOverwrites: [{
id: message.guild.id,
deny: ['VIEW_CHANNEL'],
}, {
id: message.author.id,
allow: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
}],
}).then(async channel => {
const embed = new MessageEmbed()
.setColor("BLUE")
.setTitle(`${message.author.username} Ticket`)
.setDescription(`**${message.author}, Welcome to your channel! Support will be arriving soon**\n**While you wait please tell us what your problem is**\n**If you want to close the ticket please type .close\`**`)
channel.send({
embeds: [embed]
})
});
}
}
When a person sends my command, a channel is created that only they have access to. Also, when creating a channel, a message is sent with the "accept" button, when another person clicks on the button, his rights in the created channel should be added. I can add rights, but when more than one message with a button arrives in a special channel, the person who clicked the button is added to all created channels
An example of how it works
let myreportChannel = ''
await interaction.guild.channels.create(channelNameMy, {
type: 'text', parent: `${categoryTiket}`, permissionOverwrites: [
{
id: `${permUser}`, // permUser - who sent the command
allow: ['VIEW_CHANNEL', 'SEND_MESSAGES', 'READ_MESSAGE_HISTORY', 'ATTACH_FILES']
},
{
id: `${evryOneRolle}`,
deny: ['VIEW_CHANNEL', 'SEND_MESSAGES', 'READ_MESSAGE_HISTORY']
},
]
})
//Prvivate embed
.then(async reportChannel => {
const exampleEmbed = new MessageEmbed()
.setDescription(`Reported: <#${tagBan.id}>\nReason: ${reason}\ntiket: <#${reportChannel.id}>`)
.setColor("#2F3136")
.setImage(`${settings.reportgif}`)
myreportChannel = reportChannel.id // save new channel id
await interaction.reply({embeds: [exampleEmbed], ephemeral: true})
//Report embed
const reportEmbed = new MessageEmbed()
.setDescription(`Intruder: ${tagBan}\nReason: ${reason}`)
.setColor("#2F3136")
.setImage(`${settings.reportgif}`)
await client.channels.cache.get(`${reportChannel.id}`).send({
embeds: [reportEmbed]
})
})
client.on('interactionCreate', async interaction => {
if (interaction.isButton()) {
if (interaction.customId.includes(`acceptB`)) {
const editEmbRep = new MessageEmbed()
.setDescription(`Author: <#${interaction.user.id}>\nIntruder: <#${tagBan.id}>\nStatus: ${dmStatusAc}\nTiket: <#${myreportChannel}>`)
.setColor("#2F3136")
.setImage(`${settings.reportgif}`)
interaction.message.edit({
content: 'updated text',
embeds: [editEmbRep],
components: []
})
let channelx = interaction.guild.channels.cache.get(myreportChannel) // set channel by id
if (channelx) {
channelx.permissionOverwrites.edit(interaction.user.id, {
VIEW_CHANNEL: true,
SEND_MESSAGES: true,
ATTACH_FILES: true,
READ_MESSAGE_HISTORY: true
}) //edit permision channel. add the permission of the user who clicked on the "accept" button
}
So I adjusted the code above and made some notes along the way, but this should work as expected. I split the command from the button push.
const reportChannel = await interaction.guild.channels.create(channelNameMy, {
type: 'text',
parent: `${categoryTiket}`,
permissionOverwrites: [{
id: `${permUser}`, // permUser - who sent the command
allow: ['VIEW_CHANNEL', 'SEND_MESSAGES', 'READ_MESSAGE_HISTORY', 'ATTACH_FILES']
},
{
id: `${evryOneRolle}`,
deny: ['VIEW_CHANNEL'] //denying view channel will stop all other ones from working too
},
]
})
//Prvivate embed
const exampleEmbed = new MessageEmbed()
.setDescription(`Reported: <#${tagBan.id}>\nReason: ${reason}\nticket: <#${reportChannel.id}>`)
.setColor("#2F3136")
.setImage(`${settings.reportgif}`)
interaction.reply({
embeds: [exampleEmbed],
ephemeral: true
})
//Report embed
const reportEmbed = new MessageEmbed()
.setDescription(`Intruder: ${tagBan}\nReason: ${reason}\nticket:<#${reportChannel.id}>`)
.setColor("#2F3136")
.setImage(`${settings.reportgif}`)
.setFooter({
text: `${reportChannel.id}` // I added the channel ID here again (critical part of the code to not change
})
// adds the new channel id to the footer to be used later when someone clicks the accept button
const acceptButton = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId(`acceptB`)
.setLabel('Accept')
.setStyle('SUCCESS')
.setEmoji('✅')
)
client.channels.cache.get(reportChannel.id).send({
embeds: [reportEmbed],
components: [acceptButton]
})
client.on('interactionCreate', async interaction => {
if (interaction.isButton()) {
if (interaction.customId.includes(`acceptB`)) {
// when someone clicks the accept button it grabs the embed
const oldEmbed = interaction.message.embeds[0]
// adds a line to that embed
const editEmbRep = new MessageEmbed()
.addField('Status:', `${dmStatusAc}`)
// updates the embed and removes the button
interaction.message.edit({
embeds: [editEmbRep],
components: []
})
// finds the channel using the channel id placed in the footer earlier
const channelx = interaction.guild.channels.cache.get(oldEmbed.footer.text)
channelx.permissionOverwrites.edit(interaction.user.id, {
VIEW_CHANNEL: true,
SEND_MESSAGES: true,
ATTACH_FILES: true,
READ_MESSAGE_HISTORY: true
}) // adds them to the channel
}
}
})
I am making a tickets bot.
When I try click of any of the embeds, it will run the code and create a new channel, then continue to ping me in it like I wanted, but then shows this error.
DiscordAPIError: Invalid Form Body
components[0].components[1].emoji.name: Invalid emoji
at RequestHandler.execute (C:\Users\wrigh\Documents\Discord Bots\Practice Bot - Copy\node_modules\discord.js\src\rest\RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (C:\Users\wrigh\Documents\Discord Bots\Practice Bot - Copy\node_modules\discord.js\src\rest\RequestHandler.js:51:14)
at async TextChannel.send (C:\Users\wrigh\Documents\Discord Bots\Practice Bot - Copy\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:175:15)
The full error is here (sorry for link wouldn't let me post full error) :
https://sourceb.in/dOCoUtAQVx
The code is here:
const { ButtonInteraction, MessageEmbed, MessageActionRow, MessageButton } = require("discord.js");
const DB = require("../../Structures/Handlers/Schemas/Ticket");
const { PARENTID, EVERYONEID } = require("../../Structures/config.json");
const Ticket = require("../../Structures/Handlers/Schemas/Ticket");
module.exports = {
name: "interactionCreate",
/**
*
* #param {ButtonInteraction} interaction
*/
async execute(interaction) {
if(!interaction.isButton()) return;
const { guild, member, customId } = interaction;
if (!["player", "bug", "other"].includes(customId)) return;
const ID = Math.floor(Math.random() * 90000) + 10000;
await guild.channels
.create(`${customId + "-" + ID}`, {
type: "GUILD_TEXT",
parent: PARENTID,
permissionOverwrites: [
{
id: member.id,
allow: ["SEND_MESSAGES", "VIEW_CHANNEL", "READ_MESSAGE_HISTORY"],
},
{
id: EVERYONEID,
deny: ["SEND_MESSAGES", "VIEW_CHANNEL", "READ_MESSAGE_HISTORY"],
},
],
})
.then(async (channel) => {
await DB.create({
GuildID: guild.id,
MemberID: member.id,
TicketID: ID,
ChannelID: channel.id,
Closed: false,
Locked: false,
type: customId,
});
const Embed = new MessageEmbed()
.setAuthor(
`${guild.name} | Ticket: ${ID}`,
guild.iconURL({ dynamic: true })
)
.setDescription(
"Please wait patiently for a response from the Staff team, in the mean while, describe your issue in as much detail."
)
.setFooter("The buttons below are staff only buttons.");
const Buttons = new MessageActionRow();
Buttons.addComponents(
new MessageButton()
.setCustomId("close")
.setLabel("Save and close")
.setStyle("PRIMARY")
.setEmoji("📂"),
new MessageButton()
.setCustomId("lock")
.setLabel("lock")
.setStyle("SECONDARY")
.setEmoji("'🔒"),
new MessageButton()
.setCustomId("unlock")
.setLabel("unlock")
.setStyle("SUCCESS")
.setEmoji("❤"),
);
channel.send({
embeds: [Embed],
components: [Buttons],
});
await channel
.send({ content: `${member} here is your ticket` })
.then((m) => {
setTimeout(() => {});
}, 1 * 5000);
})
interaction.reply({
content: `${member} your ticket has been created: ${channel}`,
});
},
};
```js
I'm still learning JavaScript so please bear with me if I don't get it straight away, I will try my best.
You have an extra character in your lock button. It should be .setEmoji("🔒"), not .setEmoji("'🔒"). That's what the error is telling you: "Invalid Emoji" (because '{lock} isn't an emoji)
Code:
const role = interaction.options.getRole('role');
const description = interaction.options.getString('description');
const emoji = interaction.options.getString('emoji');
const parsedEmoji = Util.parseEmoji(emoji);
if (role.position >= interaction.guild.me.roles.highest.position) {
const embed = new MessageEmbed()
.setColor('RED')
.setTitle('Error:')
.setDescription(`I can not add roles that are higher than mine`)
.setTimestamp()
.setFooter({ text: `Phantom Bot v${config.version}` });
return interaction.reply({ embeds: [embed], ephemeral: true });
}
ReactionRole.findOne({ guild_id: interaction.guild.id }, (err, settings) => {
if (err) {
const embed = new MessageEmbed()
.setColor('RED')
.setTitle('Error:')
.setDescription(`There was an error while adding the reaction role`)
.setTimestamp()
.setFooter({ text: `Phantom Bot v${config.version}` });
return interaction.reply({ embeds: [embed], ephemeral: true });
}
if (!settings) {
new ReactionRole({
guild_id: interaction.guild.id,
message: 0,
roles: {
[parsedEmoji.name]: [
role.id,
{
description: description,
id: parsedEmoji.id,
raw: emoji
}
]
}
}).save();
} else {
settings.roles[parsedEmoji.name] = [
role.id,
{
description: description,
id: parsedEmoji.id,
raw: emoji
}
]
ReactionRole.findOneAndUpdate({ guild_id: interaction.guild.id }, settings);
}
const embed = new MessageEmbed()
.setColor('PURPLE')
.setTitle('Reaction Added:')
.setDescription(`Role ${role}\nEmoji: ${emoji}`)
.setTimestamp()
.setFooter({ text: `Phantom Bot v${config.version}` });
interaction.reply({ embeds: [embed] });
});
Issue:
For some reason if the settings do exist in the else statement, it doesn't actually update it in the Mongoose database. It actually doesn't touch it at all. I've tried awaiting the ReactionRole.findOneAndUpdate but I got an error saying I couldn't await it.
How can I fix this?
Any help would be appreciated!
Fixed buy making the function an async, then it would allow await.
I want to add info to database and I'm getting the "This interaction failed" error in discord
Using better-sqlite3, discord.js v13
For the code, I've used bits and pieces of tutorials and guides from around the internet and I think some of that may have interfered with what's already been written
const { MessageActionRow, MessageButton, MessageEmbed } = require('discord.js');
const db = require("better-sqlite3")("../../main.db")
module.exports = {
name: 'test',
description: "test buy",
options: [
{
name: 'buy',
description: 'ซื้อสคริป',
type: "SUB_COMMAND",
options: [
{
name: "link",
description: "ลิ้งซองเงิน 99 บาท",
type: "STRING",
required: true,
}
]
},
],
run: async(client, interaction, args) => {
if (interaction.options.getSubcommand() === 'buy') {
const button = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId('confirm')
.setLabel('c')
.setStyle('SUCCESS'),
new MessageButton()
.setCustomId('cancel')
.setLabel('b')
.setStyle('DANGER'),
new MessageButton()
.setURL('https://www.youtube.com/')
.setLabel('a')
.setStyle('LINK'),
);
const embed = new MessageEmbed()
.setColor('#FF0000')
.setTitle('ShuShi')
.setDescription('info')
await interaction.reply({ephemeral: true, embeds: [embed], components: [button] });
const filter = i => i.user.id === interaction.member.id;
const collector = interaction.channel.createMessageComponentCollector({
filter,
time: 600000,
max: 1
});
collector.on('collect', async i => {
collector.stop();
if (i.customId === 'confirm') {
db.prepare(`INSERT INTO discorddata VALUES(:id,:own)`).run({
id: interaction.user.id,
own: 'true'
})
}
})
}
}}