Skip to content

Instantly share code, notes, and snippets.

@BlueSkunka
Created December 30, 2021 15:26
Show Gist options
  • Save BlueSkunka/f248ffa668fcaf6700efd28e69a33ce3 to your computer and use it in GitHub Desktop.
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
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