Crash after sending a message? [closed] - discord

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
my discord.js bot works but crashes after sending a reply, why?
using the example provided on the website and it does not work
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Bot ready`);
});
client.on('message', msg => {
if (msg.content === 'ping') {
msg.reply('Pong!');
});
help me fix it please, thank you

You are missing the closing bracket in the if condition
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Bot ready`);
});
client.on('message', msg => {
if (msg.content === 'ping') {
msg.reply('Pong!');
}
});
should fix it

Related

How to Pin a Message in Discord

I am trying to make a discord bot for a small server that I am in, and I want it to pin a certain message to the channel that it was sent in. I have done a few bots before, but it seems that the syntax has changed since I last used it, and code that I was going to reuse no longer works. I have managed to get around some of those changes (like the intents,) but when I try to check for a sent message, it just does nothing. My current code
const { Client, Intents } = require("discord.js");
const { token } = require("./config.json");
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
client.once("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("message", (msg) => {
if (msg.content == "something goes here") {
msg.pin()
}
});
client.login(token);
I have tried supplementing messageCreate for message like I have seen a few people recommend, but it still seems to do nothing. Even changing the msg.pin() to console.log(msg) still shows nothing in the console
client.on("messageCreate", (msg) => {
if (msg.content == "something goes here") {
console.log(msg)
}
});
I do have the privileged intent toggle enabled, so I don't think that that is the problem
[privileged toggles]
Does anybody know what the problem here is, and how I could fix it? Any help is appreciated, thanks!
First of all, you have not enabled the GUILD_MESSAGES intent in your client so you need to add that by doing this:
const client = new Client({
intents: [
Intents.FLAGS.GUILDS
Intents.FLAGS.GUILD_MESSAGES
]
});
Other than that, the .pin() function is still there and there is no change in it. You can provide a reason as well. The .pin() function also returns a promise, so you will have to use .then() or await, so your final code might look like this:
const { Client, Intents } = require("discord.js");
const { token } = require("./config.json");
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
client.once("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("message", (msg) => {
if (msg.content == "something goes here") {
msg.pin().then(() => console.log)
}
});
client.login(token);
You can learn more about the .pin() function here => pin | discord.js
For Discord.js v13 use the following:
const { Client } = require("discord.js");
const { token } = require("./config.json");
const client = new Client({
intents: new Intents(32767)
});
client.login(token)
client.on("message", (ctx) => {
if (ctx.content == "something goes here") {
ctx.pin(ctx.id, "Pinned")
}
});

How can I make a discord bot that will DM new users when they join the server?

So basically I've been working on this one bot for my server, I want it to DM the users that join the server, Like whenever a user joins my server, they would receive a DM by my bot?
I have used this code now, but it doesn't seem to work, can anyone help?
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Bot is ready!');
bot.on("guildMemberAdd", member => {
member.send("Welcome to the server!")
.catch(console.error);
});});
client.login('<token>');
you are using wrong way it is client not bot. Cause you are initial your bot as client since const client = new Discord.Client();. And there is no need to wrap it in ready event
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Bot is ready!');
});
client.on("guildMemberAdd", member => {
console.log("new member join")
member.send("Welcome to the server!").catch(console.error);
});
client.login('<token>');

