Skip to content

Commit

Permalink
telebot: define functions with keyword arguments with define-api
Browse files Browse the repository at this point in the history
  • Loading branch information
yfzhe committed Jan 16, 2024
1 parent 7ea5fc9 commit 8d714ad
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 16 deletions.
2 changes: 1 addition & 1 deletion telebot/api.rkt
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@

;; api methods
(define-api bot-get-me "/getMe"
-> user)
() -> user)

(define-api bot-send-message "/sendMessage"
response -> message)
20 changes: 8 additions & 12 deletions telebot/main.rkt
Original file line number Diff line number Diff line change
Expand Up @@ -14,31 +14,27 @@
ref :
bot-start/poll bot-start/webhook)

(define (bot-get-updates bot [offset 0])
(bot-post bot "/getUpdates"
(hasheq 'offset (number->string offset))))
(define-api bot-get-updates "/getUpdates"
((offset integer?)) -> (listof update))

(define (bot-set-webhook bot webhook-url)
;; TODO: getWebhookInfo and compare to the target
(bot-post bot "/setWebhook"
(hasheq 'url webhook-url)))
(define-api bot-set-webhook "/setWebhook"
((webhook-url string? "url"))
-> true?)

(define (bot-start/poll bot handle-update)
(let loop ([offset 0] [updates '()])
(cond
[(null? updates)
(loop offset (bot-get-updates bot offset))]
[else
(define update (jsexpr->update (car updates)))
(define update (car updates))
(define resp (handle-update update))
(bot-send-message bot resp)
(loop (add1 (update-id update)) (cdr updates))])))

(define (bot-start/webhook bot handle-update webhook-base port)
(define webhook-url
(string-append webhook-base "/webhook"))

(bot-set-webhook bot webhook-url)
(bot-set-webhook bot
#:webhook-url (string-append webhook-base "/webhook"))

(define (handle-webhook req)
(thread
Expand Down
14 changes: 11 additions & 3 deletions telebot/private/schema.rkt
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,14 @@
(define-syntax (define-api stx)
(syntax-parse stx
#:literals (->)
[(_ api-id endpoint (~optional arg:schema) -> ret:schema)
#'(define (api-id bot (~? arg))
(ret.from-jsexpr (bot-post bot endpoint (~? (arg.to-jsexpr arg)))))]))
[(_ api-id:id endpoint:string arg:schema -> ret:schema)
#'(define (api-id bot arg)
(ret.from-jsexpr (bot-post bot endpoint (arg.to-jsexpr arg))))]
[(_ api-id:id endpoint:string (fld:field ...) -> ret:schema)
#'(define (api-id bot (~@ . (make-field-kw-arg fld)) ...)
(ret.from-jsexpr
(bot-post bot endpoint
(let ([json (make-hasheq)])
(unless (json-undefined? fld.name)
(hash-set! json 'fld.key (fld.to-jsexpr fld.name))) ...
json))))]))

0 comments on commit 8d714ad

Please sign in to comment.