msg.author.dmChannel does not exist - node.js

so i need to get msg.author.dmChannel
it doesnt work
the msg.author object is the following:
User {
id: '0000000000000000',
bot: false,
system: false,
flags: UserFlags { bitfield: 0 },
username: 'username' ,
discriminator: '0000',
avatar: '8eb21315f800000000000000000000008a78ab77e',
banner: undefined,
accentColor: undefined
}
so there really is no dmChannel? how do i make one? msg.author.createDM() doesnt work
EDIT:
msg.author.send('What is the password?' + '\n If this is not you or you did not use the confim-subscription command please disregard this message. You have 1 minute'); has already been used
msg.author.send('What is the password?' + '\n If this is not you or you did not use the `confim-subscription` command please disregard this message. You have 1 minute');
console.log(msg.author);
let channel = msg.author.dmChannel;
console.log(channel);
channel.awaitMessages(m => m.author.id == msg.author.id, {
max: 1,
time: 60000,
errors: ['time']
})
.then(dm => {
dm = dm.first()
if (dm.content == password || dm.content.toUpperCase() == 'Y') {
dm.channel.send(`Your respone has been processed :thumbsup:`);
var role = message.guild.roles.find(role => role.name === "Member");
msg.guild.members.cache.get(msg.author.id).roles.add(role)
} else {
dm.channel.send(`Terminated: Invalid Response`)
}
})

In v13, DMs need their own intent (DIRECT_MESSAGES). Also, User.dmChannel can be null. To force a DM, you can use User.createDM which returns the channel. Here is what could be the final code:
let channel = await msg.author.createDM();
channel.send('What is the password?' + '\n If this is not you or you did not use the `confim-subscription` command please disregard this message. You have 1 minute');
channel.awaitMessages(m => m.author.id == msg.author.id, {
max: 1,
time: 60000,
errors: ['time']
})
.then(dm => {
dm = dm.first()
if (dm.content == password || dm.content.toUpperCase() == 'Y') {
dm.channel.send(`Your respone has been processed :thumbsup:`);
var role = message.guild.roles.find(role => role.name === "Member");
msg.guild.members.cache.get(msg.author.id).roles.add(role)
} else {
dm.channel.send(`Terminated: Invalid Response`)
}
})
Note your client does need the DM intents. You can provide it like this:
const client = new Client({
intents: [
Intents.FLAGS.DIRECT_MESSAGES //you can add other intents as needed
]
})

Related

DiscordJS 13 user embed display last message sent in specific channel

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>**");

discord.js Counting command with webhooks

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++
}
}
});

Node JS: Twich Bot messages are only displayed if on the own channel

