How to fix "Cannot send messages to this user" - javascript

I tried sending messages to a user through their DMs and got the error Cannot send messages to this user.
Here is my code:
const Discord = require("discord.js")
const config = require("./config.json");
const client = new Discord.Client();
const fs = require('fs');
client.on('ready', () => {
console.log('ca marche!!!!')
setInterval(() => {
const guild = client.guilds.cache.get("758345919350964254");
if (!guild) return; // pour évité toute erreur
guild.members.fetch();
guild.members.cache.random().createDM().then(dm =>{
dm.send(".")})
console.log("ENFIIIIIIINNN")
}, 3000);
console.log('ca marche')
})
client.login(config.token);
I tried to catch the error but didn't succeed:
client.on('ready', () => {
console.log('ca marche!!!!')
setInterval(() => {
const guild = client.guilds.cache.get("758345919350964254");
if (!guild) return; // pour évité toute erreur
guild.members.fetch();
guild.members.cache.random().createDM().then(dm =>{
dm.send(".")}).catch(error => console.log('message impossible '))
console.log("ENFIIIIIIINNN")
}, 3000000);
console.log('ca marche')
})
client.login(config.token);
Info:
discord.js version: 14.6.0
node version: v19.0.0
Error:
Uncaught DiscordAPIError DiscordAPIError: Cannot send messages to this user

Related

TypeError: Cannot read properties of undefined (reading 'createdTimestamp')

