-
-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathbot.ts
228 lines (214 loc) · 6.32 KB
/
bot.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
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import config from "./env.ts";
import { Bot, GrammyError, HttpError, InlineKeyboard } from "grammy/mod.ts";
import { parseFeed } from "rss";
import { cron } from "cron";
import {
addFeed,
getAllFeeds,
getLatest,
removeFeed,
storeLatest,
} from "./db.ts";
export const bot = new Bot(config.BOT_TOKEN);
bot.catch((err) => {
const ctx = err.ctx;
console.error(`Error while handling update ${ctx.update.update_id}:`);
const e = err.error;
if (e instanceof GrammyError) {
console.error("Error in request:", e.description);
} else if (e instanceof HttpError) {
console.error("Could not contact Telegram:", e);
} else {
console.error("Unknown error:", e);
}
});
await bot.init();
export default bot;
const OWNERS: number[] = [];
for (const owner of config.OWNERS.split(" ")) {
OWNERS.push(parseInt(owner));
}
async function matchChannelId(userName: string) {
const url = "https://www.youtube.com/" + userName;
const res = await fetch(url);
const text = await res.text();
const reg = new RegExp(
`"externalId":\"(.*)\","keywords"`,
);
const regRes = reg.exec(text);
if (!regRes || regRes.length < 2) {
return null;
}
return regRes[1];
}
const errorMsg =
"Please provide a channel link or username.\nEg: - `/add https://www.youtube.com/channel/UCykFIBKkj5ce3SggtaYSwtQ`\n- `/add @xditya`";
bot.command("start", async (ctx) => {
await ctx.reply(
`
Hey ${ctx.from!.first_name}!
I'm a YouTube feeds bot. I can send you the latest videos from your favorite YouTube channels.
Please deploy your own instance of the bot to use it. Find the repository in the button below.
`,
{
reply_markup: new InlineKeyboard().url(
"Repository",
"https://github.com/xditya/YouTubeFeeds",
),
},
);
if (OWNERS.includes(ctx.from!.id)) {
await ctx.reply(
"Use /add in any chat to add a feed to the chat. Use /list to view all added feeds and to remove them.",
{ parse_mode: "Markdown" },
);
}
});
bot
.filter((ctx) => OWNERS.includes(ctx.from!.id))
.command("add", async (ctx) => {
const channelLinkOrUserName = ctx.message!.text!.split(" ")[1];
let channelLink;
if (!channelLinkOrUserName) {
await ctx.reply(
errorMsg,
{ parse_mode: "Markdown" },
);
return;
}
let channelId;
if (!channelLinkOrUserName.startsWith("@")) {
channelId = channelLinkOrUserName.split("/").pop();
if (!channelId) {
await ctx.reply(
errorMsg,
{ parse_mode: "Markdown" },
);
return;
}
channelLink = channelLinkOrUserName;
} else {
const res = await matchChannelId(channelLinkOrUserName);
if (res == null) {
await ctx.reply(
errorMsg,
{ parse_mode: "Markdown" },
);
return;
}
channelId = res;
channelLink = "https://youtube.com/" + channelLinkOrUserName;
}
try {
const resp = await fetch(
"https://www.youtube.com/feeds/videos.xml?channel_id=" + channelId,
);
const data = await parseFeed(await resp.text());
const r = await addFeed(ctx.chat!.id, channelId);
if (r) {
await ctx.reply(
`Added "<a href="${channelLink}">${
data.title.value ?? "channel"
}</a>" to the current chat. New video notifications would be posted here!`,
{ parse_mode: "HTML" },
);
} else {
await ctx.reply(
`Notifications from "<a href="${channelLink}">${
data.title.value ?? "channel"
}</a>" are already enabled in this chat!`,
{ parse_mode: "HTML" },
);
}
} catch {
await ctx.reply(
errorMsg,
{ parse_mode: "Markdown" },
);
return;
}
});
bot
.filter((ctx) => OWNERS.includes(ctx.from!.id))
.command("list", async (ctx) => {
const reply = await ctx.reply("Processing...");
const buttons = new InlineKeyboard();
const allFeeds = await getAllFeeds();
let c = 0, x = 0;
for (const channelID in allFeeds) {
for (const chatID of allFeeds[channelID]) {
if (parseInt(chatID) == ctx.chat!.id) {
const channelInfo = await fetch(
"https://www.youtube.com/feeds/videos.xml?channel_id=" + channelID,
);
const data = await parseFeed(await channelInfo.text());
buttons.text(
data.title.value ?? "channel",
"rem" + channelID,
);
x++;
c++;
if (c == 2) {
buttons.row();
c = 0;
}
}
}
}
if (x == 0) {
return await ctx.api.editMessageText(
ctx.chat!.id,
reply.message_id,
"No feeds added in this chat! Go ahead and use /add!!",
);
}
await ctx.api.editMessageText(
ctx.chat!.id,
reply.message_id,
"Here are the feeds in this chat. Click on the button to remove that channel notification from this chat.",
{ reply_markup: buttons },
);
});
bot
.filter((ctx) => OWNERS.includes(ctx.from!.id))
.callbackQuery(/rem(.*)/, async (ctx) => {
await ctx.answerCallbackQuery();
await ctx.editMessageText(
`Removed the feed from <a href="https://youtube.com/channel/${ctx.match
?.[1]}">this channel</a> in the current chat.`,
{ parse_mode: "HTML" },
);
await removeFeed(ctx.chat!.id, ctx.match?.[1] ?? "");
});
async function postFeeds() {
const allFeeds = await getAllFeeds();
for (const channelID in allFeeds) {
try {
const resp = await fetch(
"https://www.youtube.com/feeds/videos.xml?channel_id=" + channelID,
);
const data = await parseFeed(await resp.text());
const latest = data.entries[0];
if (await getLatest(channelID) !== latest.id) {
for (const chatID of allFeeds[channelID]) {
await bot.api.sendMessage(
chatID,
`<b>New video from</b> <a href="https://youtube.com/channel/${channelID}">${
data.title.value ?? "channel"
}</a>\n\n<a href="${
latest.links[0].href
}">${latest.title?.value}</a>`,
{ parse_mode: "HTML" },
);
}
await storeLatest(channelID, latest.id);
}
} catch (e) {
console.log(e);
}
}
}
// Run Job in every 15 minutes
cron("1 */15 * * * *", () => {
postFeeds();
});