discordjs how to add all intents/permissions - node.js

I'm trying to add a role when members join the server, but it says I don't have that permission. How do I add all intents/permissions for the bot?
I'll just leave the beginning of the code.
// Require the necessary discord.js classes
const { Client, Intents, Message } = require('discord.js');
const { Player } = require("discord-player");
const { token, prefix } = require("./config.json");
// Create a new client instance
const client = new Client(
{
restTimeOffset: 0,
shards: "auto",
intents: [
Intents.FLAGS.DIRECT_MESSAGES,
Intents.FLAGS.DIRECT_MESSAGE_REACTIONS,
Intents.FLAGS.DIRECT_MESSAGE_TYPING,
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_BANS,
Intents.FLAGS.GUILD_EMOJIS_AND_STICKERS,
Intents.FLAGS.GUILD_INTEGRATIONS,
Intents.FLAGS.GUILD_INVITES,
Intents.FLAGS.GUILD_MEMBERS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
Intents.FLAGS.GUILD_MESSAGE_TYPING,
Intents.FLAGS.GUILD_PRESENCES,
Intents.FLAGS.GUILD_SCHEDULED_EVENTS,
Intents.FLAGS.GUILD_VOICE_STATES,
Intents.FLAGS.GUILD_WEBHOOKS,
]
});

The error could be coming because of other reasons as well. One explanation behind the error might be that the bot was trying to add a role to a member with a role higher than its own. In that case, you would have to manually rearrange the role hierarchy and put the bot's role on the top.
About the intents: It's not advisable to just add all the intents you want. The whole point of intents was that developers could choose what type of data they wanted their bot to receive. This whole concept is trashed if we just selected all the intents. If you still want to enable all the intents, you can just check for intents calculator in Google, and then copy the intent value given there and paste it like this:
const { Intents, Client } = require("discord.js")
const client = new Client({
intents: new Intents(value) // Insert the value here
})

Related

updated discord.js to version 14.6.0

and I've just updated to ver 14.6.0 of discord.js and non of my cmds are working why is that my code always worked before hand? example of my code here ->
if (message.content.startsWith('L!poke')) {
let targetMember = message.mentions.members.first();
if (!targetMember) return message.reply('you need to tag a user in order to poke them!!');
// message goes below!
const num = (Math.floor(Math.random()* 6)+1).toString();
message.channel.send({files: [`./poke/poke${num}.gif`]})
//message.channel.send({files:["./nom/"]})
message.channel.send(` ${targetMember.user},your you getting poked!!! -_-`);
//let embed = new Discord.RichEmbed()
//embed.setImage('https://cdn.discordapp.com/attachments/541152846540701706/653867448553963550/fm49srQ.gif')
//message.channel.send(embed);
You need additional intent flag in order to read content of the messages.
const { Client, GatewayIntentBits } = require("discord.js");
const client = new Client({
intents: [
// This will give you events about messages
GatewayIntentBits.GuildMessages,
// And this is flag you're probably missing:
GatewayIntentBits.MessageContent,
]
});
Also, don't forget that this intent should be enabled on Discord Developers Portal for your bot.

discord.js client.guilds.cache returns empty collection

Title basically says everything, when i do client.guilds.cache() it returns an empty collection. No idea what to do
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS,Intents.FLAGS.GUILD_MESSAGES,Intents.FLAGS.GUILD_MESSAGE_TYPING,Intents.FLAGS.DIRECT_MESSAGES,Intents.FLAGS.GUILD_MEMBERS] });
const guild = client.guilds.cache.find(g=>{g.id=="876857023256465468"})
console.log(client.guilds.cache)
I think its because of the intents, try using 32767 bitfield flag, 32767 stands for Intents.ALL therefore would provide all the intents that are available to the client

How to make a bot that sends message to discord channel when someone is entering and leaving a game using Rich Presence?

