<commit_before>/*
 * eval.js - Evaluate JavaScript code in Discord.
 *
 * Contributed by Ovyerus.
 */

/* eslint-disable no-unused-vars */
const Eris = require('eris');
const util = require('util');
const fs = require('fs');
const cp = require('child_process');
const path = require('path');
const got = require('got');
const IncomingMessage = require('http').IncomingMessage;
/* eslint-enable */

const FailCol = 0xF44336;
const SuccessCol = 0x8BC34A;
const ReplaceRegex = {};

exports.init = bot => {
    ReplaceRegex.token = new RegExp(`${bot.token}`, 'gi');
    Object.keys(bot.config).filter(key => /(key|token)/i.test(key)).forEach(key => {
        ReplaceRegex[key] = new RegExp(bot.config[key], 'gi');
    });
};

exports.commands = [
    'eval'
];

exports.eval = {
    desc: 'Evaluate code in Discord.',
    fullDesc: 'Used to evaluate JavaScript code in Discord. Mostly for debug purposes.',
    owner: true,
    usage: '<code>',
    main(bot, ctx) {
        return new Promise((resolve, reject) => {
            if (ctx.suffix.length === 0) {
                ctx.createMessage('Please give arguments to evaluate.').then(resolve).catch(reject);
            } else {
                let {args, cmd, suffix, cleansuffix, settings, guildBot, channel, guild} = ctx; // eslint-disable-line
                try {
                    let returned = eval(ctx.suffix);
                    let str = util.inspect(returned, {depth: 1});
                    str = str.replace(ReplaceRegex.token, '(token)');

                    let embed = {
                        title: 'Evaluation Results',
                        color: SuccessCol,
                        fields: [
                            {name: 'Input', value: generateCodeblock(ctx.suffix)},
                            {name: 'Output', value: generateCodeblock(str)}
                        ]
                    };

                    if (returned instanceof Promise) embed.fields[1].value = generateCodeblock('[object Promise]');

                    if (str.length < 1000) {
                        sendEval(bot, ctx, embed, returned).then(resolve).catch(reject);
                    } else {
                        bot.hastePost(str).then(key => {
                            let url = `https://hastebin.com/${key}.js`;
                            embed.fields[1].value = `Output is too long to display nicely.\nOutput has been uploaded [here](${url})`;

                            return sendEval(bot, ctx, embed, returned);
                        }).then(resolve).catch(reject);
                    }
                } catch(err) {
                    logger.error(err.stack || err);
                    let embed = {
                        title: 'Evaluation Results',
                        color: FailCol,
                        fields: [
                            {name: 'Input', value: generateCodeblock(ctx.suffix)},
                            {name: 'Error', value: generateCodeblock(err)}
                        ]
                    };

                    ctx.createMessage({embed}).then(resolve).catch(reject);
                }
            }
        });
    }
};

function generateCodeblock(text) {
    return `\`\`\`js\n${text}\n\`\`\``;
}

