mariobot/bot.rkt

59 lines
2.1 KiB
Racket
Raw Normal View History

2020-02-28 11:22:10 -05:00
2020-01-25 20:52:55 -05:00
#lang racket/base
2020-02-28 11:22:10 -05:00
(require net/http-client json net/url racket/port web-server/private/timer racket/file racket/bytes file/md5)
2020-01-25 20:52:55 -05:00
(define server (getenv "SERVER"))
2020-02-28 11:22:10 -05:00
(define token (getenv "TOKEN"))
2020-01-25 20:52:55 -05:00
(define safebooru "safebooru.donmai.us")
(define limit "20")
2020-02-28 11:22:10 -05:00
(define page (number->string (random 1 350)))
(define tags "mario_(series)%20-bowsette")
(define pos (random 19))
(define CRLF "\r\n")
(define boundary (bytes->string/utf-8 (md5 (number->string (current-seconds)))))
(define boundary-line (string-append "--" boundary CRLF))
2020-01-25 20:52:55 -05:00
(define (search-safebooru)
(define-values (status header response)(http-sendrecv safebooru (string-append "/posts.json?limit=" limit "&page=" page "&tags="tags ) #:ssl? #t))
(define posts (read-json response))
(list-ref posts pos))
2020-02-28 11:22:10 -05:00
(define (main)
2020-01-25 20:52:55 -05:00
(define post (search-safebooru))
(define url (hash-ref post 'file_url))
(define md5 (hash-ref post 'md5))
(define file-ext (hash-ref post 'file_ext))
(define filename (string-append md5 "." file-ext))
2020-02-28 11:22:10 -05:00
(displayln (format "Downloading ~a" filename))
2020-01-25 20:52:55 -05:00
(call-with-output-file filename
2020-02-28 11:22:10 -05:00
(lambda (in) (display (port->bytes (get-pure-port (string->url url)))in))
#:exists 'replace)
(define data
(bytes-append
(string->bytes/utf-8 (string-append boundary-line "Content-Disposition: form-data; name=\"media_ids[0]\"; filename=" "\"" filename "\"" CRLF
(format "Content-Type: image/~a" (if (eq? file-ext "jpg") "jpeg" "png")) CRLF CRLF))
(file->bytes filename)
(string->bytes/utf-8 (string-append CRLF "--" boundary "--" CRLF))))
(define-values (status headers response)
(http-sendrecv server (string-append "/api/v1/statuses") #:ssl? #t #:method #"POST" #:headers (list (string-append "Content-Type: multipart/form-data; boundary=" boundary) (string-append "Authorization: Bearer " token)) #:data data))
(displayln (format "Uploading to ~a" server))
(displayln status)
(displayln (read-json response)))
(main)
2020-01-25 20:52:55 -05:00
;define tm (start-timer-manager))
;define (loop)
;(start-timer tm 600 (upload-image))
;loop))
;loop)