telegram.lisp 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. (in-package #:chatikbot)
  2. (defvar *telegram-token* nil "Telegram bot token")
  3. (defparameter +telegram-api-format+ "https://api.telegram.org/bot~A/~A")
  4. (defvar *telegram-timeout* 30 "Default Telegram timeout")
  5. ;; (defun %telegram-api-call (method &optional args)
  6. ;; (let* ((params (loop for (k . v) in args collect (cons
  7. ;; (princ-to-string k)
  8. ;; (princ-to-string v))))
  9. ;; (response (yason:parse
  10. ;; (flexi-streams:octets-to-string
  11. ;; (drakma:http-request (format nil +telegram-api-format+ *telegram-token* method)
  12. ;; :method :post
  13. ;; :parameters params
  14. ;; :external-format-out :utf8)
  15. ;; :external-format :utf8)
  16. ;; :object-as :alist)))
  17. ;; (unless (aget "ok" response)
  18. ;; (error (aget "description" response)))
  19. ;; (aget "result" response)))
  20. (defun %telegram-api-call (method &optional args)
  21. (let* ((params (loop for (k . v) in args collect (cons
  22. (princ-to-string k)
  23. (princ-to-string v))))
  24. (timeout (+ 5 (or (cdr (assoc :timeout args))
  25. *telegram-timeout*)))
  26. (response (yason:parse
  27. (flexi-streams:octets-to-string
  28. (handler-case
  29. (bordeaux-threads:with-timeout (timeout)
  30. (dex:post (format nil +telegram-api-format+ *telegram-token* method)
  31. :content params
  32. :use-connection-pool t
  33. :force-binary t))
  34. (bordeaux-threads:timeout (e)
  35. (declare (ignore e))
  36. (error "Timeout")))
  37. :external-format :utf8)
  38. :object-as :alist)))
  39. (unless (aget "ok" response)
  40. (error (aget "description" response)))
  41. (aget "result" response)))
  42. (defun telegram-get-updates (&key offset limit timeout)
  43. (%telegram-api-call
  44. "getUpdates"
  45. (list (cons "offset" offset)
  46. (cons "limit" limit)
  47. (cons "timeout" timeout))))
  48. (defun telegram-send-message (chat-id text &key disable-web-preview reply-to reply-markup)
  49. (%telegram-api-call
  50. "sendMessage"
  51. (list (cons "chat_id" chat-id)
  52. (cons "text" text)
  53. (cons "disable_web_page_preview" disable-web-preview)
  54. (cons "reply_to_message_id" reply-to)
  55. (cons "reply_markup" reply-markup))))
  56. (defun telegram-send-sticker (chat-id sticker &key reply-to reply-markup)
  57. (%telegram-api-call
  58. "sendSticker"
  59. (list (cons "chat_id" chat-id)
  60. (cons "sticker" sticker)
  61. (cons "reply_to_message_id" reply-to)
  62. (cons "reply_markup" reply-markup))))