1
0

vk.lisp 11 KB

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