1
0

telegram.lisp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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
  13. (handler-case
  14. (bordeaux-threads:with-timeout (timeout)
  15. (json-request (format nil +telegram-api-format+
  16. *telegram-token* method)
  17. :method :post
  18. :parameters params))
  19. (bordeaux-threads:timeout () (error "Timeout")))))
  20. (unless (aget "ok" response)
  21. (error (aget "description" response)))
  22. (aget "result" response)))
  23. (defun telegram-get-updates (&key offset limit timeout)
  24. (%telegram-api-call
  25. "getUpdates"
  26. (list (cons "offset" offset)
  27. (cons "limit" limit)
  28. (cons "timeout" timeout))))
  29. (defun telegram-send-message (chat-id text &key disable-web-preview reply-to reply-markup)
  30. (%telegram-api-call
  31. "sendMessage"
  32. (list (cons "chat_id" chat-id)
  33. (cons "text" text)
  34. (cons "disable_web_page_preview" disable-web-preview)
  35. (cons "reply_to_message_id" reply-to)
  36. (cons "reply_markup" reply-markup))))
  37. (defun telegram-send-sticker (chat-id sticker &key reply-to reply-markup)
  38. (%telegram-api-call
  39. "sendSticker"
  40. (list (cons "chat_id" chat-id)
  41. (cons "sticker" sticker)
  42. (cons "reply_to_message_id" reply-to)
  43. (cons "reply_markup" reply-markup))))
  44. (defun telegram-send-photo (chat-id photo &key caption reply-to reply-markup)
  45. (%telegram-api-call
  46. "sendPhoto"
  47. (list (cons "chat_id" chat-id)
  48. (cons "photo" photo)
  49. (cons "caption" caption)
  50. (cons "reply_to_message_id" reply-to)
  51. (cons "reply_markup" reply-markup))))
  52. (defun telegram-send-chat-action (chat-id action)
  53. (%telegram-api-call
  54. "sendChatAction"
  55. (list (cons "chat_id" chat-id)
  56. (cons "action" action))))