chatikbot.lisp 21 KB

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