Permalink
Switch branches/tags
Nothing to show
Find file
Fetching contributors…
Cannot retrieve contributors at this time
93 lines (69 sloc) 2.41 KB
# irc-bot-js-currency_conversion
# ------------------------------
# Live currency conversion for irc-js-bot
# This is an official plug-in
#
# Provides one bot command: '$'
# Depends on the 'goo.gl' module
'use strict'
util = require 'util'
http = require 'http'
shorten = require 'goo.gl'
module.exports = ->
@register_special_command
name: '$'
description: 'Perform currency conversion or retrieve exchange rate.'
admin_only: false
fn: (event, input_data, output_data) =>
api_key = @bot_options.plugin_options?['irc-js-bot-currency_conversion']?.api_key
if not api_key
@log.warning "#{@log.prefix} API key for plug-in « irc-js-bot-currency_conversion » not found"
return
if '?' in input_data.flags
message = '$ <from> <to> [<amount>] • Perform currency conversion or retrieve exchange rate. If <amount> is not specified, shows exchange rate. <from> and <to> must be three-letter country codes.'
else if not input_data.args
message = "Insufficient arguments specified for currency conversion command; see #{input_data.trigger}$/? for details"
else
args_match = input_data.args.match ///
^
(\w{3}) # Three-letter country code #1
\s+
(\w{3}) # Three-letter country code #2
( # Start amount group (optional)
\s+
([\d\.,]+) # Amount
)?
$
///
if not args_match
message = "Invalid format specified for currency conversion command; see #{input_data.trigger}$/? for details"
else
from = do args_match[1].toUpperCase
to = do args_match[2].toUpperCase
amount = if args_match[4] then args_match[4].replace ',', '.' else ''
await convert from, to, amount, api_key, defer err, result
result = +result
if err
message = 'Oops, something went wrong!'
if not amount
message = "Current exchange rate #{from}#{to} is #{result}"
else
message = "#{amount} #{from} is currently #{result} #{to}"
@send output_data.method, output_data.recipient, message
convert = (from, to, amount, api_key, cb) ->
result = []
req = http.request
hostname: 'www.exchangerate-api.com'
path: "/#{from}/#{to}/#{amount}?k=#{api_key}"
method: 'get'
, (res) ->
res.setEncoding 'utf-8'
res.on 'data', (data) ->
result.push data
res.on 'end', ->
result = result.join ''
err = true if not result
cb err, result
req.on 'error', (err) ->
cb err, null
do req.end