Line data Source code
1 4 : (ns matchscore.telegram.link-wizard
2 : "Linking a chat from the bot's private chat.
3 :
4 : A connect link from the app opens the bot with `/start lt_<id>` or
5 : `/start le_<id>`. The bot answers with a keyboard button that makes Telegram
6 : show the user's groups; the choice comes back as a `chat_shared` message
7 : carrying the request id sent with the button. The pending request is kept in
8 : Redis between those two messages."
9 : (:require
10 : [cheshire.core :as json]
11 : [taoensso.carmine :as car]
12 : [taoensso.telemere :as t]
13 : [telegrambot-lib.core :as tbot]))
14 :
15 :
16 8 : (def ^:private request-ttl-seconds
17 : "How long the user has to pick a group after pressing Start."
18 : 900)
19 :
20 :
21 10 : (defn- request-key [sender-tg-id request-id] (str "tg:link-request:" sender-tg-id ":" request-id))
22 :
23 :
24 4 : (defn new-request-id
25 : "Telegram echoes this signed 32-bit id back in `chat_shared`."
26 : []
27 4 : (inc (rand-int 2147483646)))
28 :
29 :
30 4 : (defn save-request!
31 : "Remembers what the sender asked to link. `target` is
32 : {:cmd \"link_template\"|\"link_event\" :public-id \"...\"}."
33 : [redis sender-tg-id request-id target]
34 35 : (car/wcar
35 1 : redis
36 3 : (car/set
37 4 : (request-key sender-tg-id request-id)
38 3 : (json/generate-string target)
39 : :ex
40 1 : request-ttl-seconds)))
41 :
42 :
43 4 : (defn take-request!
44 : "Returns and forgets the sender's pending request, or nil when it is unknown or
45 : expired. A request is good for one pick."
46 : [redis sender-tg-id request-id]
47 5 : (let [k (request-key sender-tg-id request-id)
48 39 : value (car/wcar redis (car/get k))]
49 46 : (when value (car/wcar redis (car/del k)) (json/parse-string value true))))
50 :
51 :
52 4 : (defn pick-group-markup
53 : "Reply keyboard with one button that opens Telegram's chat picker, limited to
54 : groups the bot is already a member of."
55 : [request-id button-text]
56 12 : {:keyboard [[{:text button-text
57 7 : :request_chat {:request_id request-id
58 : :chat_is_channel false
59 : :bot_is_member true}}]]
60 : :resize_keyboard true
61 : :one_time_keyboard true})
62 :
63 :
64 16 : (def remove-keyboard-markup {:remove_keyboard true})
65 :
66 :
67 4 : (defn send!
68 : "Sends a private message with the given reply markup. Returns the message id,
69 : or nil when Telegram refuses it."
70 : [bot chat-id text reply-markup]
71 1 : (try
72 2 : (get-in
73 2 : (tbot/send-message
74 1 : bot
75 5 : {:chat_id chat-id
76 1 : :text text
77 3 : :reply_markup (json/generate-string reply-markup)})
78 3 : [:result :message_id])
79 : (catch Exception e
80 0 : (t/log!
81 : :warn
82 0 : {:message "link wizard message failed"
83 0 : :exception e})
84 : nil)))
|