I want my bot to post a simple welcome message in a 'welcome' text channel for every new member.
I've read a lot of posts here and there but still having trouble with making it work as intended
Here is the code:
console.log('Beep Boop Beep'); //prints 'Beep Boop Beep'
require('dotenv').config(); //load the dotenv node pachage and call a config() func to load thea values from .env
const {Client, MessageEmbed} = require('discord.js');
//EDIT: const client = new Client()
const client = new Client({ ws: { intents: [
'GUILDS',
'GUILD_MESSAGES',
'GUILD_PRESENCES',
'GUILD_MEMBERS'
] } });
const embed = new MessageEmbed()
.setTitle("DM thing")
.setColor(0xFF0000)
.setDescription("Add describtion here")
client.login(process.env.BOTTOKEN);
module.exports = {client, embed};
function readyDiscord() {
console.log('readyDiscord func executed. Discord is ready.');
}
client.on('ready', readyDiscord);
const commandHandler = require('./commands');
client.on('message', commandHandler);
//EDIT: 'guildMembersAdd'
client.on('guildMemberAdd', async member => {
console.log(member)
const message = `Hey, <#${member.id}>! Welcome. DM me if anytime you want.`
//EDIT: const channel = member.guild.channels.cache.get(WELCOME_CHANNEL_ID)
const channel = await
//EDIT: pocess.env
member.guild.channels.resolve(process.env.WELCOME_CHANNEL_ID);
channel.send(message)
})
PRESENCE INTENT and SERVER MEMBERS INTENT are enabled.
Each time i try to add a Test Account bot spits out those errors:
Errors:
(base) admin#MacBook-Pro-11 discord_binder % node bot.js
Beep Boop Beep
readyDiscord func executed. Discord is ready.
GuildMember {
guild: <ref *1> Guild {
members: GuildMemberManager {
cacheType: [class Collection extends Collection],
cache: [Collection [Map]],
guild: [Circular *1]
},
channels: GuildChannelManager {
cacheType: [class Collection extends Collection],
cache: [Collection [Map]],
guild: [Circular *1]
},
roles: RoleManager {
cacheType: [class Collection extends Collection],
cache: [Collection [Map]],
guild: [Circular *1]
},
presences: PresenceManager {
cacheType: [class Collection extends Collection],
cache: [Collection [Map]]
},
voiceStates: VoiceStateManager {
cacheType: [class Collection extends Collection],
cache: Collection(0) [Map] {},
guild: [Circular *1]
},
deleted: false,
available: true,
id: '779767191012638721',
shardID: 0,
name: 'testovoe_nazvaniye',
icon: '0b54ebc0b473b6571b8157d207392af0',
splash: null,
discoverySplash: null,
region: 'russia',
memberCount: 5,
large: false,
features: [],
applicationID: null,
afkTimeout: 300,
afkChannelID: null,
systemChannelID: '779768178296750080',
embedEnabled: undefined,
premiumTier: 0,
premiumSubscriptionCount: 0,
verificationLevel: 'NONE',
explicitContentFilter: 'DISABLED',
mfaLevel: 0,
joinedTimestamp: 1620485504837,
defaultMessageNotifications: 'ALL',
systemChannelFlags: SystemChannelFlags { bitfield: 0 },
maximumMembers: 100000,
maximumPresences: null,
approximateMemberCount: null,
approximatePresenceCount: null,
vanityURLCode: null,
vanityURLUses: null,
description: null,
banner: null,
rulesChannelID: null,
publicUpdatesChannelID: null,
preferredLocale: 'en-US',
ownerID: '660217837016842260',
emojis: GuildEmojiManager {
cacheType: [class Collection extends Collection],
cache: Collection(0) [Map] {},
guild: [Circular *1]
}
},
joinedTimestamp: 1620486298424,
lastMessageID: null,
lastMessageChannelID: null,
premiumSinceTimestamp: 0,
deleted: false,
nickname: null,
_roles: [],
user: User {
id: '462330953734291457',
system: null,
locale: null,
flags: UserFlags { bitfield: 0 },
username: 'Test Account',
bot: false,
discriminator: '4317',
avatar: '343601cdd6da4d03329351def9ffbffb',
lastMessageID: null,
lastMessageChannelID: null
}
}
(node:2459) UnhandledPromiseRejectionWarning: ReferenceError: pocess is not defined
at Client.<anonymous> (/Users/admin/Desktop/projects/re_bot/discord_binder/bot.js:43:57)
at Client.emit (events.js:315:20)
at Object.module.exports [as GUILD_MEMBER_ADD] (/Users/admin/Desktop/projects/re_bot/discord_binder/node_modules/discord.js/src/client/websocket/handlers/GUILD_MEMBER_ADD.js:16:14)
at WebSocketManager.handlePacket (/Users/admin/Desktop/projects/re_bot/discord_binder/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
at WebSocketShard.onPacket (/Users/admin/Desktop/projects/re_bot/discord_binder/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
at WebSocketShard.onMessage (/Users/admin/Desktop/projects/re_bot/discord_binder/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
at WebSocket.onMessage (/Users/admin/Desktop/projects/re_bot/discord_binder/node_modules/ws/lib/event-target.js:132:16)
at WebSocket.emit (events.js:315:20)
at Receiver.receiverOnMessage (/Users/admin/Desktop/projects/re_bot/discord_binder/node_modules/ws/lib/websocket.js:825:20)
at Receiver.emit (events.js:315:20)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:2459) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:2459) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
EDIT:
The overall idea of code was right, but there were lots of typos which you see as //EDIT: comments. So maybe you want to go and check your code for same typos
Could you let us know what is being logged to the console from the console.log(member)?
My best bet would be that the WELCOME_CHANNEL_ID is wrong and thus returning a bogus channel.
If that is not the case, then maybe the bot is not caching the channels, so use this:
const channel = await member.guild.channels.resolve(WELCOME_CHANNEL_ID);
Let us know if it doesn't work.
Just enabling Intents in Developer Portal dosen't mean you're using Intents
You'll have to tell your client which intents to use.
So, Instead of
const client = new Client();
You need to do
const client = new Client({ ws: { intents: [
'GUILDS',
'GUILD_MESSAGES',
'GUILD_PRESENCES',
'GUILD_MEMBERS'
] } });
This will tell the client to load the GUILD_MEMBERS Intent so that you can use guildMemberAdd
This code should work after that. Comment if any error.
Edit: In your code you've misspelled guildMemberAdd for guildMembersAdd You should also fix that.
Resource:
How to use intents
Official Docs
I see you have a comment in your code saying that WELCOME_CNAHHEL_ID is an environment variable. Just like what you did with BOTTOKEN, you might want to prefix the variable with process.env, so it should look like this:
process.env.WELCOME_CHANNEL_ID
You also have a typo in your original code: CNAHHEL instead of CHANNEL. Make sure the name on the .env file and the name you use in your code match.
Related
I have looked far and wide for answers to my question and have yet to find anything that helped me, I try to push my slash commands globally and they do not work as in discord shoots back with this when I execute the code:
Started refreshing 13 application (/) commands.
DiscordAPIError[50035]: Invalid Form Body
0.name[BASE_TYPE_REQUIRED]: This field is required
1.name[BASE_TYPE_REQUIRED]: This field is required
2.name[BASE_TYPE_REQUIRED]: This field is required
3.name[BASE_TYPE_REQUIRED]: This field is required
4.name[BASE_TYPE_REQUIRED]: This field is required
5.name[BASE_TYPE_REQUIRED]: This field is required
6.name[BASE_TYPE_REQUIRED]: This field is required
7.name[BASE_TYPE_REQUIRED]: This field is required
8.name[BASE_TYPE_REQUIRED]: This field is required
9.name[BASE_TYPE_REQUIRED]: This field is required
10.name[BASE_TYPE_REQUIRED]: This field is required
11.name[BASE_TYPE_REQUIRED]: This field is required
12.name[BASE_TYPE_REQUIRED]: This field is required
at SequentialHandler.runRequest (/home/ayden/microwave.js/node_modules/#discordjs/rest/dist/index.js:753:15)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async SequentialHandler.queueRequest (/home/ayden/microwave.js/node_modules/#discordjs/rest/dist/index.js:565:14)
at async REST.request (/home/ayden/microwave.js/node_modules/#discordjs/rest/dist/index.js:999:22)
at async /home/ayden/microwave.js/deploy.js:25:16 {
rawError: {
code: 50035,
errors: {
'0': [Object],
'1': [Object],
'2': [Object],
'3': [Object],
'4': [Object],
'5': [Object],
'6': [Object],
'7': [Object],
'8': [Object],
'9': [Object],
'10': [Object],
'11': [Object],
'12': [Object]
},
message: 'Invalid Form Body'
},
code: 50035,
status: 400,
method: 'PUT',
url: 'https://discord.com/api/v10/applications/867964961417203743/commands',
requestBody: {
files: undefined,
json: [
undefined, undefined,
undefined, undefined,
undefined, undefined,
undefined, undefined,
undefined, undefined,
undefined, undefined,
undefined
]
}
}
Here is the code from the deploy.js file:
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v10');
const { clientId, guildId, token } = require('./config.json');
const fs = require('node:fs');
const commands = [];
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.ts'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(JSON.stringify(command.data));
}
const rest = new REST({ version: '10' }).setToken(token);
(async () => {
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
const data = await rest.put(
Routes.applicationCommands(clientId),
{ body: commands },
);
console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) {
console.error(error);
}
})();
If you could help me solve this that would be much appreciated!
The problem is that you are trying to push command.data to the commands array.
Looking at one of your command files, I noticed that that property doesn’t exist. Instead, the Slash Command Builder is located at <command>.help.data (e. g. in your about.js, you are using:
module.exports.help = {
name: "about",
cat: "Info",
description: "Get information about the bot",
aliases: "",
data: new SlashCommandBuilder().setName("about").setDescription("Get information about the bot"),
}
This module.exports points to the export property .help and has the property .data which contains the SlashCommandBuilder.
To solve this issue, just change the deploy.js line 11 to the following:
commands.push(JSON.stringify(command.help.data));
This points to the correct location of the SlashCommandBuilder - preventing the array to just be filled with undefined because the property given doesn’t exist.
I hope this helps in resolving the problem.
I am creating a database with MongoDB and using the Mongoose ODM. I'm using Node.js. I ran the code without the last block several times and it was fine, but when I wrote the last block in order to use the .find() method, it threw me an odd error.
This is the app.js file:
//require mongoose
const mongoose = require('mongoose');
//connect to mongoDB database
mongoose.connect('mongodb://localhost:27017/albumDB', {useNewUrlParser: true, useUnifiedTopology: true});
//CREATE
//create schema (blueprint/structure)
//of data that we save to the database
const albumSchema = new mongoose.Schema ({
name: String, //the DB has a variable called name with a value of String
author: String,
year: Number,
genre: String,
listened: Boolean,
liked: Boolean
});
//creating the model. parameters: object of collection, schema
const Album = mongoose.model('Album', albumSchema);
//creating the album document
const album = new Album({
name: 'Insurgentes',
author: 'Steven Wilson',
year: 2008,
genre: 'Prog rock',
listened: 1,
liked: 1
});
//save album inside Album inside albumDB
//album.save().then(() => console.log('meow'));
const personSchema = new mongoose.Schema ({
name: String,
age: Number
});
const Person = mongoose.model('Person', personSchema);
const person = new Person({
name: "John",
age: 37
});
//person.save();
const SiameseDream = new Album({
name: 'Siamese Dream',
author: 'The Smashing Pumpkins',
year: 1993,
genre: 'Alt rock, Grunge',
listened: 1,
liked: 1
});
const MellonCollie = new Album({
name: 'Mellon Collie and the Infinite Sadness',
author: 'The Smashing Pumpkins',
year: 1995,
genre: 'Alt rock, Dream pop',
listened: 1,
liked: 1
});
const Adore = new Album({
name: 'Adore',
author: 'The Smashing Pumpkins',
year: 1998,
genre: 'Alt rock, Art rock',
listened: 1,
liked: 1
});
//READ
Album.find(function (err, albums){ //1. error 2.what it finds back
if (err) {
console.log(err);
} else {
console.log(albums);
}
});
This is the error that shows up on my terminal, related to the last block of code:
$ node app.js
TypeError: cursor.toArray is not a function
at model.Query.<anonymous> (C:\Users\user\Desktop\Music\node_modules\mongoose\lib\query.js:2151:19)
at model.Query._wrappedThunk [as _find] (C:\Users\user\Desktop\Music\node_modules\mongoose\lib\helpers\query\wrapThunk.js:27:8)
at C:\Users\user\Desktop\Music\node_modules\kareem\index.js:370:33
at processTicksAndRejections (internal/process/task_queues.js:75:11)
(node:11536) UnhandledPromiseRejectionWarning: MongoInvalidArgumentError: Method "collection.find()" accepts at most two arguments
at Collection.find (C:\Users\user\Desktop\Music\node_modules\mongodb\lib\collection.js:238:19)
at NativeCollection.<computed> [as find] (C:\Users\user\Desktop\Music\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:191:33)
at NativeCollection.Collection.doQueue (C:\Users\user\Desktop\Music\node_modules\mongoose\lib\collection.js:135:23)
at C:\Users\user\Desktop\Music\node_modules\mongoose\lib\collection.js:82:24
at processTicksAndRejections (internal/process/task_queues.js:75:11)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:11536) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)(node:11536) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
This issue is facing mongoose version 6.0 So you just have to downgrade the mongoose version. Just run npm uninstall mongoose to uninstall the current mongoose version then run npm i mongoose#5.13.8, this will install the version that will fix your problem. Just check this link https://www.zhishibo.com/articles/132795.html
Mongoose has just updated and in 6+ version
we have to pass the object as first parameter followed by call back function with params of error and result of query!!
To GET ALL records just pass the empty object.
Album.find({}, function (err, result){ // get all albums
if (err) { // if there will be any error
console.log(err);
} else { /// in success case in which records from DB is fetched
console.log(result);
}
});
https://mongoosejs.com/docs/api.html#model_Model.find
Updating to mongoose#6.0.1 fixed the issue for me.
npm run update --save will update all your dependencies including mongoose
I have an url adress. When I go that adress in browser it shows a json file. I need to get that json file in NodeJs.
How can I do that?
Edit: This is my current code:
const got = require('got');
var url = "https://www.instagram.com/p/CFcyO54Hc7k/?__a=1";
got(url).json().then(result => {
console.log(result);
}).catch(err => {
console.log(err);
});
And This is the result I get:
Promise { <pending> }
Hint: hit control+c anytime to enter REPL.
RequestError: Unexpected token < in JSON at position 0 in "https://www.instagram.com/accounts/login/?next=/p/CFcyO54Hc7k/%3F__a%3D1"
at Object.parseBody [as default] (/home/runner/VengefulUltimateSdk/node_modules/got/dist/source/as-promise/parse-body.js:22:15)
at /home/runner/VengefulUltimateSdk/node_modules/got/dist/source/as-promise/index.js:157:40
at JSON.parse (<anonymous>)
at parseJson (/home/runner/VengefulUltimateSdk/node_modules/got/dist/source/index.js:118:35)
at Object.parseBody [as default] (/home/runner/VengefulUltimateSdk/node_modules/got/dist/source/as-promise/parse-body.js:11:48)
at /home/runner/VengefulUltimateSdk/node_modules/got/dist/source/as-promise/index.js:157:40
at processTicksAndRejections (internal/process/task_queues.js:97:5) {
name: 'ParseError',
code: undefined,
timings: {
start: 1601274389096,
socket: 1601274389096,
lookup: 1601274389106,
connect: 1601274389117,
secureConnect: 1601274389128,
upload: 1601274389128,
response: 1601274389467,
end: 1601274389511,
error: undefined,
abort: undefined,
phases: {
wait: 0,
dns: 10,
tcp: 11,
tls: 11,
request: 0,
firstByte: 339,
download: 44,
total: 415
}
}
}
My node version is 12.16.1
If you want to get it as json you can use the fetch api (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) then in the promises you can read the json as an object in your js code.
fetch('http://server/file.json').then(resp=>resp.json()).then(data=>{do something with data});
You can use axios in NodeJS.
axios.get('https://someapiendpoint.domain.com/v1/api')
.then((response) => {
console.log(response.data);
});
You can either parse the JSON yourself or you can get a library for making an Http request that parses the JSON automatically for you. There are lots of libraries to choose from here. My favorite is got() and it will let you parse the JSON with a simple .json() added to it so the resolved value you get back is a Javascript object.
const got = require('got');
got("https://www.instagram.com/p/CFcyO54Hc7k/?__a=1").json().then(result => {
console.log(result);
}).catch(err => {
console.log(err);
});
When I run the above code with your instagram URL, I get this Javascript object back:
{
graphql: {
shortcode_media: {
__typename: 'GraphSidecar',
id: '2404017227651993316',
shortcode: 'CFcyO54Hc7k',
dimensions: [Object],
gating_info: null,
fact_check_overall_rating: null,
fact_check_information: null,
sensitivity_friction_info: null,
media_overlay_info: null,
media_preview: null,
display_url: 'https://scontent-sjc3-1.cdninstagram.com/v/t51.2885-15/e35/119980944_890957481429986_8757958615208227911_n.jpg?_nc_ht=scontent-sjc3-1.cdninstagram.com&_nc_cat=102&_nc_ohc=w7zBW_FdRNgAX9BYknl&_nc_tp=18&oh=11424efc118b55180e4d3302d75181ca&oe=5F99EB23',
display_resources: [Array],
is_video: false,
tracking_token: 'eyJ2ZXJzaW9uIjo1LCJwYXlsb2FkIjp7ImlzX2FuYWx5dGljc190cmFja2VkIjp0cnVlLCJ1dWlkIjoiZGIyMzdkMzgzYWVhNDY5YmI0ZWVkZWI4YzlhZDY0YWUyNDA0MDE3MjI3NjUxOTkzMzE2In0sInNpZ25hdHVyZSI6IiJ9',
edge_media_to_tagged_user: [Object],
edge_media_to_caption: [Object],
caption_is_edited: false,
has_ranked_comments: false,
edge_media_to_parent_comment: [Object],
edge_media_to_hoisted_comment: [Object],
edge_media_preview_comment: [Object],
comments_disabled: false,
commenting_disabled_for_viewer: false,
taken_at_timestamp: 1600801207,
edge_media_preview_like: [Object],
edge_media_to_sponsor_user: [Object],
location: null,
viewer_has_liked: false,
viewer_has_saved: false,
viewer_has_saved_to_collection: false,
viewer_in_photo_of_you: false,
viewer_can_reshare: true,
owner: [Object],
is_ad: false,
edge_web_media_to_related_media: [Object],
edge_sidecar_to_children: [Object],
edge_related_profiles: [Object]
}
}
}
If you'd rather modify your existing code, then you will probably need to use JSON.parse(). You will have to add your existing code to your question for us to help with that.
Given: Express app, AVA, supertest
When: I test generated html in response and the test case fails
Then: AVA displays the whole response object in the console which slows down analysis of the issue
Example of the test:
test('Positive case: book is found in /api/v1/books/1', async (t) => {
t.plan(2)
const response = await request(app).get('/api/v1/books/1')
t.is(response.status, 200)
const expectedBook = '<h3>Book 1</h3>'
t.truthy(response.res.text.match(expectedBook), 'Book title is not found')
})
Example of the output in the console
/express-project/src/books/index.test.js:22
21: const text = response.res.text
22: t.truthy(response.res.text.match(expectedBook), 'Book t…
23: })
Book title is not found
Value is not truthy:
null
response.res.text.match(expectedBook)
=> null
expectedBook
=> '<h3>Book 2</h3>'
response.res.text
=> '<!DOCTYPE html><html><head><title>BOOK</title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>BOOK</h1>
<h3>Book 1</h3><h4></h4></body></html>'
response.res
=> IncomingMessage {
_consuming: false,
_dumped: false,
_events: {
close: Function bound emit {},
data: [
Function {},
Function {},
Function bound emit {},
],
end: [
Function responseOnEnd {},
Function {},
Function bound emit {},
],
error: [
Function bound onceWrapper { … },
Function bound emit {},
],
},
_eventsCount: 4,
_maxListeners: undefined,
_readableState: ReadableState [
awaitDrain: 0,
.......... VERY LONG LIST WITH HUNDREDS OF LINES
SO HAVE TO SCROLL UP AND UP AND UP BEFORE YOU GET TO THE POINT
Ava is trying to be helpful in debugging the failed test so Ava puts in the console respectively
response.res.text
response.res
response
and it generates hundreds of even thousands of lines in the console
So the solution is pretty simple - use an intermediate variable for the assertion
Instead of
t.truthy(response.res.text.match(expectedBook), 'Book title is not found')
use
const text = response.res.text
t.truthy(text.match(expectedBook), 'Book title is not found')
I'm using the selenium-webdriver npm module for Node.JS, however I am having trouble writing the cookies to the console. I used the example code from the NPM page (Under usage)
var webdriver = require('selenium-webdriver'),
By = webdriver.By,
until = webdriver.until;
var driver = new webdriver.Builder()
.forBrowser('firefox')
.build();
driver.get('http://www.google.com/ncr');
driver.findElement(By.name('q')).sendKeys('webdriver');
driver.findElement(By.name('btnG')).click();
driver.wait(until.titleIs('webdriver - Google Search'), 1000);
console.log(driver.manage().getCookies());
driver.quit();
Now, I would expect console.log to write the dictionary I've seen referenced in other questions, however I get the following output:
ManagedPromise {
flow_:
ControlFlow {
propagateUnhandledRejections_: true,
activeQueue_:
TaskQueue {
name_: 'TaskQueue::5',
flow_: [Circular],
tasks_: [Object],
interrupts_: null,
pending_: null,
state_: 'new',
unhandledRejections_: Set {} },
taskQueues_: Set { [Object] },
shutdownTask_: null,
hold_:
Timeout {
_called: false,
_idleTimeout: 2147483647,
_idlePrev: [Object],
_idleNext: [Object],
_idleStart: 231,
_onTimeout: [Function: wrapper],
_repeat: [Function] } },
stack_: { [Task: WebDriver.manage().getCookies()] name: 'Task' },
parent_: null,
callbacks_: null,
state_: 'pending',
handled_: false,
value_: undefined,
queue_: null }
I get no errors in my console, but I'm not getting the cookies I expected either. I'm using the latest version of node, v5.9.1, and the latest version of selenium-webdriver. For some reason the console.log code is called before selenium's instance of Firefox even starts. How would I go about fixing this?
You can use .then(). Refer to When should we use .then with Protractor Promise? for more information.
driver.manage().getCookies().then(function (cookies) {
console.log(cookies);
});