Fetch data from back end to front end after getting it in router from database [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am building a mern expo app login and signin page. When clicking the signin button it should login but I couldn't get the data from the backend though i already made the find query inside the router express. I believe my code will help you understand better.
routeSignIn.js
const express = require("express");
const router = express.Router();
const User = require("../models/User");
router.post("/", async (req, res) => {
User.findOne({ email: req.body.email }).then((user) => {
if (!user) {
return res.status(404).json("Email or password is incorrect");
} else {
const foundUser = res.json(user);
}
});
});
module.exports = router;
Server.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const url = "mongodb://localhost/my-project1";
mongoose.connect(url, { useNewUrlParser: true });
const con = mongoose.connection;
app.use(express.json());
//Router
const routeSignIn = require("../route/routeSignIn");
app.use("/getUser", routeSignIn);
con.on("open", () => {
console.log("Database is connected...");
});
const server = app.listen(3000, () => {
const { address, port } = server.address();
console.log(`Server started. Listening at http://${address}:${port}`);
});
This is where the problem is, I couldn't fetch it from the router
SignIn.js
const loginHandle = (email, password) => {
axios
//The address here is my laptop IP address, because i wanted to link my mern server with expo server
.get("http://192.168.29.7:3000/getUser")
.then((res) => {
if (!res) {
Alert.alert("Invalid User, Username or password is incorrect.");
}
})
.catch((err) => {
console.log("Error fetching data : ", err);
});
if (data.email.length == 0 || data.password.length == 0) {
Alert.alert("Email or password field cannot be empty");
}
};
App.js
const authContext = useMemo(
() => ({
signIn: async (email) => {
const userToken = String(foundUser);
try {
await AsyncStorage.setItem("userToken", userToken);
} catch (err) {
console.log("SignIn error", err);
}
dispatch({ type: "LOGIN", email: email, token: userToken });
},
}),
[]
);
As you can see above what i wanted to do is after routing(in routeSignIn.js) with the specific user i wanted to fetch that data(from signIn.js) and pass that data into App.js to dispatch it. Note that the reducers function is in the same file(App.js) as that of the the dispatch.
I think there are several issues that I can detect with the way you are posting and retrieving data from your DB.
First of all, you are using axios.get function instead of axios.post and you are posting it to a URL that simply doesn't exist ("http://192.168.29.7:3000/getUser"). You will instead need to use someting like "/getUser/login". Also define your const as loginHandle = userData and in your userData define email as user.email and password as user.password.
In the server-side you might want to use port 3000 or 5000 and see which one works the best as sometimes you might need to run your server on port 5000.
In your routeSignIn.js file, use router.post("/login" instead so you can make sure you are routing to the correct URL.
I am not quite sure about your app.js so not gonna comment on it.
Hopefully this, to some extent, fixes your problem but I would recommend following this as much as possible and when you are comfortable with NodeJS and React, then customise the code.

A bot that deletes all messages except for messeges saying "potato"

I have been trying to make a bot that only allows the messages saying, "potato" and deletes all other messages with different content. (I am very new to this stuff.)
Here is the code I've tried so far, created by a user here:
client.on("message", (message) => {
if(message.content != "potato") return message.delete()
});
When I input it into the code, I get an indent error and a semi-colon error. When I auto fix them, I get this code:
client.on("message", (message) => {
if(message.content != "potato") return message.delete();
});
The terminal repeats back the messages in the server (has no roles or perms), but doesn't delete them in discord if they aren't "potato". The bot has Admin perm.
Any edits or suggestions? (I do have a linter, not sure if relevant.)
Thanks, PM
Rest of code:
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
client.login('TOKEN');
client.on("message", (message) => {
if(message.content !== "potato") return message.delete();
});
You need to put await before the message.delete() otherwise it won't work.
It's also better for code readability to put client.login at the bottom of the code.
Your code should look like this:
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
client.on("message", async (message) => {
if(message.content !== "potato") {return await message.delete();}
});
client.login('TOKEN');

Discord.js client.channel.cache.get().send() is not a Function

const Discord = require('discord.js');
const client = new Discord.Client();
const token = 'token';
client.on('ready', () => {
client.channels.cache.get('channelid').send('Test');
});
client.login(token);
Whenever I try to run this, it always says: "(node:20284) UnhandledPromiseRejectionWarning: TypeError: client.channels.cache.get(...).send is not a function"
This is not really a solution, but rather a workaround. This problem is caused probably because the channels ain't being stored on the ChannelManager cache, I don't know the solution to this (I can edit the answer if somebody does), but you could fetch the channel directly using the promise based ChannelManager.fetch(id: string), like that:
const { Client } = require('discord.js');
const client = new Client();
client.on('ready', async function() {
const channel = await client.channels.fetch('channelId');
channel.send('message');
});
client.login('token');

Resources