Line data Source code
1 4 : (ns matchscore.jobs.telegram-name-reminder
2 : "Telegram nudges that ask players to confirm their name. Texts and rules live in
3 : `matchscore.telegram.name-reminder`; this namespace sends them."
4 : (:require
5 : [cats.core :as c]
6 : [cats.monad.either :as either]
7 : [cheshire.core :as json]
8 : [clojure.string :as str]
9 : [matchscore.db.postgres.name-reminders :as name-db]
10 : [matchscore.db.postgres.telegram-match-notifications :as notification-db]
11 : [matchscore.domain.event.repository.postgres :as event-postgres-repo]
12 : [matchscore.domain.telegram-chat-message.repository.postgres
13 : :as
14 : telegram-chat-message-postgres-repo]
15 : [matchscore.domain.telegram-link.query :as telegram-link-query]
16 : [matchscore.domain.user.repository.postgres :as user-postgres-repo]
17 : [matchscore.domain.user.repository.redis :as user-redis-repo]
18 : [matchscore.jobs.telegram-notifications :as notification-jobs]
19 : [matchscore.telegram.event-lock :as event-lock]
20 : [matchscore.telegram.localization :as l10n]
21 : [matchscore.telegram.messages :as messages]
22 : [matchscore.telegram.name-reminder :as name-reminder]
23 : [taoensso.carmine :as car]
24 : [taoensso.telemere :as t]
25 : [telegrambot-lib.core :as tbot])
26 : (:import
27 : (java.time Duration Instant OffsetDateTime)
28 : (java.util Date)))
29 :
30 :
31 4 : (defn- bot-username
32 : [system-components]
33 7 : (get-in system-components [:config :telegram :bot-username]))
34 :
35 :
36 4 : (defn- blocked-error?
37 : "Telegram refuses private messages from a bot the user never started or blocked."
38 : [exception]
39 4 : (let [{:keys [error_code description]} (ex-data exception)
40 7 : description (str/lower-case (or description ""))]
41 4 : (or
42 3 : (= 403 error_code)
43 : (and
44 0 : (= 400 error_code)
45 0 : (some
46 0 : #(str/includes? description %)
47 0 : ["bot was blocked" "chat not found" "user is deactivated"])))))
48 :
49 :
50 4 : (defn- send!
51 : "Sends {:text :reply-markup} as HTML. Returns the Telegram message id."
52 : [telegram-bot chat-id thread-id {:keys [text reply-markup]}]
53 4 : (get-in
54 4 : (messages/request!
55 2 : tbot/send-message
56 2 : telegram-bot
57 14 : (cond->
58 14 : {:chat_id chat-id
59 2 : :text text
60 : :parse_mode "HTML"
61 6 : :link_preview_options {:is_disabled true}}
62 2 : thread-id (assoc :message_thread_id thread-id)
63 10 : reply-markup (assoc :reply_markup (json/generate-string reply-markup))))
64 3 : [:result :message_id]))
65 :
66 :
67 4 : (defn- invalidate-user-cache!
68 : [repos telegram-id]
69 18 : (when-let [user-redis (:user-redis-repo repos)]
70 6 : (user-redis-repo/invalidate-users! user-redis)
71 14 : (when telegram-id (user-redis-repo/invalidate-tg-uuid! user-redis telegram-id))))
72 :
73 :
74 4 : (defn set-bot-access!
75 : "Records whether the bot may message `telegram-id` privately (\"confirmed\" or
76 : \"denied\") and drops the cached users when that changed."
77 : [{:keys [pg repos]} telegram-id status]
78 32 : (when (and telegram-id (pos? (or (name-db/set-bot-access! pg telegram-id status) 0)))
79 8 : (invalidate-user-cache! repos telegram-id)))
80 :
81 :
82 4 : (defn- private-locale
83 : [pg user]
84 22 : (name-reminder/user-locale (:settings user) (name-db/latest-event-language pg (:uuid user))))
85 :
86 :
87 4 : (defn- send-private!
88 : "Sends a private name message. Returns :sent, :blocked (and records that the bot
89 : can no longer write to the user) or :failed."
90 : [{:keys [pg telegram-bot]} user message]
91 2 : (try
92 8 : (send! telegram-bot (:telegram-id user) nil message)
93 : :sent
94 : (catch clojure.lang.ExceptionInfo e
95 4 : (if (blocked-error? e)
96 8 : (do (notification-db/mark-user-denied! pg (:uuid user)) :blocked)
97 0 : (do
98 0 : (t/log!
99 : :warn
100 0 : {:message "Failed to send Telegram name message"
101 0 : :user-id (str (:uuid user))
102 0 : :error (select-keys (ex-data e) [:error_code :description])})
103 : :failed)))))
104 :
105 :
106 4 : (defn name-reminder-job
107 : "Goose job: one scheduled private reminder to confirm the name. Claimed before it
108 : is sent, so a retry never sends it twice."
109 : [system-components user-id]
110 12 : (when-let [user (name-db/claim-reminder! (:pg system-components) user-id)]
111 7 : (let [locale (private-locale (:pg system-components) user)
112 2 : result (send-private!
113 1 : system-components
114 1 : user
115 7 : (name-reminder/private-message locale user (bot-username system-components)))]
116 92 : (t/log!
117 : :info
118 6 : {:message "Telegram name reminder"
119 3 : :user-id (str user-id)
120 3 : :reminder (:name-reminder-count user)
121 1 : :result result})
122 1 : result)))
123 :
124 :
125 4 : (defn answer-private-start!
126 : "Answers a private /start that is not a group link request. Starting the bot means
127 : it may now message the user, which is recorded first. Then a user whose name needs
128 : confirming gets the name message; the name link (`/start name`) always gets an
129 : answer, also when the name is already confirmed. Send failures are logged, not
130 : thrown, so the command job does not retry and repeat the message."
131 : [{:keys [pg repos telegram-bot]
132 : :as ctx}
133 : {:keys [chat-id sender-tg-id sender-uuid sender-language-code]}
134 : payload]
135 10 : (set-bot-access! ctx sender-tg-id "confirmed")
136 8 : (let [name-link? (= name-reminder/start-payload payload)
137 6 : user (when sender-uuid
138 12 : (user-postgres-repo/find-by-id (:user-postgres-repo repos) sender-uuid))
139 14 : username (get-in ctx [:config :telegram :bot-username])]
140 2 : (try
141 24 : (cond (and (nil? user) name-link?)
142 0 : (send!
143 0 : telegram-bot
144 0 : chat-id
145 : nil
146 0 : {:text (l10n/t
147 0 : sender-language-code
148 : :telegram.reply/open-to-register
149 0 : (name-reminder/app-url username "/"))})
150 :
151 8 : (nil? user) nil
152 :
153 29 : (and (nil? (:name-confirmed-at user)) (not (:is-fake user)))
154 10 : (let [locale (private-locale pg user)]
155 20 : (send! telegram-bot chat-id nil (name-reminder/private-message locale user username))
156 6 : (name-db/mark-reminder-sent! pg (:uuid user)))
157 :
158 1 : name-link?
159 3 : (send!
160 1 : telegram-bot
161 1 : chat-id
162 : nil
163 8 : (name-reminder/confirmed-message (private-locale pg user) user username)))
164 : (catch clojure.lang.ExceptionInfo e
165 92 : (t/log!
166 : :warn
167 5 : {:message "Failed to answer private /start"
168 1 : :chat-id chat-id
169 8 : :error (select-keys (ex-data e) [:error_code :description])})))))
170 :
171 :
172 4 : (defn join-nudge
173 : "For a player who just pressed Join and whose name needs confirming, returns
174 : {:text <alert> :url <bot link>} for the callback answer, at most once per
175 : `join-nudge-ttl-seconds`; nil otherwise. The link opens the bot's private chat,
176 : where starting the bot shows the name message. Best effort: any failure returns
177 : nil, so the player still gets the usual answer to Join."
178 : [{:keys [redis repos config]} locale user-uuid joined-text]
179 3 : (try
180 28 : (when-let [url (name-reminder/bot-start-url (get-in config [:telegram :bot-username]))]
181 14 : (let [user (user-postgres-repo/find-by-id (:user-postgres-repo repos) user-uuid)]
182 2 : (when
183 12 : (and
184 1 : user
185 6 : (nil? (:name-confirmed-at user))
186 5 : (not (:is-fake user))
187 : (=
188 : "OK"
189 35 : (car/wcar
190 1 : redis
191 5 : (car/set
192 4 : (str "tg:name-nudge:join:" user-uuid)
193 : "1" :nx
194 1 : :ex name-reminder/join-nudge-ttl-seconds))))
195 10 : {:text (name-reminder/join-alert locale joined-text (:name user))
196 1 : :url url})))
197 : (catch Exception e
198 92 : (t/log!
199 : :warn
200 5 : {:message "Join name nudge failed"
201 3 : :user-id (str user-uuid)
202 1 : :exception e})
203 : nil)))
204 :
205 :
206 4 : (def ^:private legacy-dedupe-window
207 : "Jobs queued before request ids existed carry only the event id. They skip
208 : destinations that already got a name reminder within this window."
209 12 : (Duration/ofHours 24))
210 :
211 :
212 4 : (defn- request-revision
213 : "Content revision stored on the recorded post of one organizer request."
214 : [request-id]
215 4 : (str "name-reminder:" request-id))
216 :
217 :
218 4 : (defn- instant
219 : [x]
220 6 : (cond (instance? Instant x) x
221 5 : (instance? Date x) (.toInstant ^Date x)
222 0 : (instance? OffsetDateTime x) (.toInstant ^OffsetDateTime x)
223 : :else nil))
224 :
225 :
226 4 : (defn- delivered-destinations
227 : "Set of [chat-id thread-id] that already got this request's reminder. Deleted posts
228 : count, so cleanup of the chat never lets a retry ping the players again. Without a
229 : request id (legacy job) any name reminder of the last 24 hours counts."
230 : [message-repo event-id request-id]
231 10 : (let [revision (some->
232 1 : request-id
233 1 : request-revision)
234 4 : since (.minus (Instant/now) ^Duration legacy-dedupe-window)]
235 2 : (into
236 1 : #{}
237 2 : (comp
238 8 : (filter #(= "name_reminder" (:kind %)))
239 2 : (filter
240 1 : (fn [{:keys [content-revision created-datetime]}]
241 2 : (if revision
242 3 : (= revision content-revision)
243 11 : (when-let [at (instant created-datetime)] (.isAfter at since)))))
244 6 : (map (juxt :chat-id :thread-id)))
245 4 : (telegram-chat-message-postgres-repo/find-by-event-id message-repo event-id))))
246 :
247 :
248 4 : (defn- post-group-reminder!
249 : "Posts the reminder to one link and records it, tagged with the request. Returns the
250 : message id. The receipt uses the job's own repositories (not the event lock's
251 : transaction), so it stays even when a later destination fails and the job retries."
252 : [{:keys [repos telegram-bot]}
253 : event
254 : message
255 : request-id
256 : {:keys [chat-id thread-id]
257 : :as link}]
258 2 : (let [message-id (try
259 6 : (send! telegram-bot chat-id thread-id message)
260 : (catch clojure.lang.ExceptionInfo e
261 5 : (notification-jobs/record-delivery-failure! repos link e)
262 2 : (throw e)))
263 2 : saved (telegram-chat-message-postgres-repo/record!
264 3 : (:telegram-chat-message-postgres-repo repos)
265 6 : (cond->
266 11 : {:chat-id chat-id
267 1 : :thread-id thread-id
268 1 : :message-id message-id
269 : :sender-kind "bot"
270 : :kind "name_reminder"
271 3 : :text (:text message)
272 3 : :event-id (:uuid event)}
273 5 : request-id (assoc :content-revision (request-revision request-id))))]
274 4 : (when (either/left? saved)
275 : ;; The post is already out; throwing would make the retry post it again.
276 0 : (t/log!
277 : :error
278 0 : {:message "Failed to record Telegram name reminder; a retry may repeat it"
279 0 : :event-id (str (:uuid event))
280 0 : :chat-id chat-id
281 0 : :message-id message-id
282 0 : :error (c/extract saved)}))
283 1 : message-id))
284 :
285 :
286 4 : (defn- send-group-reminder!
287 : "Sends to every destination not yet delivered for this request. Returns
288 : {:sent n :already n :refused n :errors [retryable exceptions]}."
289 : [{:keys [repos]
290 : :as system-components}
291 : event
292 : message
293 : request-id
294 : links]
295 3 : (let [delivered (delivered-destinations
296 3 : (:telegram-chat-message-postgres-repo repos)
297 3 : (:uuid event)
298 1 : request-id)]
299 2 : (reduce
300 1 : (fn
301 : [outcome
302 : {:keys [chat-id thread-id]
303 : :as link}]
304 7 : (if (contains? delivered [chat-id thread-id])
305 5 : (update outcome :already inc)
306 1 : (try
307 7 : (post-group-reminder! system-components event message request-id link)
308 5 : (update outcome :sent inc)
309 : (catch Exception e
310 92 : (t/log!
311 : :warn
312 6 : {:message "Failed to post Telegram name reminder"
313 5 : :event-id (str (:uuid event))
314 1 : :chat-id chat-id
315 1 : :exception e})
316 1 : (if
317 4 : (and
318 4 : (instance? clojure.lang.ExceptionInfo e)
319 2 : (#'notification-jobs/destination-refused? e))
320 : ;; The chat will not take the post; retrying only re-pings the healthy ones.
321 5 : (update outcome :refused inc)
322 6 : (update outcome :errors conj e))))))
323 8 : {:sent 0
324 : :already 0
325 : :refused 0
326 1 : :errors []}
327 1 : links)))
328 :
329 :
330 4 : (defn group-name-reminder-job
331 : "Goose job: posts one message to every chat linked to the event that mentions the
332 : players whose name needs confirming. `request-id` (absent on jobs queued by older
333 : versions) identifies the organizer's request: the whole send runs under the event's
334 : lock, and a destination that already holds this request's post is skipped, so a retry
335 : after a failed chat posts only where it is still missing. Chats that refuse the post
336 : are not retried; transient failures (rate limits, outages) are rethrown after the
337 : others were tried. A process crash between Telegram accepting a post and the receipt
338 : being saved can still repeat that one post on retry.
339 : When nothing was delivered and nothing will be retried, this request's cooldown is
340 : released so the organizer can try again."
341 5 : ([system-components event-id] (group-name-reminder-job system-components event-id nil))
342 : ([{:keys [pg repos redis]
343 : :as system-components}
344 : event-id
345 : request-id]
346 1 : (let [outcome
347 2 : (event-lock/with-lock
348 5 : (or pg (:ds (:telegram-chat-message-postgres-repo repos)))
349 1 : event-id
350 1 : (fn []
351 8 : (let [event (event-postgres-repo/find-by-id (:event-postgres-repo repos) event-id {})
352 7 : players (when event (name-db/unconfirmed-event-participants pg event-id))
353 3 : message (when event
354 2 : (name-reminder/group-message
355 4 : (l10n/message-locale repos event)
356 1 : players
357 3 : (bot-username system-components)))]
358 4 : (if-not message
359 0 : {:sent 0
360 : :already 0
361 : :refused 0
362 0 : :errors []}
363 2 : (send-group-reminder!
364 1 : system-components
365 1 : event
366 1 : message
367 1 : request-id
368 2 : (telegram-link-query/resolve-links-for-event
369 8 : (select-keys system-components [:pg :repos :redis :goose])
370 1 : event))))))]
371 13 : (when-let [error (first (:errors outcome))] (throw error))
372 15 : (when (and request-id (zero? (+ (:sent outcome) (:already outcome))))
373 5 : (name-reminder/release-group-cooldown! redis event-id request-id))
374 1 : outcome)))
375 :
376 :
377 4 : (defn sync-private-bot-access-job
378 : "Goose job: the user blocked the bot (`kicked`) or started/unblocked it (`member`)
379 : in their private chat with it."
380 : [system-components {:keys [telegram-id status]}]
381 3 : (case status
382 5 : "kicked" (set-bot-access! system-components telegram-id "denied")
383 5 : "member" (set-bot-access! system-components telegram-id "confirmed")
384 : nil))
|