-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformatMessage.ts
More file actions
169 lines (161 loc) · 4.63 KB
/
formatMessage.ts
File metadata and controls
169 lines (161 loc) · 4.63 KB
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
/**
* Module for formatting messages to be sent to Telegram.
*
* Use {@link tgFmt} function to format a message.
*
* @example Formatting and sending a message
*
* ```ts
* import { initTgBot } from "./mod.ts";
* const bot = initTgBot({ botToken: "YOUR_TOKEN" });
*
* const msg = tgFmt`Hello, ${tgEntity("bold", "World")}!`;
* await bot.sendMessage({ chat_id: "123", ...msg });
* ```
*
* @module
*/
import type { TgMessageEntity, TgSendMessageParams } from "./TgApi.ts";
/**
* Formatted Telegram message, which can be passed to Telegram API methods.
*
* To send it, spread it into {@link TgSendMessageParams} when sending a message.
*
* Can also be used as a part of a bigger formatted message when passed to {@link tgFmt}.
*
* @example
*
* ```ts
* const msg: FormattedTgMessage = {
* text: "Hello, World!",
* entities: [{ type: "bold", offset: 7, length: 5 }],
* };
*
* const msg2: FormattedTgMessage = tgFmt`The message is: ${msg}`;
*
* const sendMessageParams = { chat_id: "123", ...msg2 };
* ```
*/
export type FormattedTgMessage = Pick<TgSendMessageParams, "text" | "entities">;
/**
* Values that can be used to build a {@link FormattedTgMessage} using {@link tgFmt}.
*
* @example
*
* ```ts
* tgFmt(
* "Hello", // string
* tgEntity("bold", "Bold text"), // result of a formatting function
* tgFmt`Hello, ${tgEntity("bold", "World")}!`, // another formatted message
* ["a", "b", "c"], // nested array of parts
* null, // nullish (ignored)
* );
* ```
*/
export type FormattedTgMessagePart =
| Array<FormattedTgMessagePart>
| FormattedTgMessage
| string
| null
| undefined;
/**
* Joins strings and other formatted messages into a single formatted message.
*
* Can be used either as a regular function or a tagged template literal.
*
* To actually insert entities into a message, use the {@link tgEntity} function.
*
* @example Sending a formatted message
*
* ```ts
* import { initTgBot } from "./mod.ts";
* const bot = initTgBot({ botToken: "YOUR_TOKEN" });
*
* await bot.sendMessage({
* chat_id: "123",
* ...tgFmt`Hello, ${tgEntity("bold", "World")}!`,
* });
* ```
*
* @example Sending a photo with a formatted caption
*
* ```ts
* import { initTgBot } from "./mod.ts";
* const bot = initTgBot({ botToken: "YOUR_TOKEN" });
*
* const msg = tgFmt("Hello, ", tgEntity("bold", "World"), "!");
*
* await bot.sendPhoto({
* chat_id: "123",
* photo: new Blob([]),
* caption: msg.text,
* caption_entities: msg.entities,
* });
* ```
*/
export function tgFmt(
arg0: TemplateStringsArray | FormattedTgMessagePart[] | FormattedTgMessagePart,
...args: FormattedTgMessagePart[]
): FormattedTgMessage {
// Collect all arguments into a single parts array.
// @ts-ignore -- Array.isArray doesn't detect ReadonlyArray as array.
const arg0arr: FormattedTgMessagePart[] = Array.isArray(arg0) ? arg0 : [arg0];
const parts = Array.from({ length: Math.max(arg0arr.length, args.length) })
.flatMap((_, i) => [arg0arr[i], args[i]]); // Zip arrays together.
// Iterate over all parts.
let { text, entities }: FormattedTgMessage = { text: "", entities: [] };
let index = 0;
for (const part of parts) {
// Turn part into a formatted message.
const message = tgFmtPart(part);
// Append text and entities to the result.
text += message.text;
entities.push(
...message.entities?.map((entity) => ({ ...entity, offset: index + entity.offset })) ?? [],
);
// Update index.
index += message.text.length;
}
// Remove entities if empty.
if (entities.length > 0) return { text, entities };
else return { text };
}
/**
* Formats a single part of a formatted Telegram message.
*
* Used internally by {@link tgFmt}.
*/
function tgFmtPart(part: FormattedTgMessagePart): FormattedTgMessage {
if (Array.isArray(part)) return tgFmt(part);
if (typeof part == "string") return { text: part };
if (part != null) return part;
return { text: "" };
}
/**
* Creates a formatted message containing just a single entity.
*
* The result can be used as a part of a bigger formatted message when passed to {@link tgFmt}.
*
* @see {@link TgMessageEntity} for more information about entities.
*
* @example
*
* ```ts
* tgFmt`
* Normal text.
* ${tgEntity("bold", "Bold text.")}
* ${tgEntity("italic", "Italic text.")}
* ${tgEntity("text_link", "Click me!", { url: "https://example.com" })}
* `;
* ```
*/
export function tgEntity(
type: TgMessageEntity["type"],
text: string,
options?: Omit<TgMessageEntity, "type" | "offset" | "length">,
): FormattedTgMessage {
return {
text,
entities: [{ ...options, type, offset: 0, length: text.length }],
};
}