chatikbot.lisp 20 KB

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