1
0

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. (if (pathnamep v) v
  9. (princ-to-string v)))))
  10. (timeout (+ 5 (or (cdr (assoc :timeout args))
  11. *telegram-timeout*)))
  12. (response (yason:parse
  13. (flexi-streams:make-flexi-stream
  14. (handler-case
  15. (bordeaux-threads:with-timeout (timeout)
  16. (drakma:http-request (format nil +telegram-api-format+
  17. *telegram-token* method)
  18. :method :post
  19. :parameters params
  20. :external-format-out :utf8
  21. :want-stream t :force-binary t :decode-content t))
  22. (bordeaux-threads:timeout () (error "Timeout")))
  23. :external-format :utf8)
  24. :object-as :alist)))
  25. (unless (aget "ok" response)
  26. (error (aget "description" response)))
  27. (aget "result" response)))
  28. (defun telegram-get-updates (&key offset limit timeout)
  29. (%telegram-api-call
  30. "getUpdates"
  31. (list (cons "offset" offset)
  32. (cons "limit" limit)
  33. (cons "timeout" timeout))))
  34. (defun telegram-send-message (chat-id text &key disable-web-preview reply-to reply-markup)
  35. (%telegram-api-call
  36. "sendMessage"
  37. (list (cons "chat_id" chat-id)
  38. (cons "text" text)
  39. (cons "disable_web_page_preview" disable-web-preview)
  40. (cons "reply_to_message_id" reply-to)
  41. (cons "reply_markup" reply-markup))))
  42. (defun telegram-send-sticker (chat-id sticker &key reply-to reply-markup)
  43. (%telegram-api-call
  44. "sendSticker"
  45. (list (cons "chat_id" chat-id)
  46. (cons "sticker" sticker)
  47. (cons "reply_to_message_id" reply-to)
  48. (cons "reply_markup" reply-markup))))
  49. (defun telegram-send-photo (chat-id photo &key caption reply-to reply-markup)
  50. (%telegram-api-call
  51. "sendPhoto"
  52. (list (cons "chat_id" chat-id)
  53. (cons "photo" photo)
  54. (cons "caption" caption)
  55. (cons "reply_to_message_id" reply-to)
  56. (cons "reply_markup" reply-markup))))
  57. (defun telegram-send-chat-action (chat-id action)
  58. (%telegram-api-call
  59. "sendChatAction"
  60. (list (cons "chat_id" chat-id)
  61. (cons "action" action))))