1
0

chatikbot.lisp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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. (: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 handle-message (message)
  41. (let ((id (aget "message_id" message))
  42. (chat-id (aget "id" (aget "chat" message)))
  43. (text (aget "text" message))
  44. (location (aget "location" message))
  45. (sticker (aget "file_id" (aget "sticker" message))))
  46. (log:info "handle-message" message)
  47. (when text
  48. (if (equal #\/ (char text 0))
  49. (let ((cmd (intern (string-upcase
  50. (subseq text 1 (position #\Space text)))
  51. "KEYWORD"))
  52. (args (when (position #\Space text)
  53. (split-sequence:split-sequence
  54. #\Space (subseq text (1+ (position #\Space 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. (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. (handler-case
  135. (telegram-send-message chat-id text
  136. :disable-web-preview 1)
  137. (error (e) (log:error e)))))
  138. (defun handle-cmd-akb (chat-id message-id args)
  139. (log:info "handle-cmd-akb" chat-id message-id args)
  140. (handler-case
  141. (progn
  142. (let ((total-aneks
  143. (aget "count" (vk-wall-get :domain +akb-vk-domain+ :count 1 :offset 10000000))))
  144. (dolist (post (aget "items" (vk-wall-get :domain +akb-vk-domain+
  145. :count (or (ignore-errors (parse-integer (car args))) 1)
  146. :offset (random total-aneks))))
  147. (handler-case
  148. (telegram-send-message chat-id
  149. (format-akb post)
  150. :disable-web-preview 1)
  151. (error (e) (log:error e))))))
  152. (error (e)
  153. (log:error e)
  154. (telegram-send-message chat-id "Ошибочка вышла"))))
  155. ;; Finance
  156. (defun process-rates ()
  157. (handler-case
  158. (let ((ts (local-time:timestamp-to-unix (local-time:now)))
  159. (rates (get-rates))
  160. (brent (get-brent)))
  161. (db-add-finance ts
  162. (aget "USD/RUB" rates)
  163. (aget "EUR/RUB" rates)
  164. (aget "GBP/RUB" rates)
  165. brent))
  166. (error (e) (log:error 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) (db-get-last-finance)
  170. (telegram-send-message chat-id
  171. (format nil "Зеленый ~,2F, гейро ~,2F, британец ~,2F, чёрная ~,2F @ ~A"
  172. usd eur gbp brent
  173. (format-ts (local-time:unix-to-timestamp ts))))))
  174. (defun handle-cmd-charts (chat-id message-id args)
  175. (log:info "handle-cmd-charts" chat-id message-id args)
  176. (telegram-send-chat-action chat-id "upload_photo")
  177. (handler-case
  178. (let* ((usd (or (null args) (find "usd" args :test #'equal)))
  179. (eur (or (null args) (find "eur" args :test #'equal)))
  180. (gbp (or (null args) (find "gbp" args :test #'equal)))
  181. (brent (or (null args) (find "brent" args :test #'equal)))
  182. (rates (multiple-value-list (db-get-last-finance))))
  183. (if (or usd eur gbp brent)
  184. (let ((data (db-get-series
  185. (local-time:timestamp- (local-time:now) 1 :day)
  186. usd eur gbp brent)))
  187. (telegram-send-photo chat-id
  188. (make-chart data :usd usd :eur eur :gbp gbp :brent brent)
  189. :caption
  190. (format nil "Зеленый ~,2F, гейро ~,2F, британец ~,2F, чёрная ~,2F @ ~A"
  191. (elt rates 1) (elt rates 2) (elt rates 3) (elt rates 4)
  192. (format-ts (local-time:unix-to-timestamp (elt rates 0))))))
  193. (telegram-send-message chat-id "Хуй тебе")))
  194. (error (e)
  195. (log:error e)
  196. (telegram-send-message chat-id "Хуйня какая-то"))))
  197. ;; Weather
  198. (defun handle-cmd-weather (chat-id message-id args)
  199. (log:info "handle-cmd-weather" chat-id message-id args)
  200. (let ((location (cdr (assoc chat-id *chat-locations*))))
  201. (telegram-send-message
  202. chat-id
  203. (if location
  204. (handler-case
  205. (forecast-format (forecast
  206. (aget "latitude" location)
  207. (aget "longitude" location)
  208. :hourly (find "hourly" args :key #'string-downcase :test #'equal)
  209. :daily (find "daily" args :key #'string-downcase :test #'equal)))
  210. (error (e)
  211. (log:error e)
  212. "Ошибочка вышла"))
  213. "Так а ты чьих будешь?"))))
  214. ;; Foursquare
  215. (defvar *fsq-send-to* (make-hash-table)
  216. "Hash of chat-id's to fsq users list to send checkings to")
  217. (defun fsq-user-name (user)
  218. (when user
  219. (format nil "~@[~A~]~@[ ~A~]"
  220. (aget "firstName" user)
  221. (aget "lastName" user))))
  222. (defun handle-cmd-post-checkins (chat-id message-id args)
  223. (log:info "handle-cmd-post-checkins" chat-id message-id args)
  224. (handler-case
  225. (let ((users (gethash chat-id *fsq-send-to*))
  226. (friends (fsq-fetch-friends)))
  227. (if (null args)
  228. (telegram-send-message chat-id
  229. (if (null users)
  230. "Пока никого не палим"
  231. (format nil "Палим ~{~A~^, ~}"
  232. (loop for user in friends
  233. when (member (aget "id" user)
  234. users :test #'equal)
  235. collect (fsq-user-name user)))))
  236. (progn
  237. (dolist (user args)
  238. (let ((username (fsq-user-name
  239. (find user friends
  240. :test #'equal
  241. :key #'(lambda (f) (aget "id" f))))))
  242. (when username
  243. (if (member user users :test #'equal)
  244. (progn
  245. (setf users (remove user users :test #'equal))
  246. (telegram-send-message chat-id
  247. (format nil "Больше не палим ~A" username)))
  248. (progn
  249. (push user users)
  250. (telegram-send-message chat-id (format nil "Теперь палим ~A" username)))))))
  251. (setf (gethash chat-id *fsq-send-to*) users)
  252. (save-settings))))
  253. (error (e)
  254. (log:error e)
  255. (telegram-send-message chat-id "Ошибочка вышла"))))
  256. (defun handle-cmd-fsq-friends (chat-id message-id args)
  257. (log:info "handle-cmd-fsq-friends" chat-id message-id args)
  258. (handler-case
  259. (let ((users (gethash chat-id *fsq-send-to*))
  260. (friends (fsq-fetch-friends)))
  261. (telegram-send-message
  262. chat-id
  263. (format
  264. nil "~{~A: ~:[~;📍 ~]~A~^~%~}"
  265. (loop for user in friends
  266. append (list
  267. (aget "id" user)
  268. (member (aget "id" user) users :test #'equal)
  269. (fsq-user-name user))))))
  270. (error (e) (log:error e))))
  271. (defun handle-cmd-checkins (chat-id message-id args)
  272. (log:info "handle-cmd-checkins" chat-id message-id args)
  273. (handler-case
  274. (let ((users (gethash chat-id *fsq-send-to*)))
  275. (when users
  276. (telegram-send-message
  277. chat-id
  278. (format nil "~{~A~^~%~}"
  279. (loop for checkin in (fsq-fetch-checkins)
  280. if (member (aget "id" (aget "user" checkin)) users :test #'equal)
  281. collect (fsq-format-checkin checkin t))))))
  282. (error (e) (log:error e))))
  283. (defvar *fsq-seen-ids* nil "Ids of seen checkins")
  284. (defun process-latest-checkins ()
  285. (handler-case
  286. (let ((checkins (make-hash-table)))
  287. (dolist (checkin (fsq-fetch-new-checkins))
  288. (let ((id (aget "id" checkin))
  289. (user (aget "id" (aget "user" checkin))))
  290. (unless (find id *fsq-seen-ids* :test #'equal)
  291. (loop for chat-id being the hash-keys in *fsq-send-to* using (hash-value users)
  292. do (when (member user users :test #'equal)
  293. (push (fsq-format-checkin checkin)
  294. (gethash chat-id checkins))))
  295. (push id *fsq-seen-ids*))))
  296. (loop for chat-id being the hash-keys in checkins using (hash-value texts)
  297. do (log:info "Sending checkins" chat-id texts)
  298. (telegram-send-message chat-id (format nil "~{~A~^~%~}" texts))))
  299. (error (e) (log:error e))))
  300. ;; RSS
  301. (defvar *rss-feeds* nil "All aggragated RSS feeds")
  302. (defvar *rss-chat-feeds* (make-hash-table) "Chat->Feeds mapping")
  303. (defun %send-feeds (chat-id feeds)
  304. (telegram-send-message
  305. chat-id
  306. (if (null feeds)
  307. "Пока ничего не постим"
  308. (format nil "Постим~%~{~A) ~A: ~A~^~%~}"
  309. (loop for feed in feeds
  310. for index from 1
  311. append (list index (feed-title feed) (feed-url feed)))))
  312. :disable-web-preview 1))
  313. (defun %get-feed (url)
  314. (when url
  315. (or (find url *rss-feeds* :key #'feed-url :test #'equal)
  316. (alexandria:when-let (feed (build-feed url))
  317. (log:info "Added feed" feed)
  318. (fetch-new-items feed)
  319. (push feed *rss-feeds*)
  320. feed))))
  321. (defun %used-feed-p (feed)
  322. (loop for feeds being the hash-values in *rss-chat-feeds*
  323. when (member feed feeds)
  324. do (return t)))
  325. (defun %refresh-feeds ()
  326. (setf *rss-feeds*
  327. (remove-if-not #'%used-feed-p *rss-feeds*)))
  328. (defun handle-cmd-feeds (chat-id message-id args)
  329. (log:info "handle-cmd-feeds" chat-id message-id args)
  330. (handler-case
  331. (telegram-send-message
  332. chat-id
  333. (if (null args)
  334. "URL давай"
  335. (format nil "~:[Не нашел RSS там~;~:*~{~{~A - ~A~}~^~%~}~]"
  336. (find-rss-links (car args))))
  337. :disable-web-preview 1)
  338. (error (e)
  339. (log:error e)
  340. (telegram-send-message chat-id "Ошибочка вышла"))))
  341. (defun handle-cmd-rss (chat-id message-id args)
  342. (log:info "handle-cmd-rss" chat-id message-id args)
  343. (handler-case
  344. (let ((feeds (gethash chat-id *rss-chat-feeds*)))
  345. (if (null args)
  346. (%send-feeds chat-id feeds)
  347. (progn
  348. (dolist (url args)
  349. (handler-case
  350. (let ((idx (parse-integer url)))
  351. (when (<= idx (length feeds))
  352. (setf feeds (remove (nth (1- idx) feeds) feeds))))
  353. (parse-error ()
  354. (alexandria:when-let (feed (%get-feed
  355. (or (cadar (find-rss-links url))
  356. url)))
  357. (if (member feed feeds)
  358. (setf feeds (remove feed feeds))
  359. (push feed feeds))))
  360. (error (e) (log:error e))))
  361. (setf (gethash chat-id *rss-chat-feeds*) feeds)
  362. (%refresh-feeds)
  363. (save-settings)
  364. (%send-feeds chat-id feeds))))
  365. (error (e)
  366. (log:error e)
  367. (telegram-send-message chat-id "Ошибочка вышла"))))
  368. (defun %feed-send-to (feed)
  369. (loop for chat-id being the hash-keys in *rss-chat-feeds* using (hash-value feeds)
  370. when (member feed feeds)
  371. collect chat-id))
  372. (defun process-feeds ()
  373. (handler-case
  374. (dolist (feed (remove-if-not #'need-fetch-p *rss-feeds*))
  375. (log:info "Fetching new items" (feed-url feed))
  376. (dolist (item (fetch-new-items feed))
  377. (dolist (chat-id (%feed-send-to feed))
  378. (telegram-send-message chat-id
  379. (format-feed-item feed item)
  380. :disable-web-preview 1))))
  381. (error (e) (log:error e))))
  382. (defun %load-rss-feeds (alist)
  383. (alexandria:alist-hash-table
  384. (loop for (chat-id . urls) in alist
  385. collect (cons chat-id (mapcar #'%get-feed urls)))))
  386. (defun %save-rss-feeds ()
  387. (loop for chat-id being the hash-keys in *rss-chat-feeds* using (hash-value feeds)
  388. collect (cons chat-id (mapcar #'feed-url feeds))))
  389. (defvar *save-settings-lock* (bordeaux-threads:make-lock "save-settings-lock")
  390. "Lock for multithreading access to write settings file")
  391. (defun save-settings()
  392. (bordeaux-threads:with-lock-held (*save-settings-lock*)
  393. (with-open-file (s (merge-pathnames "settings.lisp"
  394. (asdf:component-pathname
  395. (asdf:find-system '#:chatikbot)))
  396. :direction :output
  397. :if-exists :supersede
  398. :if-does-not-exist :create)
  399. (write '(in-package #:chatikbot) :stream s)
  400. (write
  401. `(setf *fsq-send-to* (alexandria:alist-hash-table ',(alexandria:hash-table-alist *fsq-send-to*))
  402. *chat-locations* ',*chat-locations*
  403. *akb-send-to* ',*akb-send-to*
  404. *akb-last-id* ,*akb-last-id*
  405. *rss-chat-feeds* (%load-rss-feeds ',(%save-rss-feeds)))
  406. :stream s)
  407. (values))))
  408. (defun start ()
  409. ;; Clear prev threads
  410. (mapc #'trivial-timers:unschedule-timer (trivial-timers:list-all-timers))
  411. (let ((old-updates (find "process-updates"
  412. (bordeaux-threads:all-threads)
  413. :key #'bordeaux-threads:thread-name
  414. :test #'equal)))
  415. (when old-updates
  416. (bordeaux-threads:destroy-thread old-updates)))
  417. ;; Load settings file
  418. (alexandria:when-let (file (probe-file
  419. (merge-pathnames "settings.lisp"
  420. (asdf:component-pathname
  421. (asdf:find-system '#:chatikbot)))))
  422. (load file))
  423. ;; Start timers
  424. (clon:schedule-function
  425. (lambda () (process-latest-akb))
  426. (clon:make-scheduler
  427. (clon:make-typed-cron-schedule :minute '* :hour '*)
  428. :allow-now-p t)
  429. :name 'process-latest-akb
  430. :thread t)
  431. (clon:schedule-function
  432. (lambda () (process-latest-checkins))
  433. (clon:make-scheduler
  434. (clon:make-typed-cron-schedule :minute '* :hour '*)
  435. :allow-now-p t)
  436. :name 'process-latest-checkins
  437. :thread t)
  438. (clon:schedule-function
  439. (lambda () (process-rates))
  440. (clon:make-scheduler
  441. (clon:make-typed-cron-schedule :minute '* :hour '*)
  442. :allow-now-p t)
  443. :name 'process-rates
  444. :thread t)
  445. (clon:schedule-function
  446. (lambda () (process-feeds))
  447. (clon:make-scheduler
  448. (clon:make-typed-cron-schedule :minute '* :hour '*)
  449. :allow-now-p t)
  450. :name 'process-feeds
  451. :thread t)
  452. ;; Start getUpdates thread
  453. (bordeaux-threads:make-thread
  454. (lambda ()
  455. (in-package #:chatikbot)
  456. (loop-with-error-backoff #'process-updates))
  457. :name "process-updates"))