Discord bot not answering messages - node.js

i've been trying a new project which is to code a discord bot with discord.js in node. The source code for interactions in the discord.js documentation works but, when i followed online tutorials, the bot does not reply to my messages in the discord server. please do correct me!, the bot seems to go online as my console does work. but the rest is history
const Discord = require('discord.js');
const env = require("./botconfig.json"); //json file containing tokens & IDs
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
let prefix = env.prefix;
client.on("ready", ()=>{
console.log(`${client.user.tag} is online in ${client.guilds.cache.size} servers`)
console.log(`the prefix is ${prefix}`);
})
client.on("messageCreate", Message => {
if (Message === "ping") {
Message.channel.send('Pong.');
}
});
client.login(env.token);

On the client.on("messageCreate", the second argument is a function that takes a Message object, NOT the message as a string! (check the class here https://discord.js.org/#/docs/discord.js/stable/class/Message). You may wanna try the following:
// Access the `content` property of the message
if (Message.content === "ping") {
Message.channel.send('Pong.');
}
Also seems the tutorials you're seeing are kind of deprecated. Discord.js has a lot of new stuff to make those easier and more organized. I would suggest you to try building your bot while following the official docs which are pretty good :) https://discord.js.org/#/docs/discord.js/stable/general/welcome

The messageCreate event does not pass a string, it passes a Discord.js Message class instance, as DJS is object-oriented. Just access the .content property such as message.content.

Related

Twitch bot with node.js

Im new to node and tried to make a simple twitch chat bot with node.js following a youtube tutorial but
everything works untill i try to use "!" command... I use the command and the bot simply doesnt respond to the command.
Here is what i have so far:
const tmi = require('tmi.js'),
{channel , username , password } = require('./settings.json');
const options = {
options: {debug: true},
connection: {
reconnct: true,
secure: true
},
identity : {
username,
password
},
channel: [channel]
};
const client = new tmi.Client(options);
client.connect().catch(console.error);
client.on('connected', () => {
client.say(channel, `${username} joined the chat`)
})
client.on('message', (channel, user, message ,self) => {
if(self) return;
if(message == '!ping') {
client.say(channel, `#${user.username}, pong`);
}
});
I cant figure it out i just want it to respond
I only played a bit with twitch bots a while ago, but the problem might be the part where you return on self:
if(self) return;
This means that if a message comes from the bot itself, it will be ignored and the function will return (and therefore stop). Meaning that if you linked the bot to the same account from which you are sending messages, those messages are ignored.
Also:
you mispelled reconnect with reconnct in the connection options
in JS I would recommend to use === instead of == because the latter attempts to convert and compare operands that are of different types (you can learn more here)
Edit: what also helps in general is to use console.log() to debug and find out where the problem is

v11 TypeError: Cannot read properties of undefined (reading 'members') discord.js v11

I want to connect to discord voice channel with discord.js as a user, and it works on some accounts but there is one account that shows this error:
TypeError: Cannot read properties of undefined (reading 'members')
While using discord.js v11.
Here is my code:
const Discord = require('discord.js');
const client = new Discord.Client();
const channelId = process.env.id
client.on("ready", () => {
let channel = client.channels.cache.get(channelId);
if(!channel) return console.log("Invalid channel id");
channel.join().then(connection => {
console.log("Successfully connected");
});
});
client.login(process.env.token);
(this is the code)
i am using discord.js v11.3.2
For one, member doesn't show up anywhere in this code snippet, and you will need to add some more code. I also noticed that at the 2nd line, channelId is spelt wrong, so that will cause an error. If you extend your code, I might be able to help. I am assuming that members is supposed to be member. So, try replacing members with member.

Slack bot ALWAYS gives missing_scope error

I'm new to Slack bots so I went through their documentation and followed some tutorials on the internet but nothing seems to help. I'm trying to add a simple bot to a workspace I've just created, all I want is to make the bot post a message once it starts. Here is my code:
const SlackBot = require('slackbots');
const botToken = 'xoxp-XXXXXXXXXXXXX-XXXXXXXXXXXX-XXXXXXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXX'
const bots = async () => {
const bot = await new SlackBot({
token: botToken,
name: 'orderbot'
});
console.log('adding event listener...');
await bot.on('start', () => {
console.log('posting message...');
bot.postMessage('general', 'Feeling hungry?');
});
};
bots();
And in the OAuth & Permissions page, I've added ALL permissions to the token's scopes. Running the bot, here is my output:
adding event listener...
/home/mohammed/OrderBot/node_modules/vow/lib/vow.js:105
throw e;
^
Error: missing_scope
at /home/mohammed/OrderBot/node_modules/slackbots/index.js:46:33
So apparently, the error is coming from the .on listener which is quite confusing and I can't understand why this is happening. What exactly am I missing?
It seems like the module slackbots which I was using is not working properly (at least for me). I solved this issue by using #slack/web-api instead.

When bot is restarted or turned on, do a specific function

I'm trying to make it so that when my bot gets a restart, in the ready.js file it will search for webhooks it made in all of the guilds the bot is in, the bot will then use that webhook and send messages through it. I wasn't able to get anywhere and this is in JS.
I've referred to the documentation for Discord.JS and really haven't gotten anywhere. I tried to get the client ID from webhook.owner and see if the bot's ID matches up with it. I am not sure how to extract the client ID from webhook.owner
guild.fetchWebhooks()
if(webhook.owner == `${bot.user.id}`);
(suggested)
guild.fetchWebhooks()
if(webhook.owner == `${bot.user.username}`);
(actual)
This is the only code I could come up with, can add full file if needed.
I expect a bot that when it restarts (bot.on) then it will search through all of the guilds it is in and find webhooks that it owns, and send messages through it without doing it to another active webhook.
What ends up happening is that my bot just sends out a mention of the bot.
Do something like this:
bot.on('ready', async () => { // on ready
await bot.guilds.forEach(async guild => { // in all guilds:
const webhooks = await guild.fetchWebhooks(); // check for Webhooks
await webhooks.forEach(async webhook => { // for all found Webhooks:
if (webhook.owner.id == bot.user.id) { // check if bot owns them
webhook.send('test'); // Do something with the Webhook example
}
});
});
});

Chaining with Telegram Bot API (like TriviaBot)

I am creating a TriviaBot style bot for telegram and am using Node.js to do so. At the moment I am having trouble capturing the users response to my quiz to determine whether the user got the question right or wrong. Below is some code:
bot.onText(/\/quiz/, function (msg) {
var chatId = msg.chat.id;
var text = quizdata.one.msgtxt;
var opts = {
reply_to_message_id: msg.message_id,
reply_markup: JSON.stringify({
keyboard: quizdata.one.keyboard,
one_time_keyboard: true
})
};
bot.sendMessage(chatId, text, opts);
//NEED TO CAPTURE THE USER RESPONSE AND REPLY TO THEIR MESSAGE ACCORDINGLY
});
NOTE : Telegram would cut of any asynchronous function, you should make separated module for listening any incoming interaction with button. You could use global Array for to store small data to be able getting returned for other module you need.
Putting all of your command in the index js not good idea tho.
if you want to listen the from keyboard callback_data. Just create a new line to listen any incoming clicked button.
bot.on("callback_query", (msg) => {
if (msg.data === "your_keyboard_callback_data") {
// do whatever you want
}
})
For more clearance node telegram api
Sorry if my answer is too late for this but hope mine can help other people 🙂

Resources