Reputation: 19
I've recently made a Discord bot using discord.js v12 and I haven't been able to set a presence for the bot.
This is the code:
client.user.setPresence({ game: { name: '.help' }, status: 'online' });
And the error is: TypeError: Cannot read property 'setPresence' of null
.
Upvotes: 1
Views: 24612
Reputation: 85
Try setting the presence in the client.on('ready', () => {})
section:
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
client.user.setPresence({
status: 'online',
activity: {
name: ".help",
type: "PLAYING"
}
});
});
Quick explanation:
The presence is what you are setting, it is made of multiple variables.
The status
can be online
, idle
, dnd
, or invisible
. (dnd is Do not disturb)
The other variable here is activity
. It is a group of two variables: name
and type
.
The name
is what the bot is doing. This is a string of your choice.
The type
is the other thing that will help it display as. It can be "PLAYING"
, "STREAMING"
, "WATCHING"
, "LISTENING"
, and "CUSTOM_STATUS"
.
Upvotes: 0
Reputation: 404
You can use the .setActivity()
function
client.user.setActivity(".help" {type: "PLAYING"}) //the type can be "PLAYING", "WATCHING", "STREAMING", "LISTENING"
Use this in your
client.on('ready' () => {
client.user.setActivity(".help" {type: "PLAYING"})
})
Upvotes: 0
Reputation: 1644
If you read the Client class docs here, you can see that the type of the user
property has type ?ClientUser
with ?
out the front - this means that it may not be defined (it's an optional value).
If you visit the ClientUser
documentation, it says it "Represents the logged in client's Discord user."
I'm guessing that if the client has not yet fully logged in, then the user
property will be undefined. Call client.login(token)
first, which is an asynchronous function, and then you can change the presence.
This means, using promises:
client.login(token).then((token) => {
// client.user is now defined
client.user.setPresence({
game: { name: '.help' },
status: 'online',
});
});
You may also want to query that client.user
is defined either way before proceeding to prevent crashing.
I suspect the reason your existing code does not work is because if you do not set the presence in the callback for the login function, you will not yet have finished logging in by the time the rest of the code runs. The following will cause an error:
client.login(token); // bad - this is async
client.user.setPresence(...)
Upvotes: 3
Reputation: 8412
This isn't quite an answer, but it's too big to go in a comment. If you want to set the status of the bot right when it goes online, you can define the presence through the Discord.Client()
constructer itself. One of the Client()
constructer's options is presence
.
// at the beginning of your code:
const client = new Discord.Client({
presence: {
status: 'online',
activity: {
name: '.help',
type: 'PLAYING',
},
},
});
Upvotes: 0