1
0

chatikbot.lisp 28 KB

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