1
0

telegram.lisp 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. (error e)))
  36. :external-format :utf8)
  37. :object-as :alist)))
  38. (unless (aget "ok" response)
  39. (error (aget "description" response)))
  40. (aget "result" response)))
  41. (defun telegram-get-updates (&key offset limit timeout)
  42. (%telegram-api-call
  43. "getUpdates"
  44. (list (cons "offset" offset)
  45. (cons "limit" limit)
  46. (cons "timeout" timeout))))
  47. (defun telegram-send-message (chat-id text &key disable-web-preview reply-to reply-markup)
  48. (%telegram-api-call
  49. "sendMessage"
  50. (list (cons "chat_id" chat-id)
  51. (cons "text" text)
  52. (cons "disable_web_page_preview" disable-web-preview)
  53. (cons "reply_to_message_id" reply-to)
  54. (cons "reply_markup" reply-markup))))
  55. (defun telegram-send-sticker (chat-id sticker &key reply-to reply-markup)
  56. (%telegram-api-call
  57. "sendSticker"
  58. (list (cons "chat_id" chat-id)
  59. (cons "sticker" sticker)
  60. (cons "reply_to_message_id" reply-to)
  61. (cons "reply_markup" reply-markup))))