<|start_filename|>download.js<|end_filename|>
const fs = require('fs');
const request = require('request');
const queue = require('async').queue;
const config = require('./config.json');

const SLACK_TOKEN = config.SLACK_TOKEN;
const API_URL = `https://slack.com/api/emoji.list`;

request(
  {
    uri: API_URL,
    json: true,
    headers: { Authorization: `Bearer ${SLACK_TOKEN}` },
  },
  (err, resp, obj) => {
    downloadEmojis(obj);
  }
);

function downloadEmojis(resp) {
  const { emoji } = resp;
  const q = queue(download, 10);
  q.drain = function () {
    console.log('all emojis have been downloaded to `/downloads` folder');
  };
  Object.keys(emoji).forEach((key) => {
    q.push({ name: key, uri: emoji[key] });
  });
}

function download(obj, cb) {
  const { name, uri } = obj;
  if (!uri.startsWith('http')) {
    return cb();
  }
  request(uri)
    .on('error', (err) => {
      console.error(err);
      cb(err);
    })
    .pipe(fs.createWriteStream(`downloads/${createName(name, uri)}`))
    .on('finish', cb);
}

function createName(name, uri) {
  return `${name}.${uri.split('.').pop()}`;
}


<|start_filename|>package.json<|end_filename|>
{
  "name": "slack-emoji",
  "version": "1.0.0",
  "description": "My slack emoji collection",
  "main": "download.js",
  "repository": "<EMAIL>:phil-r/slack-emoji.git",
  "author": "Phil <<EMAIL>>",
  "license": "MIT",
  "scripts": {
    "start": "node download.js",
    "download": "node download.js",
    "generate-md": "node generate-md.js"
  },
  "dependencies": {
    "async": "^3.1.1",
    "request": "^2.88.2"
  }
}


<|start_filename|>generate-md.js<|end_filename|>
const fs = require('fs');

const BLOCKED_FILENAMES = ['.DS_Store'];
const FOLDER = 'emojis/';


function notBlocked(filename){
  return !BLOCKED_FILENAMES.includes(filename);
}

let readme = `
# slack-emoji
:suspect: My slack emoji collection and download script

First, install dependencies:
\`\`\`sh
npm i
\`\`\`

Second, [create a slack app](https://api.slack.com/apps), add it to your workspace, add \`emoji:read\` user token scope and put the \`User OAuth Token\` into \`config.json\`

To download emojis from your slack team run:
> don't forget to create config.json, see [config.example.json](config.example.json)

\`\`\`sh
npm start
\`\`\`

To generate preview for readme run:
\`\`\`sh
npm run generate-md
\`\`\`

---
`


fs.readdir(FOLDER, (err, categories) => {
  categories.filter(notBlocked).sort().forEach(category => {
    const files = fs.readdirSync(`${FOLDER}${category}`);
    readme += `\n## ${category}\n\n`;
    files.filter(notBlocked).sort().forEach(file => {
      readme += `![${file}](${FOLDER + category}/${file})\n`;
    });
  });

  fs.writeFile("./README.md", readme, err => {
    if(err) {
        return console.error(err);
    }

    console.log("The readme was saved!")
  });
});
