Discord bot not responding on the server [duplicate] - javascript

This question already has an answer here:
message.content doesn't have any value in Discord.js
(1 answer)
Closed 3 months ago.
I'm following this tutorial: https://www.youtube.com/watch?v=qv24S2L1N0k&t=1s
the bot is working in the terminal, but not on the Discord Server.
bot.js:
require('dotenv').config()
const Discord = require('discord.js')
const client = new Discord.Client()
client.on('ready', () => {
console.log('Our bot is ready to go!!!')
})
client.login(process.env.BOT_TOKEN)
client.on("message", msg => {
if(msg.content === 'ping'){
msg.channel.send("Not tagged")
}
})
package.json
{
"name": "bot_development",
"version": "1.0.0",
"description": "",
"main": "bot.js",
"scripts": {
"start": "node bot.js",
"devStart": "nodemon bot.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"discord.js": "^12.5.3",
"dotenv": "^8.2.0",
"node": "^16.18.1"
},
"devDependencies": {
"nodemon": "^2.0.20"
}
}
I've tried with
const client = new Discord.Client({intents: ["GUILDS", "GUILD_MESSAGES"]})
and I've tried "messageCreate" instead of "message", like this:
require('dotenv').config()
const Discord = require('discord.js')
const client = new Discord.Client({intents: ["GUILDS", "GUILD_MESSAGES"]})
client.on('ready', () => {
console.log('Our bot is ready to go!!!')
})
client.login(process.env.BOT_TOKEN)
client.on("messageCreate", msg => {
if(msg.content === 'ping'){
msg.channel.send("Not tagged")
}
})
Is there any problem outside of my code? I've done the rest of the configuration at the dev portal in the tutorial.

client.on("message", msg => {
if(msg.content === "ping"){
//try msg.reply("pong") if the code below does not work
msg.channel.send("Not tagged");
}
})
try changing createMessage to 'message'

Related

TypeError: Cannot read properties of undefined (reading 'FLAGS') when trying to do 'node index.js' [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 7 months ago.
Improve this question
I am trying to make a discord bot using the OPENAI API and when I try to use the command 'node index' I get the following error:
[ERROR IMAGE][1]
index.js FILE:
const {
Client,
Intents,
} = require('discord.js');
const bot = new Client({
intents: [Intents.FLAGS.Guild, Intents.FLAGS.Guild_Members, Intents.FLAGS.Guild_Messages]
});
bot.on('ready', () => {
console.log(`Bot ${bot.user.tag} is logged in!`);
});
bot.login('OTk5MTQ0NjU3ODgxNjc3ODY1.GvMgQX.dz3r43fDHi6nqB_cO55gSHhO2jJJ-zBKQIjF5k');
bot.on('ready', () => {
console.log(`Bot ${bot.user.tag} is logged in!`);
});
Package.json file:
{
"name": "discord-gpt3-bot",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/nrrpatel/discordbot.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/nrrpatel/discordbot/issues"
},
"homepage": "https://github.com/nrrpatel/discordbot#readme",
"dependencies": {
"discord.js": "^14.0.3",
"dotenv": "^16.0.1",
"openai-api": "^1.3.1",
"typescript": "^4.7.4"
}
}
It looks like you're using an older implementation for the newest version of discord.js. If you follow the changelog for its v14, you'll see the client initialization changed.
So instead of:
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
You should be using:
const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });

DiscordJS interactionCreate and messageCreate not working

