Discord Bot Not Receiving Interactions - javascript

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

Related

Discord bot not responding on the server [duplicate]

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'

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

Heroku Keeps timing out: Error waiting for network: Resource temporarily unavailable

My index.js file:
const Discord = require('discord.js');
const levels = require('discord-xp');
const client = new Discord.Client();
const mongoose = require('./database/mongoose');
const fs = require(`fs`);
require('dotenv').config();
const port = process.env.PORT || 5000;
const host = '0.0.0.0';
const chalk = require('chalk');
const { Player } = require('discord-player');
const Gamedig = require('gamedig');
client.prefix = (`${process.env.PREFIX}`);
client.commands = new Discord.Collection();
client.player = new Player(client);
client.config = require('./config/bot');
client.emotes = client.config.emojis;
client.filters = client.config.filters;
fs.readdirSync('./commands').forEach(dirs => {
const commands = fs.readdirSync(`./commands/${dirs}`).filter(files => files.endsWith('.js'));
for (const file of commands) {
const command = require(`./commands/${dirs}/${file}`);
console.log(`Loading command ${file}`);
client.commands.set(command.name.toLowerCase(), command);
};
});
const player = fs.readdirSync(`./player`).filter(file => file.endsWith('.js'));
const events = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
for (const file of player) {
console.log(`Loading discord-player event ${file}`);
const event = require(`./player/${file}`);
client.player.on(file.split(".")[0], event.bind(null, client));
};
for (const file of events) {
console.log(`Loading discord.js event ${file}`);
const event = require(`./events/${file}`);
client.on(file.split(".")[0], event.bind(null, client));
};
mongoose.init();
client.login(process.env.TOKEN)
My Procfile:
Worker: node index.js
My package.json:
{
"name": "icrp-bot",
"version": "1.0.0",
"description": "Made For ICRP ",
"main": "index.js",
"scripts": {
"test": ".test",
"start": "node index.js"
},
"author": "Bombo43453#1901",
"license": "ISC",
"dependencies": {
"axios": "^0.21.1",
"baseplayer": "^0.2.9",
"chalk": "^4.1.1",
"discord-fivem-api": "^1.0.4",
"discord-player": "^3.4.0",
"discord-xp": "^1.1.14",
"discord.js": "^12.5.3",
"dotenv": "^8.2.0",
"ffmpeg-static": "^4.3.0",
"gamedig": "^3.0.1",
"log-timestamp": "^0.3.0",
"moment": "^2.29.1",
"moment-timezone": "^0.5.33",
"mongoose": "^5.11.14",
"node-gyp": "^8.0.0",
"opus": "0.0.0",
"opusscript": "0.0.8",
"pm2": "^4.5.6",
"python": "0.0.4",
"rebuild": "^0.1.2"
}
}
Full Error:
2021-04-23T17:18:33.808571+00:00 heroku[Worker.1]: State changed from down to starting
2021-04-23T17:18:43.196477+00:00 heroku[Worker.1]: Starting process with command `node index.js`
2021-04-23T17:18:43.846098+00:00 heroku[Worker.1]: State changed from starting to up
2021-04-23T17:18:43.854420+00:00 heroku[Worker.1]: Idling
2021-04-23T17:18:43.856605+00:00 heroku[Worker.1]: State changed from up to down
2021-04-23T17:18:43.870047+00:00 heroku[Worker.1]: Idling because quota is exhausted
2021-04-23T17:18:50.422071+00:00 app[Worker.1]: Error waiting for network: Resource temporarily unavailable
Info: this is a simple bot I have made for a fivem server. I tried to host it with heroku and tried to fix it. I tried adding a port const and a const host but that did not fix anything. I also think that my issue is very small and I have 200 hours left on heroku meaning that hours are not the issue. I tried changing the port to 8080 too and that did not help with anything. If you have an idea please tell me.
I know you said you have 200 hours left.
But Idling because quota is exhausted only shows when you run out of free hours.
Also you said you changed the port to 8080 but please note that YOU CAN'T CHANGE THE PORT ON HEROKU you get the port as env variable (Like process.env.PORT as you did above) and you can't change it.
If you're using worker that means you can't run a web process and the PORT is useless anyway.
About your last Error this is from Heroku support
This is caused by kernel-level issues that can surface occasionally on the backend instances that dynos run on. Unfortunately, there is not really a work around for this issue. Scheduler dynos will crash if this happens and the job will not be executed again until its next scheduled run time. Other dyno types will typically enter a bad state and require a manual restart (you may see "App boot timeout" errors when this happens).
Check this

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

Deploying botkit framework to azure and testing in the webchat returns 502

