chatikbot.lisp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. (in-package #:chatikbot)
  2. ;; Load config file
  3. (alexandria:when-let (file (probe-file
  4. (merge-pathnames "config.lisp"
  5. (asdf:component-pathname
  6. (asdf:find-system '#:chatikbot)))))
  7. (load file))
  8. ;; Init database
  9. (db-init)
  10. (defvar *telegram-last-update* nil "Telegram last update_id")
  11. (defvar *admins* nil "Admins chat-ids")
  12. (defun process-updates ()
  13. (loop for update in (telegram-get-updates :offset (and *telegram-last-update*
  14. (1+ *telegram-last-update*))
  15. :timeout 300)
  16. do (setf *telegram-last-update*
  17. (max (or *telegram-last-update* 0)
  18. (aget "update_id" update)))
  19. do (handle-message (aget "message" update))))
  20. (defun send-response (chat-id response &optional reply-id)
  21. (if (consp response)
  22. (if (keywordp (car response))
  23. (case (car response)
  24. (:text (telegram-send-message chat-id (cdr response) :reply-to reply-id))
  25. (:voice (telegram-send-voice chat-id (cdr response) :reply-to reply-id))
  26. (:sticker (telegram-send-sticker chat-id (cdr response) :reply-to reply-id)))
  27. (mapc #'(lambda (r) (send-response chat-id r reply-id)) response))
  28. (telegram-send-message chat-id response :reply-to reply-id)))
  29. (defun send-dont-understand (chat-id &optional text reply-id)
  30. (let ((resp (eliza text)))
  31. (log:info text resp)
  32. (when resp
  33. (send-response chat-id resp reply-id))))
  34. (defvar *chat-locations* nil "ALIST of chat->location")
  35. (defun preprocess-input (text)
  36. (when text
  37. (let ((first-word (subseq text 0 (position #\Space text))))
  38. (if (equal first-word "@chatikbot")
  39. (preprocess-input (subseq text 11))
  40. (replace-all text "@chatikbot" "ты")))))
  41. (defun parse-cmd (text)
  42. (let* ((args (split-sequence:split-sequence #\Space (subseq text 1) :remove-empty-subseqs t))
  43. (cmd (subseq (car args) 0 (position #\@ (car args)))))
  44. (values (intern (string-upcase cmd) "KEYWORD") (rest args))))
  45. (defun handle-message (message)
  46. (let ((id (aget "message_id" message))
  47. (chat-id (aget "id" (aget "chat" message)))
  48. (text (aget "text" message))
  49. (location (aget "location" message))
  50. (sticker (aget "file_id" (aget "sticker" message))))
  51. (log:info "handle-message" message)
  52. (when text
  53. (if (equal #\/ (char text 0))
  54. (multiple-value-bind (cmd args) (parse-cmd text)
  55. (case cmd
  56. (:postakb (handle-cmd-post-akb chat-id id args))
  57. (:akb (handle-cmd-akb chat-id id args))
  58. (:weather (handle-cmd-weather chat-id id args))
  59. (:hourly (handle-cmd-weather chat-id id '("hourly")))
  60. (:daily (handle-cmd-weather chat-id id '("daily")))
  61. (:rates (handle-cmd-rates chat-id id args))
  62. (:charts (handle-cmd-charts chat-id id args))
  63. (:postcheckins (handle-cmd-post-checkins chat-id id args))
  64. (:friends (handle-cmd-fsq-friends chat-id id args))
  65. (:checkins (handle-cmd-checkins chat-id id args))
  66. (:rss (handle-cmd-rss chat-id id args))
  67. (:feeds (handle-cmd-feeds chat-id id args))
  68. (:lastrss (handle-cmd-last-rss chat-id id args))
  69. (:wall (handle-cmd-wall chat-id id args))
  70. (otherwise (handle-admin-cmd chat-id text cmd args))))
  71. (send-dont-understand chat-id (preprocess-input text))))
  72. (when location
  73. (push (cons chat-id location) *chat-locations*)
  74. (telegram-send-message chat-id "Взял на карандаш")
  75. (save-settings))
  76. (when sticker
  77. (send-dont-understand chat-id))))
  78. (defmacro handling-errors (&body body)
  79. `(handler-case (progn ,@body)
  80. (simple-condition (err)
  81. (format *error-output* "~&~A: ~%" (class-name (class-of err)))
  82. (apply (function format) *error-output*
  83. (simple-condition-format-control err)
  84. (simple-condition-format-arguments err))
  85. (format *error-output* "~&"))
  86. (condition (err)
  87. (format *error-output* "~&~A: ~% ~S~%"
  88. (class-name (class-of err)) err))))
  89. (defun rep (input)
  90. (when input
  91. (with-output-to-string (*standard-output*)
  92. (let ((*package* (find-package 'chatikbot))
  93. (*error-output* *standard-output*))
  94. (handling-errors
  95. (format t "~{~S~^ ;~% ~}~%"
  96. (multiple-value-list (eval (read-from-string input)))))))))
  97. (defun handle-admin-cmd (chat-id text cmd args)
  98. (if (find chat-id *admins*)
  99. (case cmd
  100. (:eval (telegram-send-message chat-id (rep (format nil "~{~A~^ ~}" args))))
  101. (otherwise (send-dont-understand chat-id (preprocess-input (subseq text 1)))))
  102. (send-dont-understand chat-id (preprocess-input (subseq text 1)))))
  103. ;; AKB
  104. (defparameter +akb-vk-domain+ "baneks" "VK.com username of 'B-category anekdotes'")
  105. (defvar *akb-send-to* nil "List of chat-id's to send AKBs to")
  106. (defun handle-cmd-post-akb (chat-id message-id args)
  107. (log:info "handle-cmd-post-akb" chat-id message-id args)
  108. (let ((message "Хуярим аники"))
  109. (if (member chat-id *akb-send-to*)
  110. (setf message "Не хуярим больше аники"
  111. *akb-send-to* (set-difference *akb-send-to*
  112. (list chat-id)))
  113. (setf *akb-send-to* (cons chat-id *akb-send-to*)))
  114. (telegram-send-message chat-id message)
  115. (save-settings)))
  116. (defvar *akb-max-count* 5 "Max number of tweets to return per run")
  117. (defvar *akb-last-id* 0 "id of last AKB tweet")
  118. (defun format-akb (post)
  119. (let* ((id (aget "id" post))
  120. (url (format nil "https://vk.com/~A?w=wall~A_~A"
  121. +akb-vk-domain+ (aget "from_id" post) id)))
  122. (format nil "~A~%~A" (aget "text" post) url)))
  123. (defun process-latest-akb ()
  124. (handler-case
  125. (dolist (post (reverse (aget "items" (vk-wall-get :domain +akb-vk-domain+
  126. :count *akb-max-count*))))
  127. (let ((id (aget "id" post)))
  128. (when (> id *akb-last-id*)
  129. (send-akb (format-akb post))
  130. (setf *akb-last-id* id)
  131. (save-settings))))
  132. (error (e) (log:error e))))
  133. (defun send-akb (text)
  134. (log:info "send-akb: ~A" text)
  135. (dolist (chat-id *akb-send-to*)
  136. (handler-case
  137. (telegram-send-message chat-id text
  138. :disable-web-preview 1)
  139. (error (e) (log:error e)))))
  140. (defun handle-cmd-akb (chat-id message-id args)
  141. (log:info "handle-cmd-akb" chat-id message-id args)
  142. (handler-case
  143. (progn
  144. (let ((total-aneks
  145. (aget "count" (vk-wall-get :domain +akb-vk-domain+ :count 1 :offset 10000000))))
  146. (dolist (post (aget "items" (vk-wall-get :domain +akb-vk-domain+
  147. :count (or (ignore-errors (parse-integer (car args))) 1)
  148. :offset (random total-aneks))))
  149. (handler-case
  150. (telegram-send-message chat-id
  151. (format-akb post)
  152. :disable-web-preview 1)
  153. (error (e) (log:error e))))))
  154. (error (e)
  155. (log:error e)
  156. (telegram-send-message chat-id "Ошибочка вышла"))))
  157. ;; Finance
  158. (defun process-rates ()
  159. (handler-case
  160. (let ((ts (local-time:timestamp-to-unix (local-time:now)))
  161. (rates (get-rates))
  162. (brent (get-brent))
  163. (btc (get-btc-e)))
  164. (db-add-finance ts (aget "USD/RUB" rates) (aget "EUR/RUB" rates) (aget "GBP/RUB" rates) brent btc))
  165. (error (e) (log:error e))))
  166. (defun handle-cmd-rates (chat-id message-id args)
  167. (log:info "handle-cmd-rates" chat-id message-id args)
  168. (multiple-value-bind (ts usd eur gbp brent btc) (db-get-last-finance)
  169. (telegram-send-message chat-id
  170. (format nil "Зеленый *~,2F*, гейро *~,2F*, британец *~,2F*, чёрная *~,2F*, btc *~,2F* @ _~A_"
  171. usd eur gbp brent btc
  172. (format-ts (local-time:unix-to-timestamp ts)))
  173. :parse-mode "Markdown")))
  174. (defparameter +chart-ranges+ (list (cons "day" (* 24 60))
  175. (cons "week" (* 7 24 60))
  176. (cons "month" (* 30 24 60))
  177. (cons "quarter" (* 91 24 60))
  178. (cons "year" (* 365 24 60))))
  179. (defun handle-cmd-charts (chat-id message-id args)
  180. (log:info "handle-cmd-charts" chat-id message-id args)
  181. (telegram-send-chat-action chat-id "upload_photo")
  182. (handler-case
  183. (let* ((args (mapcar 'string-downcase args))
  184. (all-fields (mapcar #'car +db-finance-map+))
  185. (fields (or (intersection args all-fields :test 'equal) all-fields))
  186. (day-range (some #'(lambda (a) (aget a +chart-ranges+)) args))
  187. (number (some #'(lambda (a) (parse-integer a :junk-allowed t)) args))
  188. (avg (* 60 (cond
  189. (day-range (round day-range *chart-points*))
  190. (number)
  191. (:otherwise 1))))
  192. (after-ts (local-time:timestamp- (local-time:now)
  193. (* avg *chart-points*) :sec))
  194. (rates (multiple-value-list (db-get-last-finance)))
  195. (chart (apply #'make-chart (multiple-value-list
  196. (db-get-series after-ts fields avg)))))
  197. (telegram-send-photo chat-id chart
  198. :caption
  199. (format nil "Зеленый ~,2F, гейро ~,2F, британец ~,2F, чёрная ~,2F, btc ~,2F @ ~A"
  200. (elt rates 1) (elt rates 2) (elt rates 3) (elt rates 4) (elt rates 5)
  201. (format-ts (local-time:unix-to-timestamp (elt rates 0))))))
  202. (error (e)
  203. (log:error e)
  204. (telegram-send-message chat-id "Хуйня какая-то"))))
  205. ;; Weather
  206. (defun handle-cmd-weather (chat-id message-id args)
  207. (log:info "handle-cmd-weather" chat-id message-id args)
  208. (let ((location (cdr (assoc chat-id *chat-locations*))))
  209. (telegram-send-message
  210. chat-id
  211. (if location
  212. (handler-case
  213. (forecast-format (forecast
  214. (aget "latitude" location)
  215. (aget "longitude" location)
  216. :hourly (find "hourly" args :key #'string-downcase :test #'equal)
  217. :daily (find "daily" args :key #'string-downcase :test #'equal)))
  218. (error (e)
  219. (log:error e)
  220. "Ошибочка вышла"))
  221. "Так а ты чьих будешь?"))))
  222. ;; Foursquare
  223. (defun fsq-user-name (user)
  224. (when user
  225. (format nil "~@[~A~]~@[ ~A~]"
  226. (aget "firstName" user)
  227. (aget "lastName" user))))
  228. (defun handle-cmd-post-checkins (chat-id message-id args)
  229. (log:info "handle-cmd-post-checkins" chat-id message-id args)
  230. (handler-case
  231. (let ((users (db-fsq-get-chat-users chat-id))
  232. (friends (fsq-fetch-friends)))
  233. (if (null args)
  234. (telegram-send-message chat-id
  235. (if (null users)
  236. "Пока никого не палим"
  237. (format nil "Палим ~{~A~^, ~}"
  238. (loop for user in friends
  239. when (member (aget "id" user)
  240. users :test #'equal)
  241. collect (fsq-user-name user)))))
  242. (progn
  243. (dolist (user args)
  244. (let ((username (fsq-user-name
  245. (find user friends
  246. :test #'equal
  247. :key #'(lambda (f) (aget "id" f))))))
  248. (when username
  249. (if (member user users :test #'equal)
  250. (progn
  251. (setf users (remove user users :test #'equal))
  252. (telegram-send-message chat-id
  253. (format nil "Больше не палим ~A" username)))
  254. (progn
  255. (push user users)
  256. (telegram-send-message chat-id (format nil "Теперь палим ~A" username)))))))
  257. (db-fsq-set-chat-users chat-id users))))
  258. (error (e)
  259. (log:error e)
  260. (telegram-send-message chat-id "Ошибочка вышла"))))
  261. (defun handle-cmd-fsq-friends (chat-id message-id args)
  262. (log:info "handle-cmd-fsq-friends" chat-id message-id args)
  263. (handler-case
  264. (let ((users (db-fsq-get-chat-users chat-id))
  265. (friends (fsq-fetch-friends)))
  266. (telegram-send-message
  267. chat-id
  268. (format
  269. nil "~{~A: ~:[~;📍 ~]~A~^~%~}"
  270. (loop for user in friends
  271. append (list
  272. (aget "id" user)
  273. (member (aget "id" user) users :test #'equal)
  274. (fsq-user-name user))))))
  275. (error (e) (log:error e))))
  276. (defun handle-cmd-checkins (chat-id message-id args)
  277. (log:info "handle-cmd-checkins" chat-id message-id args)
  278. (handler-case
  279. (let ((users (db-fsq-get-chat-users chat-id)))
  280. (when users
  281. (telegram-send-message
  282. chat-id
  283. (format nil "~{~A~^~%~}"
  284. (loop for checkin in (fsq-fetch-checkins)
  285. if (member (aget "id" (aget "user" checkin)) users :test #'equal)
  286. collect (fsq-format-checkin checkin t))))))
  287. (error (e) (log:error e))))
  288. (defun process-latest-checkins ()
  289. (handler-case
  290. (let ((checkins (make-hash-table))
  291. (ts (princ-to-string (1+ (or (db-fsq-last-created) -1)))))
  292. (dolist (checkin (fsq-fetch-checkins ts))
  293. (let ((id (aget "id" checkin))
  294. (created-at (aget "createdAt" checkin))
  295. (user (aget "id" (aget "user" checkin))))
  296. (unless (db-fsq-has-seen id)
  297. (dolist (chat-id (db-fsq-get-user-chats user))
  298. (push (fsq-format-checkin checkin)
  299. (gethash chat-id checkins)))
  300. (db-fsq-add-seen id created-at))))
  301. (loop for chat-id being the hash-keys in checkins using (hash-value texts)
  302. do (log:info "Sending checkins" chat-id texts)
  303. (telegram-send-message chat-id (format nil "~{~A~^~%~}" texts))))
  304. (error (e) (log:error e))))
  305. ;; RSS
  306. (defun handle-cmd-feeds (chat-id message-id args)
  307. (log:info "handle-cmd-feeds" chat-id message-id args)
  308. (handler-case
  309. (telegram-send-message
  310. chat-id
  311. (if (null args)
  312. "URL давай"
  313. (format nil "~:[Не нашел RSS там~;~:*~{~{~A - ~A~}~^~%~}~]"
  314. (find-rss-links (car args))))
  315. :disable-web-preview 1)
  316. (error (e)
  317. (log:error e)
  318. (telegram-send-message chat-id "Ошибочка вышла"))))
  319. (defun %send-feeds (chat-id feeds)
  320. (telegram-send-message
  321. chat-id
  322. (if (null feeds)
  323. "Пока ничего не постим"
  324. (format nil "Постим~%~{~A) ~A: ~A~^~%~}"
  325. (loop for feed in feeds
  326. for index from 1
  327. append (list index (feed-title feed) (feed-url feed)))))
  328. :disable-web-preview 1))
  329. (defun %fetch-new-items (feed)
  330. (loop for item in (refresh-feed feed #'db-rss-item-exists)
  331. do (db-rss-add-item item)
  332. collect item))
  333. (defun %get-feed (url)
  334. (when url
  335. (or (db-rss-get-feed-by-url url)
  336. (alexandria:when-let (feed (build-feed url))
  337. (log:info "Added feed" feed)
  338. (db-rss-add-feed feed)
  339. (%fetch-new-items feed)
  340. feed))))
  341. (defun handle-cmd-rss (chat-id message-id args)
  342. (log:info "handle-cmd-rss" chat-id message-id args)
  343. (handler-case
  344. (let ((feeds (db-rss-get-chat-feeds chat-id)))
  345. (if (null args)
  346. (%send-feeds chat-id feeds)
  347. (progn
  348. (dolist (url args)
  349. (handler-case
  350. (let ((idx (parse-integer url)))
  351. (when (<= idx (length feeds))
  352. (setf feeds (remove (nth (1- idx) feeds) feeds))))
  353. (parse-error ()
  354. (alexandria:when-let (feed (%get-feed
  355. (or (cadar (find-rss-links url))
  356. url)))
  357. (let ((existing (find (feed-url feed) feeds :key #'feed-url :test #'equal)))
  358. (if existing
  359. (setf feeds (remove existing feeds))
  360. (push feed feeds)))))
  361. (error (e) (log:error e))))
  362. (log:info feeds)
  363. (db-rss-set-chat-feeds chat-id feeds)
  364. (%send-feeds chat-id (db-rss-get-chat-feeds chat-id)))))
  365. (error (e)
  366. (log:error e)
  367. (telegram-send-message chat-id "Ошибочка вышла"))))
  368. (defun handle-cmd-last-rss (chat-id message-id args)
  369. (log:info "handle-cmd-last-rss" chat-id message-id args)
  370. (handler-case
  371. (let ((feeds (db-rss-get-chat-feeds chat-id)))
  372. (if (null args)
  373. (%send-feeds chat-id feeds)
  374. (let* ((idx (1- (parse-integer (car args))))
  375. (limit (min 20 (if (> (length args) 1) (parse-integer (second args)) 5)))
  376. (items (db-rss-last-feed-items (nth idx feeds) limit)))
  377. (telegram-send-message chat-id
  378. (format nil "~{~A~^~%~%~}"
  379. (mapcar #'format-feed-item items))
  380. :parse-mode "Markdown"
  381. :disable-web-preview 1))))
  382. (error (e)
  383. (log:error e)
  384. (telegram-send-message chat-id "Ошибочка вышла"))))
  385. (defun process-feeds ()
  386. (handler-case
  387. (dolist (feed (remove-if-not #'need-fetch-p (db-rss-get-active-feeds)))
  388. (log:info "Fetching new items" (feed-url feed))
  389. (dolist (item (%fetch-new-items feed))
  390. (dolist (chat-id (db-rss-get-feed-chats feed))
  391. (telegram-send-message chat-id
  392. (format-feed-item item)
  393. :parse-mode "Markdown"
  394. :disable-web-preview 1)))
  395. (db-rss-update-feed feed)) ;; Update next fetch and period
  396. (error (e) (log:error e))))
  397. ;; VK walls
  398. (defun %send-domains (chat-id domains)
  399. (telegram-send-message
  400. chat-id
  401. (if (null domains)
  402. "Пока ничего не постим"
  403. (format nil "Постим~%~{~A) https://vk.com/~A~^~%~}"
  404. (loop for d in domains for i from 1 append (list i d))))
  405. :disable-web-preview 1))
  406. (defun %find-vk-domain (url)
  407. (let ((path (puri:uri-path (puri:parse-uri url))))
  408. (if (equal #\/ (elt path 0))
  409. (subseq path 1)
  410. path)))
  411. (defun %ensure-domain (domain)
  412. (let* ((res (vk-wall-get :domain domain :count 1))
  413. (last-id (aget "id" (first (aget "items" res)))))
  414. (db-vk-ensure-domain domain last-id)
  415. domain))
  416. (defun %vk-find-best-photo (attach)
  417. (when attach
  418. (let* ((photo (aget "photo" attach))
  419. (sizes (loop for (k . v) in photo
  420. when (equal "photo_" (subseq k 0 (min 6 (length k))))
  421. collect (cons (parse-integer (subseq k 6)) v))))
  422. (cdr (assoc (apply #'max (mapcar #'car sizes)) sizes)))))
  423. (defun %vk-find-picture (attachments)
  424. (%vk-find-best-photo (find "photo" attachments :key #'(lambda (a) (aget "type" a)) :test #'equal)))
  425. (defparameter +vk-link-scanner+ (cl-ppcre:create-scanner "\\[((id|club)\\d+)\\|([^\\]]*?)\\]") "vk linking regex")
  426. (defun %vk-post-text (post)
  427. (let* ((history (aget "copy_history" post))
  428. (reposts (loop for p in history
  429. collect (let* ((owner (aget "owner_id" p))
  430. (type (if (> owner 0) "id" "club"))
  431. (id (abs owner)))
  432. (format nil "[~A](https://vk.com/~A~A)"
  433. (vk-get-name owner) type id)))))
  434. (when history
  435. (setf post (car (last history))))
  436. (values
  437. (cl-ppcre:regex-replace-all +vk-link-scanner+
  438. (aget "text" post)
  439. "[\\3](https://vk.com/\\1)")
  440. (%vk-find-picture (aget "attachments" post))
  441. reposts)))
  442. (defun %format-wall-post (domain name post)
  443. (multiple-value-bind (text preview reposts) (%vk-post-text post)
  444. (values
  445. (format nil "~@[[✅](~A)~] [~A](https://vk.com/~A?w=wall~A_~A)~@[ ~{↩ ~A~}~]~@[ @ ~A~]~%~A"
  446. preview name domain (aget "from_id" post) (aget "id" post)
  447. reposts (format-ts (local-time:unix-to-timestamp (aget "date" post)))
  448. text)
  449. (if preview 0 1))))
  450. (defun handle-cmd-wall (chat-id message-id args)
  451. (log:info "handle-cmd-wall" chat-id message-id args)
  452. (handler-case
  453. (let ((domains (db-vk-get-chat-domains chat-id)))
  454. (if (null args)
  455. (%send-domains chat-id domains)
  456. (progn
  457. (dolist (url args)
  458. (handler-case
  459. (let ((idx (parse-integer url)))
  460. (db-vk-remove-chat-domain chat-id (nth (1- idx) domains)))
  461. (parse-error ()
  462. (let* ((domain (%ensure-domain (%find-vk-domain url)))
  463. (existing (find domain domains :test #'equal)))
  464. (if existing
  465. (db-vk-remove-chat-domain chat-id domain)
  466. (db-vk-add-chat-domain chat-id domain))))
  467. (error (e) (log:error e))))
  468. (%send-domains chat-id (db-vk-get-chat-domains chat-id)))))
  469. (error (e)
  470. (log:error e)
  471. (telegram-send-message chat-id (format nil "Ошибочка вышла: ~A" e)))))
  472. (defun process-walls ()
  473. (handler-case
  474. (loop for (domain last-id next-fetch period) in (db-vk-get-active-walls)
  475. when (or (null next-fetch)
  476. (local-time:timestamp> (local-time:now) (local-time:unix-to-timestamp next-fetch)))
  477. do (progn
  478. (log:info "Fetching wall" domain)
  479. (handler-case
  480. (let ((new-posts
  481. (remove last-id (reverse (aget "items" (vk-wall-get :domain domain)))
  482. :test #'>= :key (lambda (p) (aget "id" p))))
  483. name)
  484. (setf period (adjust-period period (length new-posts)))
  485. (when new-posts
  486. (setf name (vk-get-name domain)))
  487. (dolist (post new-posts)
  488. (multiple-value-bind (text disable)
  489. (%format-wall-post domain name post)
  490. (dolist (chat-id (db-vk-get-domain-chats domain))
  491. (ignore-errors
  492. (telegram-send-message chat-id text
  493. :parse-mode "Markdown"
  494. :disable-web-preview disable))))
  495. (setf last-id (max last-id (aget "id" post)))))
  496. (error (e) (log:error e)))
  497. (db-vk-update-wall domain last-id
  498. (local-time:timestamp-to-unix
  499. (local-time:timestamp+ (local-time:now) period :sec))
  500. period))) ;; Update last-id, next-fetch and period
  501. (error (e) (log:error e))))
  502. (defvar *save-settings-lock* (bordeaux-threads:make-lock "save-settings-lock")
  503. "Lock for multithreading access to write settings file")
  504. (defun save-settings()
  505. (bordeaux-threads:with-lock-held (*save-settings-lock*)
  506. (with-open-file (s (merge-pathnames "settings.lisp"
  507. (asdf:component-pathname
  508. (asdf:find-system '#:chatikbot)))
  509. :direction :output
  510. :if-exists :supersede
  511. :if-does-not-exist :create)
  512. (write '(in-package #:chatikbot) :stream s)
  513. (write
  514. `(setf *chat-locations* ',*chat-locations*
  515. *akb-send-to* ',*akb-send-to*
  516. *akb-last-id* ,*akb-last-id*)
  517. :stream s)
  518. (values))))
  519. (defvar *schedules* '(process-latest-akb
  520. process-latest-checkins
  521. process-rates
  522. process-feeds
  523. process-walls) "Enabled schedules")
  524. (defun start ()
  525. ;; Clear prev threads
  526. (mapc #'trivial-timers:unschedule-timer (trivial-timers:list-all-timers))
  527. (let ((old-updates (find "process-updates"
  528. (bordeaux-threads:all-threads)
  529. :key #'bordeaux-threads:thread-name
  530. :test #'equal)))
  531. (when old-updates
  532. (bordeaux-threads:destroy-thread old-updates)))
  533. ;; Load settings file
  534. (alexandria:when-let (file (probe-file
  535. (merge-pathnames "settings.lisp"
  536. (asdf:component-pathname
  537. (asdf:find-system '#:chatikbot)))))
  538. (load file))
  539. ;; Start timers
  540. (dolist (func *schedules*)
  541. (clon:schedule-function func
  542. (clon:make-scheduler
  543. (clon:make-typed-cron-schedule :minute '* :hour '*)
  544. :allow-now-p t)
  545. :name func
  546. :thread t))
  547. ;; Start getUpdates thread
  548. (bordeaux-threads:make-thread
  549. (lambda () (loop-with-error-backoff #'process-updates))
  550. :name "process-updates"))