I'm trying to make a bot that reacts to The User Messages. My Problem is, that the Messages the Bot sends appear in the Console, but not in the Twich Chat. In the Twich chat the Messages are only displayed on the Bots Channel.
Im Using tmi.js
My Code:
const tmi = require("tmi.js");
var config = require('./config');
const { channels } = require("./config");
const twitch_client = new tmi.client(config);
twitch_client.connect();
grussFormen = [
'Hi',
'Hallo',
'Guten Tag',
'Sehr geehrte Damen und Herren',
'Sehr geehrter Herr',
'Sehr geehrte Frau',
'Grüß dich',
'Grüß Sie',
'Grüezi',
'Hey',
'Hej',
'Moin',
'Servus',
'Na?',
'Was geht?'
];
verabschiedungen = [
'Mit freundlichen Grüßen',
'Viele Grüße',
'Liebe Grüße',
'Alles Liebe',
'Bis dann',
'Bis später',
'Bis morgen',
'Mach’s gut',
'Tschüss',
'Tschüssi',
'Tschü’',
'Schönen Tag noch',
'Schönen Abend noch',
'Ciao',
'Tschau',
'Tschaui',
'Wir sehen uns!',
]
twitch_client.on('connected', (address, port) =>{
// twitch_client.action('derNiklaas', 'Restarted');
});
twitch_client.on('chat', (channel, user, message, self) =>{
//In lowercase and withour Spaces
// analysingMessage = message.toLowerCase().replace(/\s/g, '');
//In lowercase
analysingMessage = message.toLowerCase();
//Nach Begrüßungs Formeln suchen
for (let item of grussFormen) {
if (analysingMessage.includes(' ' + item.toLowerCase()) || analysingMessage.includes(item.toLowerCase() + ' ') || analysingMessage == item.toLowerCase()){
twitch_client.action(channel, item + ' #' + user.username, (err) =>{
if(err){
console.log(err);
}
});
}
}
//Nach Verabschiedungen suchen
for (let item of verabschiedungen) {
if (analysingMessage.includes(' ' + item.toLowerCase()) || analysingMessage.includes(item.toLowerCase() + ' ') || analysingMessage == item.toLowerCase()){
twitch_client.action(channel, item + ' #' + user.username, (err) =>{
if(err){
console.log(err);
}
});
}
}
});
config.js (The Comments are not in:
module.exports = {
options: {
debug: true
},
connection: {
reconnect: true,
secure: true,
timeout: 180000,
reconnectDecay: 1.4,
reconnectInterval: 1000,
},
identity: {
username: 'isi_ko_bot',
password: 'I Removed my Password here :D'
},
channels: [
'derNiklaas' // A Channel I Whatch
// 'isi_ko_bot' // The Bots Channel
// 'isi_kohd' // My Channel
]
}
Screenshot of the Console:
It seems that you're trying to make it so that the bot react to a specific message, to do this use the following format.
if (message.startsWith("message you want the bot to react to")) {
//what you want the bot to do
}
example:
if (message.startsWith("hello")) {
client.say (channel, "Hello There!")
}

Catch the user that responses to an awaitMessages action

in my discord bot, i have a command that scrambles a word, and the first user that responds in the chat gets a reward. i already made the command to await a message response, but how can i save who responded? heres my code so far
authorID = msg.author.id;
const filter = response => {
return response.author.id === authorID;
}
msg.channel.awaitMessages(filter, {
max: 1,
time: 5000
})
.then(mg2 => {
if (mg2.first().content === "1") {
msg.channel.send("you said 1");
}
});
With the filter, you are only allowing the original msg author to enter, you should make it so it detects if the msg.content equals the unscrabbled word. Also you don't have errors: ["time"].
const filter = m => m.content === unscrabledWord;
msg.channel.awaitMessages(filter, { max: 1, time: 5000, errors: ["time"] })
.then(collected => {
const winner = collected.first().author;
msg.channel.send(`${winner} Won!`)
})
.catch(() => msg.channel.send("Nobody guessed it"));

Discord.js command handler with user permission ,client permission and throttling

How can i check user permission ,client permission , add throttling and define args in exports like commando does
my message event looks like this
client.on('message', async (message) => {
if (message.author.bot) return;
if (!message.guild) return;
let prefix
await db.collection('guilds').doc(message.guild.id).get().then((q) => {
if (q.exists) {
prefix = q.data().prefix || config1.prefix_mention;
} else {
prefix = "." || config1.prefix_mention;
}
})
const prefixRegex = new RegExp(`^(<#!?${client.user.id}>|${escapeRegex(prefix)})\\s*`);
if (!prefixRegex.test(message.content)) return;
const [ matchedPrefix ] = message.content.match(prefixRegex);
const args = message.content.slice(matchedPrefix.length).trim().split(/ +/g);
const cmd = args.shift().toLowerCase();
if (cmd.length === 0) return;
let command = client.commands.get(cmd);
if (!command) command = client.commands.get(client.aliases.get(cmd));
if (!message.channel.permissionsFor(client.user).has("SEND_MESSAGES")) return;
if (command)
command.run(client, message, args, db);
})
how can i check other permission like example
name: 'osu',
group: 'search',
memberName: 'osu',
description: 'Responds with information on an osu! user.',
clientPermissions: ["EMBED_LINKS","SEND_MESSAGES"],
userPermissions:['VIEW_CHANNEL'],
args: [
{
key: 'user',
prompt: 'What user would you like to get information on?',
type: 'string'
}
],
async run(client ,message ,args) {
//some code here
}
You can get client.user permissions and message.member permissions for message.channel and then check it with has.
About throttling , you can use cooldowns. This is the nice guide how to use it.
const { Permissions } = require('discord.js');
if(command.clientPermissions.length > 0) {
let clientChannelPermissions = message.channel.permissionsFor(message.guild.me);
clientChannelPermissions = new Permissions(clientChannelPermissions.bitfield);
if(!clientChannelPermissions.has(command.clientPermissions)) {
let missingPermissions = command.clientPermissions.filter(perm => clientChannelPermissions.has(perm) === false).join(', ')
return message.reply(`I can`t execute this command, missing permissions for ${missingPermissions}`)
}
}
if(command.userPermissions.length > 0) {
let memberChannelPermissions = message.channel.permissionsFor(message.member);
memberChannelPermissions = new Permissions(memberChannelPermissions.bitfield);
if(!memberChannelPermissions.has(command.clientPermissions)) {
let missingPermissions = command.clientPermissions.filter(perm => memberChannelPermissions.has(perm) === false).join(', ')
return message.reply(`I can`t execute this command, you missing permissions for ${missingPermissions}`)
}
}

Resources