I know this and this post both have similar titles but the solution to both is not working for me.
As you can see in my code below I've used Intents.FLAGS.GUILD_MESSAGES to create the client variable but it doesn't give any output in my console when I do the /ping command that I made. /ping however is available in when typing "/" in chat.
const { clientId, token, testGuildId } = require('./config.json');
const Discord = require('discord.js');
const fs = require('fs');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const client = new Discord.Client({
intents: [
Discord.Intents.FLAGS.GUILDS,
Discord.Intents.FLAGS.GUILD_MESSAGES,
Discord.Intents.FLAGS.DIRECT_MESSAGES,
],
});
const commandFiles = fs.readdirSync(`./Commands/commandScripts`).filter(file => file.endsWith(".js"));
//for
const commandsArray = [];
client.commandsArray = new Discord.Collection();
for (const file of commandFiles){
const newCommand = require(`./Commands/commandScripts/${file}`);
commandsArray.push(newCommand.data.toJSON());
client.commandsArray.set(newCommand.data.name, newCommand);
}
client.once('ready', async () => {
const rest = new REST({
version: "9"
}).setToken(token);
(async () => {
try {
if(process.env.ENV === "production"){
await rest.put(Routes.applicationCommands(clientId), {
body: commandsArray,
});
console.log("Successfully registered commands globally.");
} else {
var temp = await rest.put(Routes.applicationGuildCommands(clientId, testGuildId), {
body: commandsArray,
});
console.log(temp);
console.log("Successfully registered commands locally.");
}
} catch (err) {
if(err) console.error(err);
}
})();
console.log(`[${time}] *** Bot Is Ready On Discord!`);
});
client.on('interactionCreate', async interaction => {
console.log(interaction);
});
client.on("messageCreate", (message) => {
console.log(message.content);
})
client.login(token);
My package.json:
{
"name": "excavator",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"#discordjs/builders": "^0.12.0",
"#discordjs/opus": "^0.3.3",
"#discordjs/rest": "^0.3.0",
"axios": "^0.21.1",
"discord-api-types": "^0.27.3",
"discord.js": "^12.5.3",
"ffmpeg-static": "^4.2.7",
"fs": "0.0.1-security",
"mongoose": "^5.13.14",
"path": "^0.12.7",
"simple-youtube-api": "^5.2.1",
"yt-search": "^2.5.1",
"ytdl-core": "^4.4.5",
"ytdl-core-discord": "^1.2.5"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "ExcanatorGames",
"license": "ISC"
}
Figured out the problem. I needed to uninstall discord.js and reinstall discord.js

Discord Bot Not Receiving Interactions

I'm a relatively experienced developer (graduated recently), trying to get back into discord bots after I made a few a couple of years ago.
I've been following the guide on discordjs.guide, but even with the basic "hello world" style program, I am already stuck.
The program gives no errors when running, but no interactions come through in the console.
When I start the script, the bot switches to "online." Curiously, the bot does not switch back to "offline" until I regenerate the token. Not sure if that is related.
I've verified process.env.BOT_TOKEN is the correct value.
I've confirmed client.login runs successfully.
I've tried DMing the bot directly
I've tried sending messages on guild channels
I've tried #ing the bot
Is there something super obvious I'm not understanding/seeing? Otherwise, what else should I try as a troubleshooting step?
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
client.once('ready', () => {
console.log('Ready!');
});
client.on('interactionCreate', interaction => {
console.log(interaction);
});
client.login(process.env.BOT_TOKEN);
package.json:
{
"name": "timebot",
"version": "1.0.0",
"description": "",
"main": "start.js",
"scripts": {
"start": "node -r dotenv/config start.js dotenv_config_path=secrets.env",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"discord.js": "^13.1.0",
"dotenv": "^10.0.0"
}
}
Turns out, messages are not classified as "interactions" by discord.js. Additionally, you have to specify the intent to listen for messages, otherwise, the event won't be passed to your bot. Here is the revised code with those two critical changes:
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.DIRECT_MESSAGES] });
client.once('ready', () => {
console.log('Ready!');
});
client.on('interactionCreate', interaction => {
console.log(interaction);
});
client.on("messageCreate", message => {
console.log(message);
});
client.login(process.env.BOT_TOKEN);

Failed to launch the browser process! when deploying node.js app on shared hosting

