Created
December 30, 2021 15:26
-
-
Save BlueSkunka/f248ffa668fcaf6700efd28e69a33ce3 to your computer and use it in GitHub Desktop.
Generate Chart.js graph and reply with discord bot with graph as embed message
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { SlashCommandBuilder } = require("@discordjs/builders"); | |
const rp = require("request-promise"); | |
const { MessageEmbed, MessageAttachment } = require("discord.js"); | |
const { ChartJSNodeCanvas } = require("chartjs-node-canvas"); | |
let chartEmbed = {}; | |
// This function will return MessageAttachment object from discord.js | |
// Pass as much parameter as you need | |
const generateCanva = async (labels, datas) => { | |
const renderer = new ChartJSNodeCanvas({ width: 800, height: 300 }); | |
const image = await renderer.renderToBuffer({ | |
// Build your graph passing option you want | |
type: "line", // Show a bar chart | |
backgroundColor: "rgba(236,197,1)", | |
data: { | |
labels: labels, | |
datasets: [ | |
{ | |
label: "My graph title", | |
data: datas, | |
}, | |
], | |
}, | |
}); | |
return new MessageAttachment(image, "graph.png"); | |
}; | |
module.exports = { | |
data: new SlashCommandBuilder(), | |
// Build your command option before execute() if you plan to add slashCommands to your server | |
async execute(interaction) { | |
let labels = ["a", "b", "c"]; | |
let data = [10, 5, 9]; | |
// Create MessageEmbed passing options you want | |
chartEmbed = new MessageEmbed({ | |
title: "MessageEmbed title", | |
color: "YELLOW", | |
}); | |
chartEmbed.setImage("attachment://graph.png"); | |
// Generate your graph & get the picture as response | |
const attachment = await generateCanva(labels, data, convert); | |
// Reply to server / channel you want passing MessageEmbed & messageAttachment objects | |
interaction.reply({ embeds: [chartEmbed], files: [attachment] }); | |
//#endregion | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment