1
0

chatikbot.lisp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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. (otherwise (handle-admin-cmd chat-id text cmd args))))
  65. (send-dont-understand chat-id (preprocess-input text))))
  66. (when location
  67. (push (cons chat-id location) *chat-locations*)
  68. (telegram-send-message chat-id "Взял на карандаш")
  69. (save-settings))
  70. (when sticker
  71. (send-dont-understand chat-id))))
  72. (defmacro handling-errors (&body body)
  73. `(handler-case (progn ,@body)
  74. (simple-condition (err)
  75. (format *error-output* "~&~A: ~%" (class-name (class-of err)))
  76. (apply (function format) *error-output*
  77. (simple-condition-format-control err)
  78. (simple-condition-format-arguments err))
  79. (format *error-output* "~&"))
  80. (condition (err)
  81. (format *error-output* "~&~A: ~% ~S~%"
  82. (class-name (class-of err)) err))))
  83. (defun rep (input)
  84. (when input
  85. (with-output-to-string (*standard-output*)
  86. (let ((*package* (find-package 'chatikbot))
  87. (*error-output* *standard-output*))
  88. (handling-errors
  89. (format t "~{~S~^ ;~% ~}~%"
  90. (multiple-value-list (eval (read-from-string input)))))))))
  91. (defun handle-admin-cmd (chat-id text cmd args)
  92. (if (find chat-id *admins*)
  93. (case cmd
  94. (:eval (telegram-send-message chat-id (rep (format nil "~{~A~^ ~}" args))))
  95. (otherwise (send-dont-understand chat-id (preprocess-input (subseq text 1)))))
  96. (send-dont-understand chat-id (preprocess-input (subseq text 1)))))
  97. ;; AKB
  98. (defparameter +akb-vk-domain+ "baneks" "VK.com username of 'B-category anekdotes'")
  99. (defvar *akb-send-to* nil "List of chat-id's to send AKBs to")
  100. (defun handle-cmd-post-akb (chat-id message-id args)
  101. (log:info "handle-cmd-post-akb" chat-id message-id args)
  102. (let ((message "Хуярим аники"))
  103. (if (member chat-id *akb-send-to*)
  104. (setf message "Не хуярим больше аники"
  105. *akb-send-to* (set-difference *akb-send-to*
  106. (list chat-id)))
  107. (setf *akb-send-to* (cons chat-id *akb-send-to*)))
  108. (telegram-send-message chat-id message)
  109. (save-settings)))
  110. (defvar *akb-max-count* 5 "Max number of tweets to return per run")
  111. (defvar *akb-last-id* 0 "id of last AKB tweet")
  112. (defun format-akb (post)
  113. (let* ((id (aget "id" post))
  114. (url (format nil "https://vk.com/~A?w=wall~A_~A"
  115. +akb-vk-domain+ (aget "from_id" post) id)))
  116. (format nil "~A~%~A" (aget "text" post) url)))
  117. (defun process-latest-akb ()
  118. (handler-case
  119. (dolist (post (reverse (aget "items" (vk-wall-get :domain +akb-vk-domain+
  120. :count *akb-max-count*))))
  121. (let ((id (aget "id" post)))
  122. (when (> id *akb-last-id*)
  123. (send-akb (format-akb post))
  124. (setf *akb-last-id* id)
  125. (save-settings))))
  126. (error (e) (log:error e))))
  127. (defun send-akb (text)
  128. (log:info "send-akb: ~A" text)
  129. (dolist (chat-id *akb-send-to*)
  130. (handler-case
  131. (telegram-send-message chat-id text
  132. :disable-web-preview 1)
  133. (error (e) (log:error e)))))
  134. (defun handle-cmd-akb (chat-id message-id args)
  135. (log:info "handle-cmd-akb" chat-id message-id args)
  136. (handler-case
  137. (progn
  138. (let ((total-aneks
  139. (aget "count" (vk-wall-get :domain +akb-vk-domain+ :count 1 :offset 10000000))))
  140. (dolist (post (aget "items" (vk-wall-get :domain +akb-vk-domain+
  141. :count (or (ignore-errors (parse-integer (car args))) 1)
  142. :offset (random total-aneks))))
  143. (handler-case
  144. (telegram-send-message chat-id
  145. (format-akb post)
  146. :disable-web-preview 1)
  147. (error (e) (log:error e))))))
  148. (error (e)
  149. (log:error e)
  150. (telegram-send-message chat-id "Ошибочка вышла"))))
  151. ;; Finance
  152. (defvar *per-minute-rates* (make-circular (make-list 1440))
  153. "Circular list for 24h per minute rates")
  154. (defun process-rates ()
  155. (handler-case
  156. (push-circular (cons (local-time:timestamp-to-unix (local-time:now))
  157. (get-rates))
  158. *per-minute-rates*)
  159. (error (e) (log:error e))))
  160. (defun handle-cmd-rates (chat-id message-id args)
  161. (log:info "handle-cmd-rates" chat-id message-id args)
  162. (let ((rates (rest (peek-circular *per-minute-rates*))))
  163. (telegram-send-message chat-id
  164. (format nil "Зеленый ~A, гейро ~A, британец ~A"
  165. (cdar rates) (cdadr rates) (cdaddr rates)))))
  166. (defun handle-cmd-charts (chat-id message-id args)
  167. (log:info "handle-cmd-charts" chat-id message-id args)
  168. (telegram-send-chat-action chat-id "upload_photo")
  169. (let ((chart (make-chart *per-minute-rates*))
  170. (rates (rest (peek-circular *per-minute-rates*))))
  171. (telegram-send-photo chat-id chart
  172. :caption (format nil "Зеленый ~A, гейро ~A, британец ~A"
  173. (cdar rates) (cdadr rates) (cdaddr rates)))))
  174. ;; Weather
  175. (defun handle-cmd-weather (chat-id message-id args)
  176. (log:info "handle-cmd-weather" chat-id message-id args)
  177. (let ((location (cdr (assoc chat-id *chat-locations*))))
  178. (telegram-send-message
  179. chat-id
  180. (if location
  181. (handler-case
  182. (forecast-format (forecast
  183. (aget "latitude" location)
  184. (aget "longitude" location)
  185. :hourly (find "hourly" args :key #'string-downcase :test #'equal)
  186. :daily (find "daily" args :key #'string-downcase :test #'equal)))
  187. (error (e)
  188. (log:error e)
  189. "Ошибочка вышла"))
  190. "Так а ты чьих будешь?"))))
  191. ;; Foursquare
  192. (defvar *fsq-send-to* (make-hash-table)
  193. "Hash of chat-id's to fsq users list to send checkings to")
  194. (defun fsq-user-name (user)
  195. (when user
  196. (format nil "~@[~A~]~@[ ~A~]"
  197. (aget "firstName" user)
  198. (aget "lastName" user))))
  199. (defun handle-cmd-post-checkins (chat-id message-id args)
  200. (log:info "handle-cmd-post-checkins" chat-id message-id args)
  201. (handler-case
  202. (let ((users (gethash chat-id *fsq-send-to*))
  203. (friends (fsq-fetch-friends)))
  204. (if (null args)
  205. (telegram-send-message chat-id
  206. (if (null users)
  207. "Пока никого не палим"
  208. (format nil "Палим ~{~A~^, ~}"
  209. (loop for user in friends
  210. when (member (aget "id" user)
  211. users :test #'equal)
  212. collect (fsq-user-name user)))))
  213. (progn
  214. (dolist (user args)
  215. (let ((username (fsq-user-name
  216. (find user friends
  217. :test #'equal
  218. :key #'(lambda (f) (aget "id" f))))))
  219. (when username
  220. (if (member user users :test #'equal)
  221. (progn
  222. (setf users (remove user users :test #'equal))
  223. (telegram-send-message chat-id
  224. (format nil "Больше не палим ~A" username)))
  225. (progn
  226. (push user users)
  227. (telegram-send-message chat-id (format nil "Теперь палим ~A" username)))))))
  228. (setf (gethash chat-id *fsq-send-to*) users)
  229. (save-settings))))
  230. (error (e)
  231. (log:error e)
  232. (telegram-send-message chat-id "Ошибочка вышла"))))
  233. (defun handle-cmd-fsq-friends (chat-id message-id args)
  234. (log:info "handle-cmd-fsq-friends" chat-id message-id args)
  235. (handler-case
  236. (let ((users (gethash chat-id *fsq-send-to*))
  237. (friends (fsq-fetch-friends)))
  238. (telegram-send-message
  239. chat-id
  240. (format
  241. nil "~{~A: ~:[~;📍 ~]~A~^~%~}"
  242. (loop for user in friends
  243. append (list
  244. (aget "id" user)
  245. (member (aget "id" user) users :test #'equal)
  246. (fsq-user-name user))))))
  247. (error (e) (log:error e))))
  248. (defun handle-cmd-checkins (chat-id message-id args)
  249. (log:info "handle-cmd-checkins" chat-id message-id args)
  250. (handler-case
  251. (let ((users (gethash chat-id *fsq-send-to*)))
  252. (when users
  253. (telegram-send-message
  254. chat-id
  255. (format nil "~{~A~^~%~}"
  256. (loop for checkin in (fsq-fetch-checkins)
  257. if (member (aget "id" (aget "user" checkin)) users :test #'equal)
  258. collect (fsq-format-checkin checkin t))))))
  259. (error (e) (log:error e))))
  260. (defvar *fsq-seen-ids* nil "Ids of seen checkins")
  261. (defun process-latest-checkins ()
  262. (handler-case
  263. (let ((checkins (make-hash-table)))
  264. (dolist (checkin (fsq-fetch-new-checkins))
  265. (let ((id (aget "id" checkin))
  266. (user (aget "id" (aget "user" checkin))))
  267. (unless (find id *fsq-seen-ids* :test #'equal)
  268. (loop for chat-id being the hash-keys in *fsq-send-to* using (hash-value users)
  269. do (when (member user users :test #'equal)
  270. (push (fsq-format-checkin checkin)
  271. (gethash chat-id checkins))))
  272. (push id *fsq-seen-ids*))))
  273. (loop for chat-id being the hash-keys in checkins using (hash-value texts)
  274. do (log:info "Sending checkins" chat-id texts)
  275. (telegram-send-message chat-id (format nil "~{~A~^~%~}" texts))))
  276. (error (e) (log:error e))))
  277. (defun save-settings()
  278. (with-open-file (s (merge-pathnames "settings.lisp"
  279. (asdf:component-pathname
  280. (asdf:find-system '#:chatikbot)))
  281. :direction :output
  282. :if-exists :supersede
  283. :if-does-not-exist :create)
  284. (write '(in-package #:chatikbot) :stream s)
  285. (write
  286. `(setf *fsq-send-to* (alexandria:alist-hash-table ',(alexandria:hash-table-alist *fsq-send-to*))
  287. *chat-locations* ',*chat-locations*
  288. *akb-send-to* ',*akb-send-to*
  289. *akb-last-id* ,*akb-last-id*)
  290. :stream s)))
  291. (defun start ()
  292. ;; Clear prev threads
  293. (mapc #'trivial-timers:unschedule-timer (trivial-timers:list-all-timers))
  294. (let ((old-updates (find "process-updates"
  295. (bordeaux-threads:all-threads)
  296. :key #'bordeaux-threads:thread-name
  297. :test #'equal)))
  298. (when old-updates
  299. (bordeaux-threads:destroy-thread old-updates)))
  300. ;; Load settings file
  301. (alexandria:when-let (file (probe-file
  302. (merge-pathnames "settings.lisp"
  303. (asdf:component-pathname
  304. (asdf:find-system '#:chatikbot)))))
  305. (load file))
  306. ;; Start timers
  307. (clon:schedule-function
  308. (lambda () (process-latest-akb))
  309. (clon:make-scheduler
  310. (clon:make-typed-cron-schedule :minute '* :hour '*)
  311. :allow-now-p t)
  312. :thread t)
  313. (clon:schedule-function
  314. (lambda () (process-latest-checkins))
  315. (clon:make-scheduler
  316. (clon:make-typed-cron-schedule :minute '* :hour '*)
  317. :allow-now-p t)
  318. :thread t)
  319. (clon:schedule-function
  320. (lambda () (process-rates))
  321. (clon:make-scheduler
  322. (clon:make-typed-cron-schedule :minute '* :hour '*)
  323. :allow-now-p t)
  324. :thread t)
  325. ;; Start getUpdates thread
  326. (bordeaux-threads:make-thread
  327. (lambda ()
  328. (in-package #:chatikbot)
  329. (loop-with-error-backoff #'process-updates))
  330. :name "process-updates"))