-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
145 lines (116 loc) · 3.75 KB
/
main.ts
File metadata and controls
145 lines (116 loc) · 3.75 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
import "@std/dotenv/load";
import { Bot, InlineQueryResultBuilder } from "grammy";
const TOKEN_VAR_NAME = "API_TOKEN";
const token = Deno.env.get(TOKEN_VAR_NAME);
if (!token) {
console.error(
`Error: ${TOKEN_VAR_NAME} is not provided. Please add it to your environment variables or .env file.`,
);
Deno.exit(1);
}
const LINK_RULES_VAR_NAME = "LINK_RULES";
const linkRulesVarValue = Deno.env.get(LINK_RULES_VAR_NAME);
if (!linkRulesVarValue) {
console.error(
`Error: ${LINK_RULES_VAR_NAME} is not provided. Please add it to your environment variables or .env file. See .env.example for reference.`,
);
Deno.exit(1);
}
let linkReplacementRulesMap: Record<string, string>;
try {
const parsed = JSON.parse(linkRulesVarValue);
if (
typeof parsed !== "object" || parsed === null ||
Array.isArray(parsed) ||
!Object.values(parsed).every((v) => typeof v === "string")
) {
throw new Error("must be a JSON object with string values");
}
linkReplacementRulesMap = parsed as Record<string, string>;
} catch (error) {
console.error(
`Error: ${LINK_RULES_VAR_NAME} is invalid: ${
error instanceof Error ? error.message : error
}. See .env.example for reference.`,
);
Deno.exit(1);
}
const replaceLink = (url: string): string => {
for (
const [originalDomain, newDomain] of Object.entries(linkReplacementRulesMap)
) {
const regex = new RegExp(`https?://(www\\.)?${originalDomain}`);
if (regex.test(url)) {
return url.replace(regex, `https://${newDomain}`);
}
}
return url;
};
const extractUrls = (text: string): string[] => {
const query = text.split("\n").map((x) => x.trim());
const urls: string[] = [];
for (const line of query) {
let startIndex = 0;
while (startIndex < line.length) {
const httpIndex = line.indexOf("http", startIndex);
if (httpIndex === -1) break;
let endIndex = line.length;
const nextHttpIndex = line.indexOf("http", httpIndex + 4);
const nextWhitespaceIndex = line.indexOf(" ", httpIndex);
if (nextHttpIndex !== -1 && nextHttpIndex < endIndex) {
endIndex = nextHttpIndex;
}
if (nextWhitespaceIndex !== -1 && nextWhitespaceIndex < endIndex) {
endIndex = nextWhitespaceIndex;
}
const url = line.slice(httpIndex, endIndex);
urls.push(url);
startIndex = endIndex;
}
}
return urls;
};
const getReplyText = (url: string, modifiedUrl: string): string =>
`<a href="${modifiedUrl}">${modifiedUrl}</a>\n\n(<a href="${url}">Original</a>)`;
const bot = new Bot(token);
bot.on("message:text", async (ctx) => {
const messageText = ctx.message.text;
if (messageText) {
const urls = extractUrls(messageText);
for (const url of urls) {
const modifiedUrl = replaceLink(url);
if (modifiedUrl !== url) {
const replyText = getReplyText(url, modifiedUrl);
await ctx.reply(replyText, {
disable_notification: true,
parse_mode: "HTML",
})
.catch((error) => console.error("Failed to send message:", error));
}
}
}
});
bot.on("inline_query", async (ctx) => {
const query = ctx.inlineQuery.query.trim();
if (query) {
const urls = extractUrls(query);
const results = urls.map((url, index) => {
const modifiedUrl = replaceLink(url);
const replyText = getReplyText(url, modifiedUrl);
return InlineQueryResultBuilder
.article(String(index), "Modified link", {
description: modifiedUrl,
}).text(replyText, {
parse_mode: "HTML",
});
});
await ctx.answerInlineQuery(results).catch(
(error) => {
console.error("Failed to answer inline query:", error);
},
);
}
});
bot.start({
onStart: () => console.log("Bot is running..."),
});