Skip to content

Instantly share code, notes, and snippets.

@TrevorS
Last active August 29, 2015 14:14
Show Gist options
  • Save TrevorS/6087de3382ece806f99f to your computer and use it in GitHub Desktop.
Save TrevorS/6087de3382ece806f99f to your computer and use it in GitHub Desktop.
# api info
api = 'dictionaryapi.com/api/v1/references/collegiate/xml'
sounds = 'media.merriam-webster.com/soundc11'
key = process.env.PRONOUNCE_KEY
# xml parser
parser = require 'xml2json'
# define String#startsWith
String::startsWith = (string) -> @.lastIndexOf(string, 0) == 0
# respond to requests
module.exports = (robot) ->
robot.respond /pronounce (\w+)/i, (msg) ->
pronounce(msg, msg.match[1])
robot.respond /say (\w+)/i, (msg) ->
pronounce(msg, msg.match[1])
pronounce = (msg, word) ->
robot.http(call_for(word))
.get() (err, res, body) ->
try
data = parse_xml(body)
wav = find_wav(data)
msg.send pronunciation(wav)
catch
msg.send "Could not find #{word}."
parse_xml = (xml) ->
JSON.parse(parser.toJson(xml))
find_wav = (json) ->
json.entry_list.entry[0].sound.wav
call_for = (word) ->
"http://#{api}/#{word}?key=#{key}"
pronunciation = (wav) ->
if wav.startsWith('bix')
dir = 'bix'
else if wav.startsWith('gg')
dir = 'gg'
else
dir = wav[0]
"http://#{sounds}/#{dir}/#{wav}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment