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.
Related
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.
Revoking A Ban Using Code
So, I am making a moderation discord bot using VS Code and I have already set up a ban command. I want to make a unban command (revoking a ban) too so that the user can easily unban a user and not have to go into Server Settings to do it.
I know you can do it because I have been using another bot, GAwesomeBot, that is able to do it.
Link to GAwesomeBot: https://gawesomebot.com
I am a little new to Stack Overflow and this is my first question so pardon me if I am doing anything wrong.
Consider using GuildMemberManager#unban
https://discord.js.org/#/docs/main/stable/class/GuildMemberManager?scrollTo=unban
let guildMemberManager, toUnbanSnowflake;
guildMemberManager.unban(toUnbanSnowflake); // Takes UserResolveable as argument
First you want to define the user that you are unbanning.
Because the user is already banned you will have to mention the user by their ID and then unbanning them.
let args = message.content.split(/ +/g); //Split the message by every space
let user = message.guild.members.cache.get(args[1]); //getting the user
user.unban({ reason: args[2].length > 0 ? args[2] : 'No reason provided.' }); //Unbanning the user
The full example:
//Define your variables
const Discord = require('discord.js');
const client = new Discord.Client();
var prefix = 'your-prefix-here';
//Add a message event listener
client.on('message', () => {
let args = message.content.split(/ +/g); //Split the message by every space
if (message.content.toLowerCase() === prefix + 'unban') {
let user = message.guild.members.cache.get(args[1]); //getting the user
if (!user) return message.channel.send('Please specify a user ID');
user.unban({ reason: args[2].length > 0 ? args[2] : 'No reason provided.' }).then(() => message.channel.send('Success');
}
});
I've a node.js application that get some bot telegram token and run them as a bot.
I use telegraf module.
But when a bot receive too many request or throw an error and then crashed, this happen for the others bot.
What can i do to solve this problem.
I want the bots to be separate from each other.
A way is Copying my code and run the bots as multi script separately.
But i have many bot so it's impossible.
Here is my code to run the bots:
const Telegraf = require('telegraf');
var {Robots} = require('./model/models/robots');
var botsList = [];
setInterval(() => {
Robots.find({bot_type: 'group manager'}).then((res) => {
if(res.length > 0){
var tokens = [];
for(var i = 0 ; i < res.length ; i++){
var newToken = res[i].token;
tokens.push(newToken);
}
var bot = [];
tokens.map(token => {
if(!botsList.includes(token)){
botsList.push(token);
var botUserId = token.split(':')[0];
bot[botUserId] = new Telegraf(token);
module.exports = {
bot
};
const Commands = require('./controller/commands/commands.js');
bot[botUserId].on('text', (ctx) => {
Commands.executeCommand(bot[botUserId], ctx);
});
bot[botUserId].startPolling();
}
});
}
}).catch(console.log);
}, 5000);
If you just want the error in one broker to not affect the script as whole, you can just handle the error using process.uncaughtException handler for the script.
process.on('uncaughtException', console.log);
If you want to go a step further and create child process for each bot to run in. Use child_process module provided by Node.
const fork = require('child_process').fork;
fork('./bot.js', token);
Here, the bot.js can have all the bot related code.
Hope this helps!
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'
How do you play an audio file from a Discord bot? Needs to play a local file, be in JS, and upon a certain message being sent it will join the user who typed the message, and will play the file to that channel.
GitHub Project: LINK
In order to do this there are a few things you have to make sure of first.
Have FFMPEG installed & the environment path set for it in Windows [link]
Have Microsoft Visual Studio (VS) installed [link]
Have Node.js installed.[link]
Have Discord.js installed in VS.
From there the steps are quite simple. After making your project index.js you will start typing some code. Here are the steps:
Add the Discord.js dependency to the project;
var Discord = require('discord.js');
Create out client variable called bot;
var bot = new Discord.Client();
3. Create a Boolean variable to make sure that the system doesn't overload of requests;
var isReady = true;
Next make the function to intercept the correct message;
bot.on('message', message =>{ENTER CODE HERE});
Create an if statement to check if the message is correct & if the bot is ready;
if (isReady && message.content === 'MESSAGE'){ENTER CODE HERE}
Set the bot to unready so that it cannot process events until it finishes;
isReady = false;
Create a variable for the channel that the message-sender is currently in;
var voiceChannel = message.member.voice.channel;
Join that channel and keep track of all errors;
voiceChannel.join().then(connection =>{ENTER CODE HERE}).catch(err => console.log(err));
Create a refrence to and play the audio file;
const dispatcher = connection.play('./audiofile.mp3');
Slot to wait until the audio file is done playing;
dispatcher.on("end", end => {ENTER CODE HERE});
Leave channel after audio is done playing;
voiceChannel.leave();
Login to the application;
bot.login('CLIENT TOKEN HERE');
After you are all finished with this, make sure to check for any un-closed brackets or parentheses. i made this because it took my hours until I finally found a good solution so I just wanted to share it with anybody who is out there looking for something like this.
thanks so much!
One thing I will say to help anyone else, is things like where it says ENTER CODE HERE on step 10, you put the code from step 11 IE:
dispatcher.on("end", end => voiceChannel.leave());
As a complete example, this is how I have used it in my message command IF block:
if (command === "COMMAND") {
var VC = message.member.voiceChannel;
if (!VC)
return message.reply("MESSAGE IF NOT IN A VOICE CHANNEL")
VC.join()
.then(connection => {
const dispatcher = connection.playFile('c:/PAtH/TO/MP3/FILE.MP3');
dispatcher.on("end", end => {VC.leave()});
})
.catch(console.error);
};
I went ahead an included Nicholas Johnson's Github bot code here, but I made slight modifications.
He appears to be creating a lock; so I created a LockableClient that extends the Discord Client.
Never include an authorization token in the code
auth.json
{
"token" : "your-token-here"
}
lockable-client.js
const { Client } = require('discord.js')
/**
* A lockable client that can interact with the Discord API.
* #extends {Client}
*/
class LockableClient extends Client {
constructor(options) {
super(options)
this.locked = false
}
lock() {
this.setLocked(true)
}
unlock() {
this.setLocked(false)
}
setLocked(locked) {
return this.locked = locked
}
isLocked {
return this.locked
}
}
module.exports = LockableClient;
index.js
const auth = require('./auth.json')
const { LockableClient } = require('./lockable-client.js')
const bot = new LockableClient()
bot.on('message', message => {
if (!bot.isLocked() && message.content === 'Gotcha Bitch') {
bot.lock()
var voiceChannel = message.member.voiceChannel
voiceChannel.join().then(connection => {
const dispatcher = connection.playFile('./assets/audio/gab.mp3')
dispatcher.on('end', end => voiceChannel.leave());
}).catch(err => console.log(err))
bot.unlock()
}
})
bot.login(auth.token)
This is an semi old thread but I'm going to add code here that will hopefully help someone out and save them time. It took me way too long to figure this out but dispatcher.on('end') didn't work for me. I think in later versions of discord.js they changed it from end to finish
var voiceChannel = msg.member.voice.channel;
voiceChannel.join()
.then(connection => {
const dispatcher = connection.play(fileName);
dispatcher.on("finish", end => {
voiceChannel.leave();
deleteFile(fileName);
});
})
.catch(console.error);
Note that fileName is a string path for example: fileName = "/example.mp3". Hopefully that helps someone out there :)
Update: If you want to detect if the Audio has stopped, you must subscribe to the speaking event.
voiceChannel
.join()
.then((connection) => {
const dispatcher = connection.play("./audio_files/file.mp3");
dispatcher.on("speaking", (speaking) => {
if (!speaking) {
voiceChannel.leave();
}
});
})