i'm new in StackOverflow.
I need counting command for my discord bot (discord.js)...
I need that when the user starts counting for example 1, then the bot will delete his message and change the webhook to his name and avatar and send his message and the variable will increase by 1...
This is what I got, but there is an error :(
client.on('message', ({message, channel, content, member}) => {
if (channel.id === 'channel_id') {
let webhookClient = new Discord.WebhookClient('webhook_id', 'webhook_token');
let count = 0;
if (member.user.bot) return
if (Number(content) === count + 1) {
webhookClient.send(count, {
username: content.author.username,
avatarURL: content.author.displayAvatarURL()
});
count++
}
}
})
Error: TypeError: Cannot read property 'username' of undefined
And I would also like the bot to delete all messages that are not associated with the counter, such as words or emoji ... ("hello", "😀")
In order to get the author's username and avatarURL you need to:
username: message.author.username
avatarURL: message.author.displayAvatarURL()
Something like this should work:
client.on('message', async message =>{
if (message.channel.id === 'channel_id') {
let webhookClient = new Discord.WebhookClient('webhook_id', 'webhook_token');
let count = 0;
if (message.author.bot) return;
if (Number(message.content) === count + 1) {
webhookClient.send(count, {
username: message.author.username,
avatarURL: message.author.displayAvatarURL()
});
count++
}
}
});
Related
client.on('messageCreate', message => {
if(message.author.bot) return;
if(message.channel.id == "1012047542462185572"){
var messageContent = message.content;
client.channels.cache.get('1012048291111903292').send(messageContent)
}
});
This code can only send a message from a channel to another though a bot but it's only the bot speaking, I want to add which user is speaking. How can i implement this?
Use this
client.on('messageCreate', async (message) => {
if(message.author.bot) return;
if(message.channel.id == "1012047542462185572") {
const { content, member, author } = message
const channel = await client.channels.fetch('1012048291111903292')
// for nickname:
const str = `**${member.displayName}:**\n${content}`
// for username and tag
const str = `**${author.tag}:**\n${content}`
// you may only use one of these. when you
// adapt it to your own code, remove one of
// these "str", keep the one you want
channel.send({ content: str })
}
})
I am currently working on a command right now that I would like the server owner to use. When done it sends the embed and will wait for the server owner to paste we will say the channel id. I want to label this to call in another command but at the moment it sends the embed but when I send a channel ID nothing happens. No message is sent but it also does not break the bot. I am still able to send the command again and again.
Please do not mind the slop, I am new to all this and trying to learn as I go any tips would be appreciated!
EDIT: I am using version 12 (12.5.3)
const { prefix } = require('../config.json');
const Discord = require('discord.js');
const client = new Discord.Client();
module.exports = {
name: 'setchannel',
description: 'command to assign bot to channel',
execute(message, args) {
if(message.channel.type == "dm") {
const keepinservercommandembed = new Discord.MessageEmbed()
.setColor('#FF0000')
.setTitle('**Im Sorry!**')
.addFields(
{ name: `**Can` + `'t accept: ${prefix}setchannel**`, value: 'Please keep this command to the server!' },
)
message.channel.send(keepinservercommandembed);
}
else {
const messagesender = message.member.id;
const serverowner = message.guild.owner.id;
const setchannelembed = new Discord.MessageEmbed()
.setColor('#FF0000')
.addFields(
{ name: `**Let's get searching!**`, value: `Hello ${message.guild.owner}, what channel would you like me to post group finding results?` },
)
const notownerembed = new Discord.MessageEmbed()
.setColor('#FF0000')
.addFields(
{ name: `**Whoops!**`, value: `Sorry only ${message.guild.owner} can use this command.` },
)
if(messagesender == serverowner) {
message.delete ();
const filter = m => m.content.message;
const collector = message.channel.createMessageCollector(filter, { time: 15000 });
message.channel.send(setchannelembed).then(() => {
collector.on('collect', m => {
message.channel.send(`${m.content}`)
});
});
}
else {
message.delete ();
message.channel.send(notownerembed);
}
}
}
}
After comparing your code to my similiar discord.js v13 code and checking out the v12 docs, I think I found the problem.
I don't think m.content.message is a function. If your aim is for someone to paste the channel ID, the filter code would be:
const filter = m => m.author.id === message.guild.owner.id;
To filter out other people who may be entering an ID (assuming the input is valid).
Use the filter as follows:
message.channel.createMessageCollector({filter: filter, time: 15000 });
To filter out invalid inputs:
collector.on('collect', m => {
if (isNaN(m)) return; //all channel id's in discord are integers (numbers)
else message.channel.send(`${m.content}`);
});
Just had a simple question, I have some moderation slash commands on discord bot running on Discord.js V13, and I need to get the user ID of the person who runs the slash command. So I can then check for the permissions of the user on the guild to make sure he has the Ban_Members permission per example. And also how do I get the guild ID of where the slash command was executed
Thanks! If I wasn't clear feel free to ask me to clarify something
The code I tried
client.ws.on("INTERACTION_CREATE", async (interaction) => {
if (interaction.data.component_type) return;
const command = interaction.data.name.toLowerCase();
const args = interaction.data.options;
if (command == "mute") {
const guildId = interaction.guildId;
console.log(guildId);
// client.api.interactions(interaction.id, interaction.token).callback.post({
// data: {
// type: 4,
// data: {
// embeds: [muteembed],
// ephemeral: "false",
// },
// },
// });
}
});
And I just receive undefined in the console log
Something else I tried
client.on("interactionCreate", async (interaction) => {
if (interaction.data.component_type) return;
const command = interaction.data.name.toLowerCase();
const args = interaction.data.options;
if (command == "mute") {
const guildId = interaction.guildId;
console.log(guildId);
// client.api.interactions(interaction.id, interaction.token).callback.post({
// data: {
// type: 4,
// data: {
// embeds: [muteembed],
// ephemeral: "false",
// },
// },
// });
}
});
And I get this error:
if (interaction.data.component_type) return;
^
TypeError: Cannot read properties of undefined (reading 'component_type')
its usually
interaction.user.id
interaction.member.id
The two things you need is a user and a guild. Make sure you check there is a guild, otherwise things will go wrong.
if(!interaction.guild) return; // Returns as there is no guild
var guild = interaction.guild.id;
var userID = interaction.user.id;
I am building a profile slash command for discord.js 13. The command checks users roles and displays specific information about them. We are hoping to add the persons introduction from an introduction channel. Is there anyway to pull the last message sent from a user from a specific channel?
Current Code
try{
await guild.members.fetch();
const member = guild.members.cache.get(UserOption.id);
const roles = member.roles;
const userFlags = UserOption.flags.toArray();
const activity = UserOption.presence?.activities[0];
//create the EMBED
const embeduserinfo = new MessageEmbed()
embeduserinfo.setThumbnail(member.user.displayAvatarURL({ dynamic: true, size: 512 }))
embeduserinfo.setAuthor("Information about " + member.user.username + "#" + member.user.discriminator, member.user.displayAvatarURL({ dynamic: true }), "https://discord.gg/FQGXbypRf8")
embeduserinfo.addField('**❱ Username**',`<#${member.user.id}>\n\`${member.user.tag}\``,true)
embeduserinfo.addField('**❱ Avatar**',`[\`Link to avatar\`](${member.user.displayAvatarURL({ format: "png" })})`,true)
embeduserinfo.addField('**❱ Joined Discord**', "\`"+moment(member.user.createdTimestamp).format("DD/MM/YYYY") + "\`\n" + "`"+ moment(member.user.createdTimestamp).format("hh:mm:ss") + "\`",true)
embeduserinfo.addField('**❱ Joined MetroVan**', "\`"+moment(member.joinedTimestamp).format("DD/MM/YYYY") + "\`\n" + "`"+ moment(member.joinedTimestamp).format("hh:mm:ss")+ "\`",true)
//DIRECT MESSAGE DISPLAY CODE
if (roles.cache.find(r => r.id === "893305823315492914")) //dms are open
{
embeduserinfo.addField("**❱ DM STATUS**\n`🔔 OPEN` ", "** **", true)
}
If you just need the last message in the channel, use the below code. Possible duplicate of Get last message sent to channel
let channel = bot.channels.get('id-of-the-channel');
channel.messages.fetch({ limit: 1 }).then(messages => {
let lastMessage = messages.first();
if (!lastMessage.author.bot) {
// Do something with it
}
})
.catch(console.error);
If you want the last message sent in a channel by a specific user, filter it with the id property as below-
let channel = bot.channels.get('id-of-the-channel');
channel.messages.fetch().then(messages => {
let lastMessage = messages.filter(m => m.author.id === 'id-of-user').last;
//Do something with it
})
.catch(console.error);
async function searchForLastMessageFromUser(channel, userId) {
let messages = await channel.messages.fetch({before: null}, {cache: true});
while (messages.size > 0) {
let result = messages.find(message => {
return message.author.id === userId;
});
if (result !== null) return result;
messages = await channel.messages.fetch({limit: 50, before: messages[messages.length - 1]}, {cache: true});
}
return null;
}
embeduserinfo.setDescription("**❱ INTRODUCTION**\n" + introMessageText, "** Add your intro at <#885123781130067988>**");
Hi I'm trying to make my Bot change its status from a message, and also set it with quick.db so if it restarts it changes back to the sotd. For example the message would be something like : Song of the day: "Wild Reputation" from the Album(s) PWR UP and I only want the song name as the status.
client.on('message', message => {
if (message.channel.id === '792250171320434688') {
if (message.author.id === '403657714812715008') {
const ms = message.content
db.set('sotd_', ms)
let so = db.get('sotd_')
client.user.setActivity(so, { type: "PLAYING"})
}
}
});
I guess the problem is somewhere with quick.db because as far as I can tell the discord.js part is correct. My suggestion is to try the following:
client.on('message', message => {
if (message.channel.id === '792250171320434688' && message.author.id === '403657714812715008') {
const ms = message.content
client.user.setActivity(ms, { type: "PLAYING"})
db.set('sotd_', ms)
}
});
This way you eliminate possible errors when trying to get the data from the database. And then if you want to get the last status from quick.db do something like
client.on('ready', () => {
const lastStatus = db.get('sotd_');
client.user.setActivity(lastStatus, { type: "PLAYING"});
});