-
Notifications
You must be signed in to change notification settings - Fork 0
/
publishQuote.ts
72 lines (64 loc) · 2.38 KB
/
publishQuote.ts
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
import bot from "./initBot.ts";
import { ObjectId } from "./deps.ts";
import publishToMastodon from "./utils/publishToMastodon.ts";
import getQuotesButtons from "./callbacks/getQuotesButtons.ts";
import sendMassiveMessage from "./utils/sendMassiveMessage.ts";
import { changeQuote, getFullQuote, getQuote, parseFullQuote } from "./controllers/mongo/quote.controller.ts";
interface CommonParams {
id?: string | ObjectId;
}
interface ParamsChat extends CommonParams {
chatID: number | string;
chatType: "group" | "supergroup" | "private";
}
interface ParamsNoChat extends CommonParams {
chatID?: undefined;
chatType?: undefined;
}
type Params = ParamsChat | ParamsNoChat;
export default async function publishQuote({ id, chatID, chatType }: Params = {}) {
const query: { _id?: ObjectId } = {};
if (id) {
query._id = new ObjectId(id);
} else if (chatID === undefined) {
// Si se está publicando a todos se envía siguiente la que tenga menos tiempo de haber sido enviada
query._id = (await getQuote(
{ archived: { $ne: true } },
{ sort: { lastSentTime: 1 }, projection: { _id: 1 } }
))!._id;
}
// Si es usando el comando /frase, se intenciona compartir la última que se envió
else
query._id = (await getQuote(
{ archived: { $ne: true } },
{ sort: { lastSentTime: -1 }, projection: { _id: -1 } }
))!._id;
const possibleQuote = await getFullQuote(query);
if (possibleQuote === null) {
if (chatID === undefined) return;
return bot.api.sendMessage(chatID, "No hay frases para compartir.").catch(() => {});
}
const fullQuote = parseFullQuote(possibleQuote, true);
if (chatID)
return bot.api
.sendMessage(chatID, fullQuote, {
parse_mode: "HTML",
link_preview_options: { is_disabled: true },
reply_markup:
possibleQuote.number && chatType === "private"
? await getQuotesButtons(possibleQuote.number, chatID)
: undefined,
})
.catch(() => {});
await sendMassiveMessage(fullQuote, undefined, {
parse_mode: "HTML",
link_preview_options: { is_disabled: true },
});
try {
const { quote, extras } = parseFullQuote(possibleQuote, false);
await publishToMastodon(quote, extras, possibleQuote.language);
} catch (e) {
console.error(e);
}
await changeQuote({ _id: possibleQuote._id }, { $set: { lastSentTime: new Date() }, $inc: { timesSent: 1 } });
}