So I built a simple project to test out and it works well on my local machine. the challenge comes when I deploy it on my Cpanel hosting I get an error A UnhandledPromiseRejectionWarning: Error: Failed to launch the browser process!
//app.json
const { Client } = require('whatsapp-web.js');
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const client = new Client();
client.on('qr', (qr) => {
// Generate and scan this code with your phone
console.log('QR RECEIVED', qr);
});
client.on('ready', () => {
console.log('Client is ready!');
});
client.on('message', msg => {
if (msg.body == '!ping') {
msg.reply('pong');
}
});
client.initialize();
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
// package.json
{
"name": "puppet",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start" : "node app.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"whatsapp-web.js": "^1.12.0"
}
}
everything installs correctly but when the app starts it writes this error in the log file
App 4096690 output: (node:4096690) UnhandledPromiseRejectionWarning: Error: Failed to launch the browser process!
App 4096690 output: /home/linearcb/nodevenv/repositories/whatsapp/10/lib/node_modules/puppeteer/.local-chromium/linux-818858/chrome-linux/chrome: error while loading shared libraries: libatk-1.0.so.0: cannot open shared object file: No such file or directory

"Error: Client network socket disconnected before secure TLS connection was established" on Firebase Function

I am using nodemailer with my Firebase Functions (server-side functions) for my React.js project and am getting the error: Error: Client network socket disconnected before secure TLS connection was established... and causing some emails to not be sent out. This is a big issue for this project, as the client can't be missing emails sent from the system. Why am I getting this error and how might I remedy it?
Firebase Function index.js:
"use strict";
import functions = require('firebase-functions');
import admin = require("firebase-admin");
import nodemailer = require('nodemailer');
import { DocumentSnapshot } from 'firebase-functions/lib/providers/firestore';
import { Change, EventContext } from 'firebase-functions';
import { Status } from './common';
admin.initializeApp(functions.config().firebase);
export const onUserCreated = functions.firestore.document('users/{userId}')
.onCreate(async (snap: { data: () => any; }) => {
console.log("Client create heard! Starting inner...")
const newValue = snap.data();
try {
console.log("Started try{}...")
// Template it
const htmlEmail =
`
<div>
<h2>client Sign Up</h2>
`
// Config it
const transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 465,
secure: true,
auth: {
user: functions.config().email.user,
pass: functions.config().email.password
}
})
console.log("transporter = " + transporter)
// Pack it
const mailOptions = {
from: `email123#gmail.com`,
to: 'email123#gmail.com',
replyTo: `${newValue.email}`,
subject: `user sign up`,
text: `A new user sign up with the email of ${newValue.email}.`,
html: htmlEmail
}
// Send it
transporter.sendMail(mailOptions, (err: any) => {
if(err) {
console.error(err);
} else {
console.log("Successfully sent mail with sendMail()!");
}
})
} catch (error) {
console.error(error)
}
});
Functions package.json:
{
"name": "functions",
"scripts": {
"lint": "tslint --project tsconfig.json",
"build": "tsc",
"serve": "npm run build && firebase emulators:start --only functions",
"shell": "npm run build && firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "10"
},
"main": "lib/index.js",
"dependencies": {
"#types/nodemailer": "^6.4.0",
"firebase-admin": "^9.4.1",
"firebase-functions": "^3.11.0",
"nodemailer": "^6.4.16"
},
"devDependencies": {
"firebase-functions-test": "^0.2.3",
"tslint": "^5.12.0",
"typescript": "^3.8.0"
},
"private": true
}
Full error:
In my case the error gone after adding TLS version to nodemailer options:
let transporter = nodemailer.createTransport({
host: 'smtp-server',
port: 25,
tls: {
ciphers : 'SSLv3',
},
});
You should return a promise to avoid unexpected Fuctions behaviour like early termination.
Checking Nodemailer API documentation
I can see that transporter.sendMail returns a promise. So just returning this promise should fix your issue:
export const onUserCreated = functions.firestore.document('users/{userId}')
.onCreate(async (snap: { data: () => any; }) => {
....
return transporter.sendMail(mailOptions)
}

Categories

Resources