So I am a very beginner coder and I want to learn more, I searched for some time how to do this and didn't find so I need some help.
I just want to make a bot when someone opens a game for exemple osu!, the bot to send a message to a text channel saying "*Persons name * joined osu!", and when they leave to say "*Persons name * left osu!".
I did this but it doesn't work.
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('ConnectionLogs is online!');
});
client.on("presenceUpdate", (oldMember, newMember) => {
if(newMember.id === '406742915352756235') {
if(newMember.presence.game.name === 'osu!') {
console.log('osu! detected!');
client.channels.get('573671522116304901').send('**Joining Game:**', {
files: [
]
});
}
}
});
client.login('MY TOKEN')
Since you haven't mentioned it, I would suggest you haven't turned on the intents? Long story short - you don't get those events by default, as an effort to decrease traffic. You should go to your Discord Application (in developer portal) > Bot > enable the intents.
A bit more explanation can be found here: https://stackoverflow.com/a/64559391/2065080

Sending proactive messages to a channel in Teams

So,
I searched far and wide, read everything I could find on the topic and I am still failing at this. I have managed to send proactive message to user, reply to a topic in team, etc. but I am unable to send a proactive message (create new post) in a team channel.
Is there an available example (I was unable to find any)? MS Docs for NodeJS seem to show an example of messaging each user in the team, but not the channel itself.
I explored the source code, and channelData is hardcoded to null inside botFrameworkAdapter.js, which only adds to the confusion.
So, basic code is:
const builder = require('botbuilder');
const adapter = new builder.BotFrameworkAdapter({
appId: 'XXX',
appPassword: 'YYY'
});
const conversation = {
channelData: {
//I have all this (saved from event when bot joined the Team)
},
...
// WHAT THIS OBJECT NEEDS TO BE TO SEND A SIMPLE "HELLO" TO A CHANNEL?
// I have all the d
};
adapter.createConversation(conversation, async (turnContext) => {
turnContext.sendActivity('HELLO'); //This may or may not be needed?
});
Has anyone done this with Node ? If so, can anyone show me a working example (with properly constructed conversation object)?
* EDIT *
As Hilton suggested in the answer below, I tried using ConnectorClient directly, but it returns resource unavailable (/v3/conversations)
Here is the code that I am using (it's literally only that, just trying to send demo message):
const path = require('path');
const { ConnectorClient, MicrosoftAppCredentials } = require('botframework-connector');
const ENV_FILE = path.join(__dirname, '.env');
require('dotenv').config({ path: ENV_FILE });
const serviceUrl = 'https://smba.trafficmanager.net/emea/';
async function sendToChannel() {
MicrosoftAppCredentials.trustServiceUrl(serviceUrl);
var credentials = new MicrosoftAppCredentials(process.env.MicrosoftAppId, process.env.MicrosoftAppPassword);
var client = new ConnectorClient(credentials, { baseUri: serviceUrl });
var conversationResponse = await client.conversations.createConversation({
bot: {
id: process.env.MicrosoftAppId,
name: process.env.BotName
},
isGroup: true,
conversationType: "channel",
id: "19:XXX#thread.tacv2"
});
var acivityResponse = await client.conversations.sendToConversation(conversationResponse.id, {
type: 'message',
from: { id: process.env.MicrosoftAppId },
text: 'This a message from Bot Connector Client (NodeJS)'
});
}
sendToChannel();
What am I doing wrong?
Okay, so, this is how I made it work. I am posting it here for future reference.
DISCLAIMER: I still have no idea how to use it with botbuilder as was asked in my initial question, and this answer is going to use ConnectorClient, which is acceptable (for me, at least). Based on Hilton's directions and a GitHub issue that I saw earlier ( https://github.com/OfficeDev/BotBuilder-MicrosoftTeams/issues/162#issuecomment-434978847 ), I made it work finally. MS Documentation is not that helpful, since they always use context variable which is available when your Bot is responding to a message or activity, and they keep a record of these contexts internally while the Bot is running. However, if your Bot is restarted for some reason or you want to store your data in your database to be used later, this is the way to go.
So, the code (NodeJS):
const path = require('path');
const { ConnectorClient, MicrosoftAppCredentials } = require('botframework-connector');
const ENV_FILE = path.join(__dirname, '.env');
require('dotenv').config({ path: ENV_FILE });
const serviceUrl = 'https://smba.trafficmanager.net/emea/';
async function sendToChannel() {
MicrosoftAppCredentials.trustServiceUrl(serviceUrl);
var credentials = new MicrosoftAppCredentials(process.env.MicrosoftAppId, process.env.MicrosoftAppPassword);
var client = new ConnectorClient(credentials, { baseUri: serviceUrl });
var conversationResponse = await client.conversations.createConversation({
bot: {
id: process.env.MicrosoftAppId,
name: process.env.BotName
},
isGroup: true,
conversationType: "channel",
channelData: {
channel: { id: "19:XXX#thread.tacv2" }
},
activity: {
type: 'message',
text: 'This a message from Bot Connector Client (NodeJS)'
}
});
}
sendToChannel();
NOTE: As Hilton pointed out, serviceUrl also needs to be loaded from your database, along with the channel id. It is available inside the activity which you receive initially when your Bot is added to team / channel / group along with channelId which you will also need, and you need to store those for future reference (do not hardcode them like in the example).
So, there is no separate createConversation and sendActivity, it's all in one call.
Thanks Hilton for your time, and a blurred image of my hand to MS Docs :)
Hope this helps someone else
(I'm replacing my previous answer as I think this fits the situation much better).
I've looked more into this and done a Fiddler trace to get you a more complete answer. I'm not a Node guy, so I'm not sure this will translate 100%, but let's see.
Basically, you're wanting to send to the following endpoint:
https://smba.trafficmanager.net/emea/v3/conversations/19:[RestOfYourChannelId]/activities
and you'll be posting a message like the following:
{
"type": "message",
"from": {
"id": "28:[rest of bot user id]",
"name": "[bot name]"
},
"conversation": {
"isGroup": true,
"conversationType": "channel",
"id": "19:[RestOfYourChannelId]"
},
"text": "Test Message"
}
However, to post to that endpoint, you need to authenticate to it properly. It's possible to do that, and communicate with the endpoint directly, but it's actually easier to just use the built-in mechanisms. This means getting and storing the conversationreference when the bot is first installed to the channel. This file shows how to do that (see how it gets and stores the conversationReference in the this.onConversationUpdate function). In that same sample, in a different file, it shows how to use that conversation reference to actually send the pro-active message - see here, where it uses adapter.continueConversation.
One of the Microsoft bot team members also shows this in similar detail over here. He also adds MicrosoftAppCredentials.trustServiceUrl(ref.serviceUrl); which can be necessary under certain circumstances (if you're having security issues, give that a try).
That -should- cover what you need, so give it a go, and let me know if you're still having difficulties.

How to catch conversation ending event?

Using Microsoft BotBuilder, I want to catch event when user close or terminate a conversation with my bot. Here is the code of my bot:
const builder = require('botbuilder');
const connector = new builder.ChatConnector({
appId: process.env.MICROSOFT_APP_ID,
appPassword: process.env.MICROSOFT_APP_PASSWORD
});
const inMemoryStorage = new builder.MemoryBotStorage();
const bot = new builder.UniversalBot(connector).set('storage', inMemoryStorage);
initialize(bot);
function initialize(bot) {
bot.on('conversationUpdate', function(data) {
});
}
From the block of code above, I want to add an event that will handle ending conversation. Here is my example code:
function initialize(bot) {
bot.on('conversationEnd', function(data) {
var user = data.user,
address = data.address,
conversationId = data.address.conversation.id;
});
}
So, is there an event of conversationEnd like above code? I want to know if botBuilder can handle an ending conversation?
There is no event like converstaionEnd. Think of it in this way. If you are chatting with someone, you can just opt to not reply anymore. To a human user, it will seem that conversation has ended, but bot will not have any clue. It will keep on waiting. Unless you provide the intelligence to bot, to wait for a certain amount of time before considering that conversation has ended.
That said there are some other things you can handle:
You can handle conversationUpdate event. This event is triggered when any member joins/leaves a converstaion. Example
You can use a certain keyword (like goodbye, exit, etc.) as conversation ending keyword, which can trigger endConversationActionExample

Resources