Run C or Python Programs Using Discord Bot

Abhiram R Pai
Apr 6 · 6 min read
DiscordJs

During Lockdown I was using discord to interact with my friends while playing video games like among us. We used to play music using discord bot(groovy), while we took a break for like 5 mins. I was constantly thinking about creating a discord bot. I started off with an initial idea of creating a discord bot that would play music. Then one day my friend came up with a wild idea which was running programs written in c or python using a discord bot. I took this up as an challenge and ended up creating a bot that would run c and python program.

Running Python Program using Discord Bot
Running C Program using Discord Bot

Prerequisites

>NodeJs
>CodeEditor (VScode,Atom,Sublime,etc..)
>Discord Account and a Discord Server

Lets Start Creating the bot

First you have to register the bot in discord developer portal .

Developer Portal

After you login you will reach this screen then click on new application and you would be able to create a new application.

Creating the bot
General Info of the new bot

On this page you can set the bot icon description about the bot etc.

Select bot option, and add a bot.

Adding bot

Now the bot is setup,

Bot details

Now Lets Code the bot

First lets create a directory for the bot, and also install the dependencies required for coding the bot.

Inital Steps
  • discord.js — The Discord library used to create our Discord bot.
  • dotenv — This is going to allow us to hide certain variables, such as our bot’s client ID.
  • request — This package is used to make http and https request.

Lets start coding by opening preferred code editor, I am using vscode.

vscode folder structure

Now lets add .env and node_modules to .gitignore so that those files are not pushed to github repo in future.

gitignore

Now we will get the token for our bot from the developer portal,

click on bot option and then click on copy,

bot token

Now paste the bot token in .env file

CLIENT_TOKEN=<your token>

Now in package json add a line inside script tag,

“start”:"node index.js"
package.json

Now lets create a file index.js and add the required dependencies

const Discord = require(“discord.js”);
const client = new Discord.Client();
var request = require(“request”);
require(“dotenv”).config();
client.login(process.env.CLIENT_TOKEN);

Now for the compiler we would be using jdoodle api,
sign up and get the client Id and client Secret and paste it in .env file,

CLIENT_ID=<your client Id>
CLIENT_SECRET=<your client secret>

Now lets add the code to run c and python program

const Discord = require("discord.js");
const client = new Discord.Client();
var request = require("request");
require("dotenv").config();

const prefix = "coder ";

client.on("ready", () => {
console.log("coder-BOT is online!");
});

client.on("message", async (message) => {
try {
let args = message.content.substring(prefix.length).split(" ");
switch (args[0]) {case "run":
var input = "";
var language, index;
if (args[1] == "C" || args[1] == "c") {
language = "c";
index = "0";
} else if (args[1] == "python") {
language = "python3";
index = "3";
}
var fileName = message.attachments.array()[0];
for (var i = 2; i < args.length; i++) input += args[i] + " ";

request.get(fileName.url, (err, response, body) => {
const runRequestBody = {
script: body,
language: language,
stdin: input,
versionIndex: index,
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
};
request
.post({
url: "https://api.jdoodle.com/execute",
json: runRequestBody,
})
.on("error", (error) => {
console.log("request.post error", error);
return;
})
.on("data", (data) => {
const parsedData = JSON.parse(data.toString());
if (parsedData.error) {
return;
} else {
var output = "";
for (var i = 0; i < parsedData.output.length; i++) {
if (parsedData.output[i] == "\n") output += "\n";
else output += parsedData.output[i];
}
let outputOfProgram = new Discord.MessageEmbed()
.setAuthor(client.user.username)
.setDescription("Result!!!")
.setColor("33FFB3")
.setDescription(output);
message.channel.send(outputOfProgram);
return;
}
});
});
break;
}
}
catch (Exception) {
console.log(Exception);
let Errorbotembed = new Discord.MessageEmbed()
.setAuthor(client.user.username)
.setDescription("Error!!!")
.setColor("FFFFFF")
.setDescription("Error Encountered\nFor Help use\nDM help");
message.channel.send(Errorbotembed);
}
});


client.login(process.env.CLIENT_TOKEN);

So lets break the code,

client.on ready is when the discord bot goes online and it would just print coder-BOT is online in the command prompt.

client.on message works when someone sends a message in the channel on which the discord bot has access to.

In our case what we do here is we split the message to check whether the starting of the message contains the pattern “coder”. If a message starts with coder then we understand that the message is to the coderBot. Now here I used switch statement since we have only 1 command the coderbot address that is the run command.

Now when a message comes starting with “coder run” the first case would run and what we do in here is we check what is the argument that comes after the run command if it is c then c compiler is used and if it is python then we use the python interpreter. The index variable is set according to how the index is set in the jdoodle ide i.e, in our case we are using python 3.7.4 which is at index 3 in jdoodle python ide and gcc 5.3.0 c compiler at index 0.

Now after the language is specified we specify the inputs to the file and it is.

Now to capture the file that is uploaded along with the message we use,

var fileName = message.attachments.array()[0];

Now we send the request using jdoodle api and print the output accordingly.

Adding bot to server

Navigate to the OAuth2 option in the developer portal,

Oauth2 of the application

In scopes select bot,

Bot Permssion

Then in bot permission select send message and manage roles.

Copy the link and then go to the link and add to the discord server.

Add Bot To Server

After this the bot will be added to the discord server.

Now lets try running the bot.

Use the command,

npm start

You will get coder-Bot online message in cmd.

cmd

Now lets see whether it can run c and python programs,

Running Python Program using Coder Bot
Running C Program using Coder Bot

So we have successfully built a discord bot that can run c and python program using discord js.

You can find the full code here,

https://github.com/Pai026/coderBot

https://gist.github.com/Pai026/9979af5829a5854882858fcabfa6eb97

Any queries , Mail me @ abhirampai1999@gmail.com,

or DM at,

https://www.linkedin.com/in/abhiram-r-pai-bb3288170

Abhiram R Pai (@pai_abhiram) / Twitter

Abhiram Pai (@abhiram_pai) • Instagram photos and videos

Geek Culture

Proud to geek out. Follow to join our +500K monthly readers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store