-
Notifications
You must be signed in to change notification settings - Fork 15
/
intro.js
128 lines (106 loc) · 2.96 KB
/
intro.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
const debug = require('debug')('tipmebch');
const { formatBchWithUsd, transfer } = require('./apis');
module.exports = function createIntro({
redisClient,
fetchRpc,
lockBitcoind,
ctx,
}) {
const claim = async ({ unclaimed, message, ctx }) => {
const {
bitcoinAccountId,
chatId,
bchAmount,
receiverUsername,
senderUsername,
} = unclaimed;
debug('Unclaimed %O', unclaimed);
await transfer(bitcoinAccountId, message.from.id.toString(), bchAmount, {
fetchRpc,
lockBitcoind,
redisClient,
});
const amountText = await formatBchWithUsd(bchAmount);
try {
await ctx.telegram.sendMessage(
chatId,
`@${receiverUsername} has claimed a ${amountText} tip from @${senderUsername}`
);
} catch (error) {
console.warn(
`WARN: Failed to tell user about their claim:\n${error.message}`
);
}
};
return async function intro(ctx, next) {
const { updateType, update } = ctx;
if (updateType !== 'message') {
return;
}
const { message } = update;
const userIsAlreadyKnown = await redisClient.existsAsync(
`telegram.user.${message.from.id}`
);
debug(
'User %s (%s) is already known? %s',
message.from.id,
message.from.username,
userIsAlreadyKnown
);
if (userIsAlreadyKnown) {
ctx.userWasAlreadyKnown = true;
return await next();
}
const { username } = message.from;
if (!username) {
return;
}
debug(`Storing user mapping for ${message.from.id} <> ${username}`);
// TODO: Possible issue if a different username was previously attached to this user id
await Promise.all([
redisClient.setAsync(
`telegram.user.${message.from.id}`,
message.from.username
),
redisClient.setAsync(`telegram.user.${username}`, message.from.id),
]);
const unclaimedIdsKey = `telegram.unclaimed.received:${username}`;
debug('Unclaimed ids key, %s', unclaimedIdsKey);
const unclaimeds = await redisClient
.multi()
.lrange(unclaimedIdsKey, 0, -1)
.del(unclaimedIdsKey)
.execAsync()
.then(_ => _[0] || [])
.then(
unclaimedIds =>
console.log({ unclaimedIds }) ||
Promise.all(
unclaimedIds.map(unclaimedId =>
redisClient
.multi()
.get(`telegram.unclaimed.${unclaimedId}`)
.del(`telegram.unclaimed.${unclaimedId}`)
.execAsync()
.then(_ => _[0])
)
)
);
debug('Unclaimeds %O', unclaimeds);
debug(`Found %s unclaimeds`, unclaimeds.length);
if (!unclaimeds) {
return await next();
}
await Promise.all(
unclaimeds.map(_ => JSON.parse(_)).map(unclaimed =>
claim({
unclaimed,
ctx,
message,
})
)
);
await redisClient.incrAsync('stats.intros.count');
await next();
};
};