1
0

chatikbot.lisp 19 KB

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