{"size": 1537, "ext": "js", "max_stars_repo_path": "src/cmds/Services/lyrics.js", "max_stars_repo_name": "bakapear/JibrilBot", "max_stars_repo_stars_event_min_datetime": "2018-02-16T17:13:13.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-16T17:13:13.000Z", "max_issues_repo_path": "src/cmds/Services/lyrics.js", "max_issues_repo_name": "bakapear/JibrilBot", "max_issues_repo_issues_event_min_datetime": "2018-03-07T16:49:29.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-16T16:37:50.000Z", "max_forks_repo_path": "src/cmds/Services/lyrics.js", "max_forks_repo_name": "bakapear/Jibril", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1, "max_issues_count": 10, "max_forks_count": null, "avg_line_length": 24.015625, "max_line_length": 101, "alphanum_fraction": 0.5836044242}
/* global cfg */
let got = require('got')
let cheerio = require('cheerio')
let apiGenius = process.env.API_GENIUS

module.exports = {
  name: ['lyrics'],
  desc: 'Get the lyrics of a song',
  permission: '',
  usage: '<query>',
  args: 1,
  command: async function (msg, cmd, args) {
    let body = await searchGenius(args.join(' '))
    if (!body) {
      msg.channel.send('Something went wrong!')
      return
    }
    if (!body.length) {
      msg.channel.send('Nothing found!')
      return
    }
    let mod = msg.content.startsWith(cfg.prefix.random) ? Math.floor(Math.random() * body.length) : 0
    let lyrics = await getLyricsFromLink(body[mod].result.url)
    if (lyrics.length > 1996) lyrics = lyrics.substr(0, 1996) + '...'
    msg.channel.send({
      embed: {
        title: body[mod].result.title,
        description: lyrics,
        thumbnail: {
          url: body[mod].result.song_art_image_thumbnail_url
        }
      }
    })
  }
}

async function searchGenius (query) {
  try {
    let url = 'https://api.genius.com/search'
    let body = (await got(url, {
      json: true,
      headers: {

        Authorization: 'Bearer ' + apiGenius
      },
      query: {
        q: query
      }
    })).body
    if (body.response && body.response.hits) {
      return body.response.hits
    } else {
      return null
    }
  } catch (e) { if (e) return null }
}

async function getLyricsFromLink (link) {
  let body = (await got(link)).body
  let $ = cheerio.load(body)
  let res = $('.lyrics p').text()
  return res
}
