1
0

chatikbot.lisp 20 KB

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