vk.lisp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. (in-package #:chatikbot)
  2. (defparameter +vk-api-url+ "https://api.vk.com/method/~A?v=5.40" "VK.com API endpoint")
  3. (defun %vk-api-call (method &optional args)
  4. (handler-case
  5. (bordeaux-threads:with-timeout (5)
  6. (let* ((params (loop for (k . v) in args
  7. when v
  8. collect (cons
  9. (princ-to-string k)
  10. (princ-to-string v))))
  11. (response (json-request (format nil +vk-api-url+ method)
  12. :method :post
  13. :parameters params)))
  14. (when (aget "error" response)
  15. (error (aget "error_msg" (aget "error" response))))
  16. (aget "response" response)))
  17. (bordeaux-threads:timeout (e)
  18. (declare (ignore e))
  19. (error "Timeout"))))
  20. (defun vk-wall-get (&key owner-id domain offset count filter extended fields)
  21. (%vk-api-call "wall.get"
  22. `(("owner_id" . ,owner-id)
  23. ("domain" . ,domain)
  24. ("offset" . ,offset)
  25. ("count" . ,count)
  26. ("filter" . ,filter)
  27. ("extended" . ,extended)
  28. ("fields" . ,fields))))
  29. (defun vk-get-user-name (id)
  30. (let ((r (first (%vk-api-call "users.get" `(("user_ids" . ,id))))))
  31. (format nil "~A ~A" (aget "first_name" r) (aget "last_name" r))))
  32. (defun vk-get-group-name (id)
  33. (aget "name" (first (%vk-api-call "groups.getById"
  34. `(("group_id" . ,(if (numberp id)
  35. (- id)
  36. id)))))))
  37. (defun vk-get-name (id)
  38. (if (and (numberp id) (> id 0))
  39. (vk-get-user-name id)
  40. (vk-get-group-name id)))
  41. ;; VK walls
  42. (defun %send-domains (chat-id domains)
  43. (bot-send-message
  44. chat-id
  45. (if (null domains)
  46. "Пока ничего не постим"
  47. (format nil "Постим~%~{~A) https://vk.com/~A~^~%~}"
  48. (loop for d in domains for i from 1 append (list i d))))
  49. :disable-web-preview 1))
  50. (defun %find-vk-domain (url)
  51. (let ((path (puri:uri-path (puri:parse-uri url))))
  52. (if (equal #\/ (elt path 0))
  53. (subseq path 1)
  54. path)))
  55. (defun %ensure-domain (domain)
  56. (let* ((res (vk-wall-get :domain domain :count 1))
  57. (last-id (aget "id" (first (aget "items" res)))))
  58. (db/vk-ensure-domain domain last-id)
  59. domain))
  60. (defun %vk-find-best-photo (attach)
  61. (when attach
  62. (let* ((photo (aget "photo" attach))
  63. (sizes (loop for (k . v) in photo
  64. when (equal "photo_" (subseq k 0 (min 6 (length k))))
  65. collect (cons (parse-integer (subseq k 6)) v))))
  66. (cdr (assoc (apply #'max (mapcar #'car sizes)) sizes)))))
  67. (defun %vk-find-video (attach)
  68. (when attach
  69. (let ((video (aget "video" attach)))
  70. (format nil "https://vk.com/video~A_~A"
  71. (aget "owner_id" video)
  72. (aget "id" video)))))
  73. (defun %vk-find-preview (attachments)
  74. (labels ((find-type (type)
  75. (find type attachments :key #'(lambda (a) (aget "type" a)) :test #'equal)))
  76. (or
  77. (%vk-find-best-photo (find-type "photo"))
  78. (%vk-find-video (find-type "video")))))
  79. (defparameter +vk-link-scanner+ (cl-ppcre:create-scanner "\\[((id|club)\\d+)\\|([^\\]]*?)\\]") "vk linking regex")
  80. (defun %vk-post-text (post)
  81. (let* ((history (aget "copy_history" post))
  82. (reposts (loop for p in history
  83. collect (let* ((owner (aget "owner_id" p))
  84. (type (if (> owner 0) "id" "club"))
  85. (id (abs owner)))
  86. (format nil "[~A](https://vk.com/~A~A)"
  87. (vk-get-name owner) type id)))))
  88. (when history
  89. (setf post (car (last history))))
  90. (values
  91. (cl-ppcre:regex-replace-all +vk-link-scanner+
  92. (aget "text" post)
  93. "[\\3](https://vk.com/\\1)")
  94. (%vk-find-preview (aget "attachments" post))
  95. reposts)))
  96. (defun %format-wall-post (domain name post)
  97. (multiple-value-bind (text preview reposts) (%vk-post-text post)
  98. (values
  99. (format nil "~@[[✅](~A) ~][~A](https://vk.com/~A?w=wall~A_~A)~@[ ~{↩ ~A~}~]~@[ @ ~A~]~%~A"
  100. preview name domain (aget "from_id" post) (aget "id" post)
  101. reposts (format-ts (local-time:unix-to-timestamp (aget "date" post)))
  102. text)
  103. (if preview 0 1))))
  104. ;; Database
  105. (def-db-init
  106. (db-execute "create table if not exists vk_walls (domain, last_id, next_fetch, period)")
  107. (db-execute "create unique index if not exists vk_walls_domain_idx on vk_walls (domain)")
  108. (db-execute "create table if not exists vk_chat_walls (chat_id, domain)")
  109. (db-execute "create index if not exists vk_chat_walls_chat_idx on vk_chat_walls (chat_id)")
  110. (db-execute "create index if not exists vk_chat_walls_domain_idx on vk_chat_walls (domain)"))
  111. (defun db/vk-ensure-domain (domain last-id)
  112. (db-transaction
  113. (unless (db-single "select domain from vk_walls where domain = ?" domain)
  114. (db-execute "insert into vk_walls (domain, last_id, period) values (?, ?, 300)" domain last-id))))
  115. (defun db/vk-get-domain-chats (domain)
  116. (flatten (db-select "select chat_id from vk_chat_walls where domain = ?" domain)))
  117. (defun db/vk-get-chat-domains (chat-id)
  118. (flatten (db-select "select domain from vk_chat_walls where chat_id = ?" chat-id)))
  119. (defun db/vk-add-chat-domain (chat-id domain)
  120. (db-execute "insert into vk_chat_walls (chat_id, domain) values (?, ?)" chat-id domain))
  121. (defun db/vk-remove-chat-domain (chat-id domain)
  122. (db-execute "delete from vk_chat_walls where chat_id = ? and domain = ?" chat-id domain))
  123. (defun db/vk-get-active-walls ()
  124. (db-select "select domain, last_id, next_fetch, period from vk_walls w where exists (select 1 from vk_chat_walls where domain=w.domain)"))
  125. (defun db/vk-update-wall (domain last-id next-fetch period)
  126. (db-execute "update vk_walls set last_id = ?, next_fetch = ?, period = ? where domain = ?" last-id next-fetch period domain))
  127. ;; Cron
  128. (defcron process-walls ()
  129. (loop for (domain last-id next-fetch period) in (db/vk-get-active-walls)
  130. when (or (null next-fetch)
  131. (local-time:timestamp> (local-time:now) (local-time:unix-to-timestamp next-fetch)))
  132. do (progn
  133. (log:info "Fetching wall" domain)
  134. (handler-case
  135. (let ((new-posts
  136. (remove last-id (reverse (aget "items" (vk-wall-get :domain domain)))
  137. :test #'>= :key (lambda (p) (aget "id" p))))
  138. name)
  139. (setf period (adjust-period period (length new-posts)))
  140. (when new-posts
  141. (setf name (vk-get-name domain)))
  142. (dolist (post new-posts)
  143. (multiple-value-bind (text disable)
  144. (%format-wall-post domain name post)
  145. (dolist (chat-id (db/vk-get-domain-chats domain))
  146. (ignore-errors
  147. (telegram-send-message chat-id text
  148. :parse-mode "Markdown"
  149. :disable-web-preview disable))))
  150. (setf last-id (max last-id (aget "id" post)))))
  151. (error (e) (log:error "~A" e)))
  152. (db/vk-update-wall domain last-id
  153. (local-time:timestamp-to-unix
  154. (local-time:timestamp+ (local-time:now) period :sec))
  155. period))) ;; Update last-id, next-fetch and period
  156. )
  157. ;; Hooks
  158. (defparameter +akb-vk-domain+ "baneks" "VK.com username of 'B-category anekdotes'")
  159. (defvar *akb-max-posts* 10 "Maximum number of AKB posts to send at once")
  160. (defun format-akb (post)
  161. (let* ((id (aget "id" post))
  162. (url (format nil "https://vk.com/~A?w=wall~A_~A"
  163. +akb-vk-domain+ (aget "from_id" post) id)))
  164. (format nil "~A~%~A" (aget "text" post) url)))
  165. (def-message-cmd-handler handler-akb (:akb)
  166. (let ((total-aneks
  167. (aget "count" (vk-wall-get :domain +akb-vk-domain+ :count 1 :offset 10000000))))
  168. (dolist (post (aget "items" (vk-wall-get :domain +akb-vk-domain+
  169. :count (min *akb-max-posts*
  170. (or (ignore-errors (parse-integer (car args)))
  171. 1))
  172. :offset (random total-aneks))))
  173. (bot-send-message chat-id (format-akb post) :disable-web-preview 1))))
  174. (def-message-cmd-handler handler-cmd-wall (:wall)
  175. (let ((domains (db/vk-get-chat-domains chat-id)))
  176. (if (null args)
  177. (%send-domains chat-id domains)
  178. (progn
  179. (dolist (url args)
  180. (handler-case
  181. (let ((idx (parse-integer url)))
  182. (db/vk-remove-chat-domain chat-id (nth (1- idx) domains)))
  183. (parse-error ()
  184. (let* ((domain (%ensure-domain (%find-vk-domain url)))
  185. (existing (find domain domains :test #'equal)))
  186. (if existing
  187. (db/vk-remove-chat-domain chat-id domain)
  188. (db/vk-add-chat-domain chat-id domain))))
  189. (error (e) (log:error "~A" e))))
  190. (%send-domains chat-id (db/vk-get-chat-domains chat-id))))))