I'm creating a discord bot, and I am trying to make it so that it would greet everyone when it turns on. I have been using bot.channels.get to find the channel and so far that part of the code works fine. It stops working when it tries to send a message.
I have tried all combinations of bot.channels.get and bot.channels.find, together with generalChannel.send and generalChannel.sendMessage, but to still no avail.
const Discord = require('discord.js');
const fs = require('fs');
const bot = new Discord.Client();
let rawVariables = fs.readFileSync('variables.json');
let variables = JSON.parse(rawVariables);
var generalChannel;
bot.on('ready', () => {
generalChannel = bot.channels.get(variables.Channels.general);
generalChannel.send("Helllo!");
});
bot.login(variables.BotToken);
I just need it to message the channel when it starts up.
variables.Channels.general should be a string of the id of your channel
you can get the id by rightclicking on a channel -> copy id
it should look something like this:
'408632672669273'
Related
So basically I'm trying to create a Discord bot that when you type "!cat" the Discord bot sends an image of a random cat inside of an embed but every time I use the command the image stays the same.... I tried to put the embed variable inside of the function so it refreshes every time someone says "!cat" but it didn't work..... this is the code that I'm using:
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', message => {
console.log(message.content);
if (message.content === "!cat") {
const catEmbed = new Discord.MessageEmbed()
.setTitle("MEOW!")
.setImage("http://theoldreader.com/kittens/600/400")
.setThumbnail("http://theoldreader.com/kittens/600/400")
message.channel.send(catEmbed)
}
});
client.login('NOT GONNA TELL MY TOKEN');
It looks like a caching issue. Try to append some random character as a query string to your URL. Something like this should work:
client.on('message', (message) => {
if (message.content === '!cat') {
// generate a random string
const rand = Math.random().toString(36).slice(2);
const catEmbed = new Discord.MessageEmbed()
.setTitle('MEOW!')
// append it as a query string
.setImage(`http://theoldreader.com/kittens/600/400?${rand}`)
.setThumbnail(`http://theoldreader.com/kittens/600/400?${rand}`);
message.channel.send(catEmbed);
}
});
I signed up just a few moments ago because something was really bothering me:
I have the following code:
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('guildMemberAdd', (member) => {
console.log('New member.')
const welcomeEmbed = new Discord.MessageEmbed()
.setImage(member.user.avatarURL())
.setColor('#e9fa2a')
.setAuthor("Mangoly Assistant")
.setTitle("New member in server")
.setDescription('Welcome <#${member.id}> to the server! If you are new, please be sure to check out or rules channel and some useful links. We are glad to be having you here, everyone wave hello! :wave:')
.setFooter('Created by kostis;#4464. || Mangoly Assistant')
client.channels.cache.get('825130442197434418').send(welcomeEmbed)
});
client.once('ready', () => {
console.log('Bot is ready')
})
client.login(nice try);
For some reason, when I leave and rejoin the server, the embed isn't sending at all to the channel. I am getting no errors in the console. Any ideas on what may have gone wrong? Thanks. :)
You need 'Server Members Intent' enabled when you invite the bot. Go to Discord Developer Portal > Bot > Scroll to bottom > make sure server members intent is checked
You should also be able to enable it manually in your code, but idrk how to do it. I think it’s like this:
//Client declaration
const client = new Discord.Client({
ws: {
intents: ['GUILD_MEMBERS']
}
})
Also, quick thing: to use ${variableHere} in a string, it must be a string with backticks ( ` ), like this:
var a = 'abc';
var b = '${a}d' //returns ${a}d
var c = `${a}d` //returns abcs
Attempting to implement texas hold em poker in discord with a bot using node js.
Currently have a problem try to nest
client.on('message', message => {
calls. The idea behind these is that the first one looks for the !poker command, and subsequent ones listen for joining players, player bets etc.
code:
const Discord = require('discord.js');
const dotenv = require('dotenv').config();
const Game = require("./classes.js").Game
const Player = require("./classes.js").Player
// create a new Discord client
const client = new Discord.Client();
// when the client is ready, run this code
// this event will only trigger one time after logging in
client.once('ready', () => {
console.log('Ready!');
});
let prefix = '!';
client.on('message', message => {
//prevent feedback loops
if (!message.content.startsWith(prefix) || message.author.bot) return;
if (message.content.startsWith(`${prefix}poker`)){
//getting args
const args = message.content.slice(prefix.length).trim().split(' ');
const command = args.shift().toLowerCase();
//converting to relevant data type
let no_players = parseInt(args[0]);
let money = parseInt(args[1])
//initialising game object and card deck
let game = new Game();
game.deck = game.createDeck();
//list to contain players (will be objects from the Player class)
let players = [];
//list to contain player usernames, will be used to identify if someone has already joined
let player_users = [];
// loop until we have enough players, as specified by the first input arguemnt
while (players.length <= no_players){
//now wait for a join message
client.on('message', message => {
//if message == join, and the player has not already joined
if (message.content.startsWith('join')){
if (!players.includes(message.author.username)){
let newPlayer = new Player(message.author.username,money);
players.push(newPlayer);
player_users.push(message.author.username);
}
}
});
}
//debugging purposes
console.log(players)
}
if (message.content.startsWith(`${prefix}hands`)){
message.channel.send("Here are the poker hands", {files: ["poker-hand-rankings-mobile.png"]});
}
});
client.login(process.env.TOKEN);
The command syntax in discord will look like !poker {number of players} {betting money for each player}
Other functionality in create decks etc works fine.
When I run in the debugger it doesnt seem to enter the second client.on code block, and I recieve this error upon running FATAL ERROR: MarkCompactCollector: young object promotion failed Allocation failed - JavaScript heap out of memory
Not sure if my overall approach is flawed here, i.e. discord.js cant have two processes waiting for messages running at the same time. Or if there is variable overlap between defining message.
Considering scrapping and moving to python so any help would be greatly appreciated.
I am making a discord bot in javascript. My intent is to visit https://api.chess.com/pub/player/edisonst/stats and somehow parse only the chess_daily last rating, chess_rapid last rating, chess_bullet last rating, chess_blitz last rating, etc. I do not know how to choose only those elements.
Here is my existing code.
const discord = require('discord.js')
const fetch = require('node-fetch');
const client = new discord.Client();
const prefix = '!';
client.once('ready', () =>{
console.log('Console is online');
});
client.on('message', async message => {
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length);
let url = "https://api.chess.com/pub/player/" + args + "stats";
})
In my last line of code I arrive at the site that I wish to get the information from, but I don't know how to get just those bits. Thank you for any and all help that I may receive.
You can use jsdom to "render" page that you get and manipulate it as you would in browser. This way you can select elements and get their contents.
I know that to have a collection populated such as guilds and channels, the bot must have logged in already, i.e. it can be used inside command files as well as inside events. What I have is a module that will display my logs inside my control discord server, and I want to be able to reference this module inside my events as well as my commands.
I have tried importing the module inside of the events, as well as other options that would make sense.
This is the code inside my module
const Discord = require('discord.js')
const bot = new Discord.Client()
const CC = '../settings/control-center.json'
const CCFile = require(CC)
const GUILD = bot.guilds.get(CCFile.GUILD)
const STARTUP = bot.channels.get(CCFile.STARTUP)
const INFO = bot.channels.get(CCFile.INFO)
const ERRORS = bot.channels.get(CCFile.ERRORS)
const RESTART = bot.channels.get(CCFile.RESTART)
const EXECUTABLES = bot.channels.get(CCFile.EXECUTABLES)
class Control {
/**
* Implement control center logging
* #param {string} message - What to send to the startup channel
* #return {string} The final product being sent to the startup channel
*/
STARTUP(message) {
return STARTUP.send(`${message}`)
}
}
module.exports = Control
I want to be able to globally use this module/the functions inside, so that my code can be more compact. So how can I have it so that this code is only loaded once the bot is logged in?
In your module code, you are creating a new Discord client instance, and never calling the login method.
A better approach would be to pass the bot object in your method
module file
const CC = '../settings/control-center.json';
const CCFile = require(CC);
const GUILD = CCFile.GUILD;
const STARTUP = CCFile.STARTUP;
const INFO = CCFile.INFO;
const ERRORS = CCFile.ERRORS;
const RESTART = CCFile.RESTART;
const EXECUTABLES = CCFile.EXECUTABLES;
class Control {
startup(bot, message) {
return bot.channels.get(STARTUP).send(message);
}
}
module.exports = Control
app file
// Use the bot here
const Discord = require('discord.js')
const bot = new Discord.Client()
const control = require('path/to/control.js');
[...]
// to send a message when ready, try something like this
bot.on('ready', () => {
control.startup(bot, 'bot is ready');
});
// don't forget to login
bot.login('YOUR-TOKEN-HERE');