1
0

chatikbot.lisp 28 KB

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