chatikbot.lisp 20 KB

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