For my internship I am making a chatbot. I created a bot using botkit framework (yo botkit) and got as far as using it in the ms Teams client. But only using my localhost + ngrok setup. when I want to use https://{myproject}.azurewebsites.net/api/messages after deployment I get a 502 error message.
To try if I actually did my deployment okay, I made another project using "yo botbuilder" without botkit framework. Following the same steps I deployed it to a fresh Group. This time using the https://{myproject}.azurewebsites.net/api/messages url worked. (standard echo bot)
After that, I copied my bot files from my first project into my new one and replaced my index.js from my standard botbuilder project with my bot.js file from my botkit framework project.
I just used the standard botbuilder -> index.js file and botkit -> bot.js file +
in my package.json I changed the main and the scripts to point to bot.js instead of index.js.
After deploying, it just gave me my 502 again.
index.js
const dotenv = require('dotenv');
const path = require('path');
const restify = require('restify');
// Import required bot services.
// See https://aka.ms/bot-services to learn more about the different parts of a bot.
const { BotFrameworkAdapter } = require('botbuilder');
// This bot's main dialog.
const { EchoBot } = require('./bot');
// Import required bot configuration.
const ENV_FILE = path.join(__dirname, '.env');
dotenv.config({ path: ENV_FILE });
// Create HTTP server
const server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, () => {
console.log(`\n${ server.name } listening to ${ server.url }`);
console.log('\nGet Bot Framework Emulator: https://aka.ms/botframework-emulator');
console.log('\nTo talk to your bot, open the emulator select "Open Bot"');
});
// Create adapter.
// See https://aka.ms/about-bot-adapter to learn more about how bots work.
const adapter = new BotFrameworkAdapter({
appId: process.env.MicrosoftAppId,
appPassword: process.env.MicrosoftAppPassword
});
// Catch-all for errors.
const onTurnErrorHandler = async (context, error) => {
// This check writes out errors to console log .vs. app insights.
// NOTE: In production environment, you should consider logging this to Azure
// application insights.
console.error(`\n [onTurnError] unhandled error: ${ error }`);
// Send a trace activity, which will be displayed in Bot Framework Emulator
await context.sendTraceActivity(
'OnTurnError Trace',
`${ error }`,
'https://www.botframework.com/schemas/error',
'TurnError'
);
// Send a message to the user
await context.sendActivity('The bot encountered an error or bug.');
await context.sendActivity('To continue to run this bot, please fix the bot source code.');
};
// Set the onTurnError for the singleton BotFrameworkAdapter.
adapter.onTurnError = onTurnErrorHandler;
// Create the main dialog.
const myBot = new EchoBot();
// Listen for incoming requests.
server.post('/api/messages', (req, res) => {
adapter.processActivity(req, res, async (context) => {
// Route to main dialog.
await myBot.run(context);
});
});
// Listen for Upgrade requests for Streaming.
server.on('upgrade', (req, socket, head) => {
// Create an adapter scoped to this WebSocket connection to allow storing session data.
const streamingAdapter = new BotFrameworkAdapter({
appId: process.env.MicrosoftAppId,
appPassword: process.env.MicrosoftAppPassword
});
// Set onTurnError for the BotFrameworkAdapter created for each connection.
streamingAdapter.onTurnError = onTurnErrorHandler;
streamingAdapter.useWebSocket(req, socket, head, async (context) => {
// After connecting via WebSocket, run this logic for every request sent over
// the WebSocket connection.
await myBot.run(context);
});
});
bot.js
const { Botkit } = require('botkit');
const { BotkitCMSHelper } = require('botkit-plugin-cms');
// Import a platform-specific adapter for botframework.
const { MongoDbStorage } = require('botbuilder-storage-mongodb');
// Load process.env values from .env file
require('dotenv').config();
let storage = null;
if (process.env.MONGO_URI) {
storage = mongoStorage = new MongoDbStorage({
url : process.env.MONGO_URI,
});
}
const controller = new Botkit({
webhook_uri: '/api/messages',
adapterConfig: {
appId: process.env.APP_ID,
appPassword: process.env.APP_PASSWORD,
},
storage
});
if (process.env.CMS_URI) {
controller.usePlugin(new BotkitCMSHelper({
uri: process.env.CMS_URI,
token: process.env.CMS_TOKEN,
}));
}
// Once the bot has booted up its internal services, you can use them to do stuff.
controller.ready(() => {
// load traditional developer-created local custom feature modules
controller.loadModules(__dirname + '/features');
/* catch-all that uses the CMS to trigger dialogs */
if (controller.plugins.cms) {
controller.on('message,direct_message', async (bot, message) => {
let results = false;
results = await controller.plugins.cms.testTrigger(bot, message);
if (results !== false) {
// do not continue middleware!
return false;
}
});
}
});
controller.webserver.get('/', (req, res) => {
res.send(`This app is running Botkit ${ controller.version }.`);
});
package.json
{
"name": "my-chat-bot",
"version": "1.0.0",
"description": "Demonstrate the core capabilities of the Microsoft Bot Framework",
"author": "Generated using Microsoft Bot Builder Yeoman generator v4.7.0",
"license": "MIT",
"main": "bot.js",
"scripts": {
"start": "node ./bot.js",
"watch": "nodemon ./bot.js",
"lint": "eslint .",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "https://github.com"
},
"dependencies": {
"botbuilder": "~4.7.0",
"dotenv": "^8.2.0",
"restify": "~8.4.0",
"botbuilder-storage-mongodb": "^0.9.5",
"botkit": "^4.6.2",
"botkit-plugin-cms": "^1.0.3",
"firebase-admin": "^8.9.2",
"jira-client": "^6.15.0",
"request": "^2.88.2"
},
"devDependencies": {
"eslint": "^6.6.0",
"eslint-config-standard": "^14.1.0",
"eslint-plugin-import": "^2.18.2",
"eslint-plugin-node": "^10.0.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-standard": "^4.0.1",
"nodemon": "~1.19.4"
}
}

Categories

Resources