Discord.js setGame() not working anymore - javascript

I have been coding my Discord bot using Discord.JS for about 2 months now and I've just recently noticed that my bot isn't saying that it's playing what I'm telling it. When I first coded the bot up until recently it worked just fine. Now the 3 discord bots I have aren't showing their games.
This is the code I'm using:
const Discord = require("discord.js");
const bot = new Discord.Client();
bot.on("ready", () => {
console.log("Ready");
bot.user.setGame("Type !help");
}

.setGame() is deprecated now but you could use .setPresence() or you could use the .setActivity() which is the same thing and format as the .setGame().
Ex.
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.user.setActivity('YouTube', { type: 'WATCHING' });
Here is a link to the documentation in case you wanted to change 'Watching' to something else like 'Playing'.

setGame() is now deprecated, and discord.js asks you to use setActivity().
const Discord = require("discord.js");
const bot = new Discord.Client();
bot.on("ready", () => {
console.log("Ready");
bot.user.setActivity("Type !help");
})
Hope this helped.

The setGame() Method has stopped working, here's what you can do:
update to latest 11.1-dev or
use .setPresence({ game: { name: 'nameGoesHere', type: 0 } }); as a workaround instead
Source: https://github.com/hydrabolt/discord.js/issues/1807#issuecomment-323578919

Here's a short example of using the .setPresence that LW001 linked to:
var Discord = require('discord.js');
var bot = new Discord.Client();
bot.on('ready', () => {
bot.user.setStatus('available') // Can be 'available', 'idle', 'dnd', or 'invisible'
bot.user.setPresence({
game: {
name: 'Type !help',
type: 0
}
});
});
https://discord.js.org/#/docs/main/stable/class/ClientUser?scrollTo=setGame

setgame is depreciated use setActivity instead
example:
client.user.setActivity('activity here')
Or:
client.user.setActivity('activity here', {type: "WATCHING"})
type can be WATCHING, LISTENING, PLAYING or STREAMING
if streaming you need to add this below the setActivity code
url: "twitch.tv/urtwitchusername",

Related

Cannot read properties of undefined (reading 'join') Discord.js

im trying to create my discord music bot, but when i run it. It cannot join my voiceChannel, returning this error: channel_info.channelId.join is not a function. Below, my code:
const Discord = require('discord.js');
const bot = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
const ytdl = require('ytdl-core');
const streamOptions = { seek: 0, volume: 1 };
const botToken = 'mytoken';
bot.login(botToken);
bot.on('ready', () => {
console.log('to olain');
});
bot.on('message', msg => {
if (msg.author.bot) {
return;
}
if (msg.content.toLowerCase().startsWith(';p')) {
const channel_info = msg.member.guild.voiceStates.cache.find(user => user.id == msg.author.id);
if (channel_info.channelId == null) {
return console.log('Canal não encontrado!');
}
console.log('Canal encontrado');
channel_info.channelId.join().then(connection => {
const stream = ytdl('https://www.youtube.com/watch?v=BxmMGnvvDCo', { filter: 'audioonly' });
const DJ = connection.playStream(stream, streamOptions);
DJ.on('end', end => {
channel_info.channelId.leave();
});
})
.catch(console.error);
}
});
There are several issues in this code. Even if we fix some of these issues, this code will still not work due to differences between discord.js v12 and v13. Let's get started.
Issue #1
This is not one of the core issues causing your code to not work, but it's something useful to consider. You are doing this to get the voice state of the message author:
msg.member.guild.voiceStates.cache.find(user => user.id == msg.author.id);
When you could easily do the exact same thing in a much shorter, less-likely-to-produce-errors way:
msg.member.voice;
Issue #2
Now this is a core issue causing your code to not work. In fact, it is causing the error in your question. You are trying to do:
channel_info.channelId.join();
That does not make sense. You are trying to join a channel ID? channelId is just a String of numbers like so: "719051328038633544". You can't "join" that String of numbers. You want to join the actual channel that the member is in, like so:
channel_info.channel.join();
Issue #3
Based on how you are using a channelId property instead of channelID, I assume you are on discord.js v13. Voice channels do not have a .join() method on v13; in fact, discord.js v13 has no support for joining or playing audio in voice channels. You must install the discord.js/voice package in order to join a voice channel in discord.js v13. This is critical. Even if you fix the above two issues, you must solve this third issue or your code will not work (unless you downgrade to discord.js v12).

Send message to specific discord channel in discord.js v12

Every line of code i try to use to send a message to a specific channel doesn't seem to work in discord.js v12 even when i got that code from the official documentation. Here is my code:
const Discord = require('discord.js');
const client = new Discord.Client();
const announcementChannel = client.channels.cache.get(process.env.CHANNELANN);
let announcement = "MESSAGE HERE";
client.on("presenceUpdate", (oldPresence, newPresence) => {
if (!newPresence.activities) return false;
newPresence.activities.forEach(activity => {
if (activity.type == "STREAMING") {
if(newPresence.user.id == "THE ID IS HERE") {
announcementChannel.send(announcement);
}
} else {
client.user.setActivity("over the server", {
type: "WATCHING"
});
};
});
});
client.login(process.env.TOKEN);
Here is the error i receive:
announcementChannel.send(announcement);
^
TypeError: Cannot read property 'send' of undefined
I was able to fix this by replacing that line with:
client.channels.cache.get(process.env.CHANNELANN).send(announcement);
However, now it just keeps spamming the message and doesn't only send it once then stops. You know any fix for that?
Once initiated, make it wait until the stop streaming
None of the answers I found worked with the latest version (12.5.1) so here's what worked for me.
const channel = client.channels.cache.get(textChannelId) as TextChannel;
if (channel) {
const m = new Message(client, {id: clientId}, channel);
const content: MessageOptions = {content: message};
//if (image) {
// content.embed = {image: {url: image}};
//}
await m.channel.send(content);
}

Cannot get bot to autoban new accounts on Discord

The bot is very simple and will ultimately not require any input from me. What I want the bot to do is to check the age of an account that joins and then ban them if they are a new account made within the past 10 minutes. The part that I'm stuck on is calculating the time I think. The bot isn't giving any errors, it's just not banning the new account that I made. For testing purpose, I put the bot onto a new server I"m making that doesn't have anyone else on it and also changed the amount of time to 14400 seconds so that it's within 10 days and should give me enough time to figure out what's wrong.
Here's my code as it stands:
const Discord = require("discord.js");
const client = new Discord.Client();
client.on("ready", () => {
console.log("I am ready!");
});
client.on("message", (message) => {
if (message.content.startsWith("ping")) {
message.channel.send("pong!");
}
});
client.on("guildMemberAdd", (member) => {
if (Date.now() - member.user.createdAt <= 14400) {
guildMember.ban({ days: 14, reason: 'New account' })
}
});
client.login("Token");
member.client.user.createdAt is the section that I think I'm having a problem with. When I run a debug on Date.now() that works fine but I can't seem to get it to calculate the age of an account that joins.
I'm pretty sure that this is the property I need but I must be calling it incorrectly. Please forgive any ignorance, I'm super new to js.
https://discord.js.org/#/docs/main/master/class/User?scrollTo=createdAt
I would love to know what I'm doing wrong. Thanks!
Finally figured out the problem. The issue is actually multi-part here. The first issue is that I thought it was calculating in seconds, but instead it's actually calculating in milliseconds so the if statement was never true. Once I made that true by increasing the time to 10 days in milliseconds, I got an error on the guildMember since it wasn't defined. I changed that to member and then got an error on the days that it can't be more than 7. Here's the final working code.
const Discord = require("discord.js");
const client = new Discord.Client();
client.on("ready", () => {
console.log("I am ready!");
});
client.on("message", (message) => {
if (message.content.startsWith("ping")) {
message.channel.send("pong!");
}
});
client.on("guildMemberAdd", (member) => {
if (Date.now() - member.user.createdAt <= 864000000) {
member.ban({ days: 7, reason: 'New account' })
}
});
client.login("Token");
You need to put the "async" for it to work
const Discord = require("discord.js");
const client = new Discord.Client();
client.on("ready", () => {
console.log("I am ready!");
});
client.on("message", (message) => {
if (message.content.startsWith("ping")) {
message.channel.send("pong!");
}
});
client.on("guildMemberAdd", async member => {
if (Date.now() - member.user.createdAt <= 1209600000) {
member.ban({ days: 14, reason: 'New account' })
}
});
client.login("Token");

Discord JS (Bot Presence)

So, in Discord, users can have a custom status, however, when I try to set my bot up with one nothing happens...Even though CUSTOM_STATUS is available
I have bot.user.setPresence({ activity: { name: "Testing", type: "CUSTOM_STATUS" }, status: "online" });
inside of the ready event. I was just wondering why this doesn't work and if there is a work around
According to the docs.
Bots cannot set a CUSTOM_STATUS, it is only for custom statuses received from users
The valid types you could choose from are:
PLAYING
STREAMING
LISTENING
WATCHING
Try client.user.setActivity(Your Status)
I am using this and its working fine
If you are using v12 then i cant help you
You should make sure that your setPresence command is in your ready event. For example, this is my ready command:
const {PREFIX} = require('../config.json');
const { Message } = require('discord.js');
const message = require('./message.js');
//must update when new module.exports event happens
const leaveEvent = require('../util/guildMemberRemove');
const invitecounterEvent = require('../util/guildMemberAddinvitecounter');
const modmailEvent = require('../util/modmail');
module.exports = (client, message) => {
//must update when new module.exports event happens
leaveEvent(client);
invitecounterEvent(client);
modmailEvent(client);
console.log(' ');
console.log(`Hi, ${client.user.username} is now online! My Prefix is ${PREFIX}`);
console.log(`Bot has started, with ${client.users.size} users, in ${client.channels.size} channels of ${client.guilds.size} guilds.`);
//client.user.setActivity(`Serving ${client.guilds.size} servers`); (big servers only)
client.user.setActivity('U', { type: 'WATCHING' }) //PLAYING, STREAMING, LISTENING, WATCHING, CUSTOM_STATUS
.then(presence => console.log(`Activity set to: WATCHING ${presence.activities[0].name}`))
.catch(console.error);
console.log(`Ready as ${client.user.tag} to serve in ${client.channels.cache.size} channels on ${client.guilds.cache.size} servers, for a total of ${client.users.cache.size} users.`);
client.generateInvite(['SEND_MESSAGES', 'MANAGE_GUILD', 'MENTION_EVERYONE', 'ADMINISTRATOR',])
.then(link => {
console.log(`Generated bot invite link: ${link}`);
// eslint-disable-next-line no-undef
inviteLink = link;
});
};
The part that should help you is client.user.setActivity('U', { type: 'WATCHING' })
The different types you can do are PLAYING, STREAMING, LISTENING, and WATCHING.

discord.js client.user.setPresence() breaks bot

My bot currently runs fine. I decided to add a 'playing ' status to it. This is the relevant code:
// Import the discord.js modules required
const Discord = require('discord.js');
// Create an instance of a Discord client
const client = new Discord.Client();
// Load config properties from 'config.json'
const config = require("./config.json");
const contest = config.contest;
// Set bots status to playing 'contest' defined in 'config.json'
client.user.setPresence({
game:{
name:contest
},
status:'online'
});
In 'config.json':
{
"contest": "Example Game"
}
When I add this, the bot no longer works, and appears offline. Any ideas?
EDIT:
Source of the information:
https://discord.js.org/#/docs/main/stable/class/ClientUser?scrollTo=setPresence
In the example section:
// Set the client user's presence
client.user.setPresence({ game: { name: 'with discord.js' }, status: 'idle' })
.then(console.log)
.catch(console.error);
You need to read the config, instead of
const config = require(...)
You need
const fs = require("fs");
const config = JSON.parse(fs.readFileSync("config.json"));
const contest = config.contest;
Then
game:{
name:contest
}
Figured it out - this needs to be placed inside an event, otherwise it's just floating code. For example, I placed this inside a
client.on('ready) event.

Categories

Resources