I'm trying to create a ping command for my discord bot. My code seems pretty straightforward:
index.js:
require("dotenv").config();
const { Client, Intents, Collection } = require("discord.js");
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
});
const fs = require("fs");
client.commands = new Collection();
const commandFiles = fs
.readdirSync("./commands")
.filter((file) => file.endsWith(".js"));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.data.name, command);
}
const eventFiles = fs
.readdirSync("./events")
.filter((file) => file.endsWith(".js"));
for (const file of eventFiles) {
const event = require(`./events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args, client));
} else {
client.on(event.name, (...args) => event.execute(...args, client));
}
}
client.on("interactionCreate", (interaction) => {
console.log(interaction);
});
client.login(process.env.TOKEN);
messageCreate.js:
require("dotenv").config();
module.exports = {
name: "messageCreate",
on: true,
async execute(msg, client) {
// If message author is a bot, or the message doesn't start with the prefix, return.
if (msg.author.bot || !msg.content.startsWith(process.env.PREFIX)) return;
var command = msg.content.substring(1).split(" ")[0].toLowerCase();
// Remove the command from the args
var args = msg.content.substring().split(/(?<=^\S+)\s/)[1];
if (!client.commands.has(command)) return;
try {
await client.commands.get(command).execute(msg, args, client);
} catch (error) {
console.error(error);
await msg.reply({
content: "Error: Please check console for error(s)",
ephemeral: true,
});
}
},
};
ping.js:
const { SlashCommandBuilder } = require("#discordjs/builders");
const { MessageEmbed } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("ping")
.setDescription("Replies to ping with pong"),
async execute(msg, args, client, interaction) {
const embed = new MessageEmbed()
.setColor("#0099ff")
.setTitle("🏓 Pong!")
.setDescription(
`Latency is ${
Date.now() - msg.createdTimestamp
}ms. API Latency is ${Math.round(client.ws.ping)}ms`
)
.setTimestamp();
await interaction.reply({
embeds: [embed],
ephemeral: true,
});
},
};
I'm passing my msg parameter, so why is it that it doesn't recognize the msg.createdTimestamp within ping.js? EDIT: I've updated some of my code, updating the way the parameters are passed. Now I'm getting a TypeError: Cannot read properties of undefined (reading 'reply') error in my ping.js file.
So I figured it out. The msg portion of what I'm passing actually gets passed down to the interaction argument. Just had to change msg to interaction to get everything to work:
ping.js
const { SlashCommandBuilder } = require("#discordjs/builders");
const { MessageEmbed } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("ping")
.setDescription("Replies to ping with pong"),
async execute(interaction, args, client) {
const embed = new MessageEmbed()
.setColor("#0099ff")
.setTitle("🏓 Pong!")
.setDescription(
`Latency is ${
Date.now() - interaction.createdTimestamp
}ms. API Latency is ${Math.round(client.ws.ping)}ms`
)
.setTimestamp();
await interaction.reply({
embeds: [embed],
ephemeral: true,
});
},
};

Discord does not respond to commands

It is a simple command but my bot is not responding when I ask it. It has administrator priviledges so it should respond. What am I doing wrong?
const {
Client,
Intents,
Message
} = require('discord.js');
const client = new Client({
intents: [Intents.FLAGS.GUILDS]
});
const config = require("./config.json");
client.on('ready', () => {
console.log(`Bot ${client.user.tag} foi carregado em ${client.user.size} e esta online!`);
client.user.setGame(`Eu estou em ${client.guilds.size} servidores`)
});
client.on("guildCreate", guild => {
console.log(`O bot entrou nos Servidor: ${guild.me} (ID: ${guild.id}). QTD mebros: ${guild.memberCount} `);
client.user.setActivity('YouTube', {
type: 'WATCHING'
});
});
client.on("guildDelete", guild => {
console.log(`O bot foi removido do serivdor: ${guild.name} (ID: ${guild.id})`);
client.user.setActivity(`Serving ${client.guilds.size} servers`)
})
client.on("menssage", async message => {
if (message.author.bot) return;
if (menssage.channel.type === "dm") return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const comando = args.shift().toLowerCase();
if (comando === "ping") {
const m = await message.channel.send("Ping?");
m.edit(`Pong a latencia e ${m.createdTimesTamp - message.createdTimesTamp}ms. `)
}
});
client.login(config.token);
The function setGame doesn't exists, you need to change it to
client.user.setActivity(`Serving ${client.guilds.size} servers`, { type: 'PLAYING' })

Discord.js v12 send the error message from dm

I want to sending the error message from dm to users. But I'm getting ReferenceError: error is not defined error. How can I fix this?
if (error) {
client.users.cache.get(message.author.id).send(error)
}
Here is my index.js
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`\x1b[33m${client.user.tag} \x1b[0mgiriş yaptı!`);
client.user.setActivity(`Online on ${client.guilds.cache.size} servers`, {type: 'WATCHING'})
});
client.on('message', message => {
const { channel } = message
if (channel.type === 'news') {
message.crosspost().catch(console.error)
console.log(`\x1b[31m${message.guild.name}\x1b[0m sunucusunda duyuru yapıldı! \x1b[33m(ID: ${message.guild.id})`)
}
if (error) {
client.users.cache.get(message.author.id).send(error)
}
});
Your code doesn't seem to recognize 'error'. I don't know what your whole code is, but I prefer to use a catch instead.
.catch(error => {
return <user>.send(error);
})
Problem is solved.
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`\x1b[33m${client.user.tag} \x1b[0mgiriş yaptı!`);
client.user.setActivity(`Online on ${client.guilds.cache.size} servers`, {type: 'WATCHING'})
});
client.on('message', message => {
const { channel } = message
if (channel.type === 'news') {
message.crosspost().catch(error => {
console.log(error)
message.author.send(error.message)
})
console.log(`\x1b[31m${message.guild.name}\x1b[0m sunucusunda duyuru yapıldı! \x1b[33m(ID: ${message.guild.id})`)
}
});

why does my discord bot don't seem to hear?

Well, I would create a discord bot that will stock given data in a database, .then I began to learn js
Until now i haven't any problem and found a lot of help in the web, before to create the database i tried to show detected data on the console but now I'm blocked and can't understand by myself where is the problem.
here is my code
const Discord = require('discord.js')
const client = new Discord.Client();
const { promisify } = require('util')
const sleep = promisify(setTimeout)
require('dotenv').config();
const BOT_TOKEN = '******'
client.on('ready', async () => {
console.log(`The bot is now working !\n\n`);
});
client.on('message', async (receivedMessage) => {
// Prevent bot from responding to its own messages
if (receivedMessage.author == client.user) {
return;
}
const { author, content, channel } = receivedMessage;
const { id } = author;
const trimmedContent = content.trim();
if (trimmedContent.startsWith('!ins')) {
console.log('Inside ins');
module.exports = {
prefix: "!ins",
fn: (msg) => {
let application = {}
let filter = (msg) => !msg.author.bot;
let options = {
max: 1,
time: 15000
};
msg.member.send("nom ?")
.then(dm => {
// After each question, we'll setup a collector on the DM channel
return dm.channel.awaitMessages(filter, options)
})
.then(collected => {
// Convert the collection to an array & get the content from the first element
application.name = collected.array()[0].content;
// Ask the next question
return msg.member.send("Parfait, maintenant votre mail ?")
})
.then(dm => {
return dm.channel.awaitMessages(filter, options)
})
.then(collected => {
application.emailAddress = collected.array()[0].content;
return msg.member.send("Excellent. Enfin, quel est votre âge ?")
})
.then(dm => {
return dm.channel.awaitMessages(filter, options)
})
.then(collected => {
application.pitch = collected.array()[0].content;
console.log(application)
})
}
}
}
});
// client.login logs the bot in and sets it up for use. You'll enter your token here.
client.login(' ');
The problem is that bot doesn't react to !ins command and on the console I only have the console.log 2 and 3
if you need any more info, feel free to ask them and thanks for taken time
I do think that you should code your main structure like mine because yours is a bit messy.
const Discord = require('discord.js');
const client = new Discord.Client();
const BOT_TOKEN = '...';
client.on('ready', async () => {
console.log(`The bot is now working !\n\n`);
});
client.on('message', async (receivedMessage) => {
// Prevent bot from responding to its own messages
if (receivedMessage.author == client.user) {
return;
}
const { author, content, channel } = receivedMessage;
const { id } = author;
// Removes whitespace from both ends of a string, "I personally do like this"
const trimmedContent = content.trim();
if (trimmedContent.startsWith('!ins')) {
console.log('Inside ins');
}
});
client.login(BOT_TOKEN);
process.on('exit', () => {
client.destroy();
console.log(`The bot is now disconnected !\n\n`);
});

How can I fix these TypeErrors in my Discord bot?

I am getting a few errors:
line 12: TypeError: Cannot read property 'user' of undefined
line 14: TypeError: Cannot read property 'guilds' of undefined
I might have a few other errors that I haven't seen yet.
How can I fix these errors?
Here is the code for my Discord bot:
console.log("hi");
const { RichEmbed } = require("discord.js");
const randomPuppy = require("random-puppy");
const Discord = require('discord.js');
const client = new Discord.Client();
const token = 'token';
client.on('ready', async client => {
console.log('This bot is online');
client.user.setActivity("Youtube", {type: "Watching"})
client.guilds.cache.forEach((guild) => {
console.log(guild.name)
guild.channels.cache.forEach((channel) => {
console.log(` - ${channel.name} ${channel.type} ${channel.id}`)
})
//general text id: 721950719657115750
})
const jpg = "https://cdn.discordapp.com/attachments/709199176562638849/722646217930178620/OIPK7JS66QT.jpg"
const img = await randomPuppy(jpg);
const embed = new RichEmbed()
.setColor("RANDOM")
.setImage(img)
.setTitle(`From /r/${random}`)
.setURL(`https://reddit.com/r/${random}`);
message.channel.send(embed);
})
client.on('message', msg=>{
if(msg.content === "hello"){
msg.reply('hello')
}
})
client.login(token);
Try
client.user.setPresence({
activity: {name: 'Youtube'},
status: 'Watching'
})

Categories

Resources