function sendEval(bot, ctx, embed, returned) {
    return new Promise((resolve, reject) => {
        let outer;
        ctx.createMessage({embed}).then(m => {
            outer = m;
            if (returned instanceof Promise) {
                return returned;
            } else {
                return null;
            }
        }).then(res => {
            if (!res) {
                resolve();
                return null;
            } else {
                let strN;
                if (res instanceof IncomingMessage && res.requestUrl) {
                    strN = res.headers['content-type'].split(';')[0] === 'application/json' ? util.inspect(JSON.parse(res.body), {depth: 1}) : res.body;
                } else {
                    strN = util.inspect(res, {depth: 1});
                }
                strN = strN.replace(ReplaceRegex.token, '(token)');

                if (strN.length >= 1000) {
                    return bot.hastePost(strN);
                } else {
                    return outer.edit({embed: {
                        title: 'Evaluation Results',
                        color: SuccessCol,
                        fields: [
                            {name: 'Input', value: generateCodeblock(ctx.suffix)},
                            {name: 'Output', value: generateCodeblock(strN)}
                        ]
                    }});
                }
            }
        }).then(res => {
            if (!res || res instanceof Eris.Message) return null;

            let url = `https://hastebin.com/${res}.js`;

            return outer.edit({embed: {
                title: 'Evaluation Results',
                color: SuccessCol,
                fields: [
                    {name: 'Input', value: generateCodeblock(ctx.suffix)},
                    {name: 'Output', value: `Output is too long to display nicely.\nOutput has been uploaded [here](${url})`}<commit_msg>Maybe finally fix got request handling<commit_after>/*
 * eval.js - Evaluate JavaScript code in Discord.
 *
 * Contributed by Ovyerus.
 */

/* eslint-disable no-unused-vars */
const Eris = require('eris');
const util = require('util');
const fs = require('fs');
const cp = require('child_process');
const path = require('path');
const got = require('got');
const IncomingMessage = require('http').IncomingMessage;
const PassThrough = require('streams').PassThrough;
/* eslint-enable */

const FailCol = 0xF44336;
const SuccessCol = 0x8BC34A;
const ReplaceRegex = {};

exports.init = bot => {
    ReplaceRegex.token = new RegExp(`${bot.token}`, 'gi');
    Object.keys(bot.config).filter(key => /(key|token)/i.test(key)).forEach(key => {
        ReplaceRegex[key] = new RegExp(bot.config[key], 'gi');
    });
};

exports.commands = [
    'eval'
];

exports.eval = {
    desc: 'Evaluate code in Discord.',
    fullDesc: 'Used to evaluate JavaScript code in Discord. Mostly for debug purposes.',
    owner: true,
    usage: '<code>',
    main(bot, ctx) {
        return new Promise((resolve, reject) => {
            if (ctx.suffix.length === 0) {
                ctx.createMessage('Please give arguments to evaluate.').then(resolve).catch(reject);
            } else {
                let {args, cmd, suffix, cleansuffix, settings, guildBot, channel, guild} = ctx; // eslint-disable-line
                try {
                    let returned = eval(ctx.suffix);
                    let str = util.inspect(returned, {depth: 1});
                    str = str.replace(ReplaceRegex.token, '(token)');

                    let embed = {
                        title: 'Evaluation Results',
                        color: SuccessCol,
                        fields: [
                            {name: 'Input', value: generateCodeblock(ctx.suffix)},
                            {name: 'Output', value: generateCodeblock(str)}
                        ]
                    };

                    if (returned instanceof Promise) embed.fields[1].value = generateCodeblock('[object Promise]');

                    if (str.length < 1000) {
                        sendEval(bot, ctx, embed, returned).then(resolve).catch(reject);
                    } else {
                        bot.hastePost(str).then(key => {
                            let url = `https://hastebin.com/${key}.js`;
                            embed.fields[1].value = `Output is too long to display nicely.\nOutput has been uploaded [here](${url})`;

                            return sendEval(bot, ctx, embed, returned);
                        }).then(resolve).catch(reject);
                    }
                } catch(err) {
                    logger.error(err.stack || err);
                    let embed = {
                        title: 'Evaluation Results',
                        color: FailCol,
                        fields: [
                            {name: 'Input', value: generateCodeblock(ctx.suffix)},
                            {name: 'Error', value: generateCodeblock(err)}
                        ]
                    };

                    ctx.createMessage({embed}).then(resolve).catch(reject);
                }
            }
        });
    }
};

function generateCodeblock(text) {
    return `\`\`\`js\n${text}\n\`\`\``;
}

function sendEval(bot, ctx, embed, returned) {
    return new Promise((resolve, reject) => {
        let outer;
        ctx.createMessage({embed}).then(m => {
            outer = m;
            if (returned instanceof Promise) {
                return returned;
            } else {
                return null;
            }
        }).then(res => {
            if (!res) {
                resolve();
                return null;
            } else {
                let strN;
                if ((res instanceof IncomingMessage || res instanceof PassThrough) && res.requestUrl) {
                    strN = res.headers['content-type'].split(';')[0] === 'application/json' ? util.inspect(JSON.parse(res.body), {depth: 1}) : res.body;
                } else {
                    strN = util.inspect(res, {depth: 1});
                }
                strN = strN.replace(ReplaceRegex.token, '(token)');

                if (strN.length >= 1000) {
                    return bot.hastePost(strN);
                } else {
                    return outer.edit({embed: {
                        title: 'Evaluation Results',
                        color: SuccessCol,
                        fields: [
                            {name: 'Input', value: generateCodeblock(ctx.suffix)},
                            {name: 'Output', value: generateCodeblock(strN)}
                        ]
                    }});
                }
            }
        }).then(res => {
            if (!res || res instanceof Eris.Message) return null;

            let url = `https://hastebin.com/${res}.js`;

            return outer.edit({embed: {
                title: 'Evaluation Results',
                color: SuccessCol,
                fields: [
                    {name: 'Input', value: generateCodeblock(ctx.suffix)},
                    {name: 'Output', value: `Output is too long to display nicely.\nOutput has been uploaded [here](${url})`}
{'fraction_non_alphanumeric': 0.13262268318448095, 'fraction_numerical': 0.004801690194948622, 'mean_word_length': 1.4224238194929053, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 25, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5799721', 'n_tokens_mistral': 2810, 'n_tokens_neox': 2613, 'n_words': 618}