Skip to content

Instantly share code, notes, and snippets.

@paulosuzart
Last active March 9, 2020 10:53
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save paulosuzart/96197abdbf68b078545c to your computer and use it in GitHub Desktop.
Save paulosuzart/96197abdbf68b078545c to your computer and use it in GitHub Desktop.
#lang racket
(require net/http-client)
(require net/url)
(require json)
(require net/uri-codec)
(require racket/cmdline)
(define lg (make-logger 'currency-logger))
(current-logger lg)
(define rc (make-log-receiver lg 'info))
(define verbose-mode (make-parameter #t))
(define interval (make-parameter 1))
(define varying (make-parameter 0))
(define (fetch)
(let* (
[uri (string->url "https://currencyconverter.p.mashape.com/?from=USD&to=BRL&from_amount=1")]
[in (get-pure-port uri (list (format "X-Mashape-Key: ~a" (getenv "MASHAP_KEY"))) #:redirections 5)]
[to-amount (hash-ref (read-json in) 'to_amount)])
(log-info (format "Just fetched USD to BRL: ~a" to-amount))
to-amount))
(define (post-hip current-value last-value delta)
(let* ([message (format "O dolar ferrou! Variou em: ~a centavos. Valor anterior: ~a. Valor atual: ~a Usando deta: ~a" delta last-value current-value (varying))]
[form-encoded (list '(from . "cur-watcher") '(color . "red") (cons 'message message) '(room_id . "216979"))]
[uri (string->url (format "https://api.hipchat.com/v1/rooms/message?format=json&auth_token=~a" (getenv "HIPCHAT_TOKEN")))])
(let ([port (post-pure-port uri
(string->bytes/utf-8 (alist->form-urlencoded form-encoded))
'("Content-Type: application/x-www-form-urlencoded"))])
(log-info "Just posted to hipchat ~a: form-encoded" form-encoded))))
(define (process varying interval)
(define last-value -1)
(define current-value -1)
(for ([i (in-naturals 1)])
(log-info (format "Iteration n. ~a" i))
(set! current-value (fetch))
(let ([dif (abs (- last-value current-value))])
(and (>= dif varying)
(not (= last-value -1))
(post-hip current-value last-value dif))
(set! last-value current-value)
(sleep interval))))
(define main
(command-line
#:program "Currency Watcher"
#:once-each
[("-v" "--verbose") "More verbose output"
(verbose-mode #t)]
[("-i" "--interval") i "Interval between executions"
(interval (string->number i))]
[("-d" "--delta") d "Delta between last collected value and current one"
(varying (string->number d))]))
(void
(thread
(λ()(let loop ()
(define v (sync rc))
(and (verbose-mode)
(printf "[~a] ~a\n" (vector-ref v 0) (vector-ref v 1)))
(loop)))))
(process (varying) (interval))
@avraamisvi
Copy link

very good!

@unbalancedparentheses
Copy link

this is awesome

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment