-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
99 lines (83 loc) · 2.72 KB
/
index.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
// noinspection JSIgnoredPromiseFromCall
import 'dotenv/config';
import { Client } from "@notionhq/client";
import { Bot } from "grammy";
import { ListBlockChildrenResponse } from "@notionhq/client/build/src/api-endpoints";
const notion = new Client({ auth: process.env.NOTION_ACCESS_TOKEN });
const bot = new Bot(process.env.BOT_TOKEN);
// Type-guard
function isTodo <T extends Record<string, unknown>>(obj: T): obj is T & { type: 'to_do' } {
return 'type' in obj && obj.type === 'to_do';
}
// Checks if link already exists in Notion page
function alreadyExists(link: string, list: ListBlockChildrenResponse) {
for (const result of list.results) {
if (isTodo(result)) {
if (result.to_do.rich_text[0].href == link) {
return true;
}
}
}
}
// Pushes link to the end of specified Notion block
async function pushToNotion(postText, postURL) {
const response = await notion.blocks.children.append({
block_id: process.env.BLOCK_ID,
children: [
{
object: "block",
type: "paragraph",
paragraph: {
rich_text: [{
type: "text",
text: {
content: postText,
link: {
url: postURL
}
}
}],
},
},
],
});
console.log(response);
}
async function redirect(itemText, item) {
for (let entity of item) {
if (entity.type === "url") {
let link = itemText.slice(entity.offset, entity.length);
await pushToNotion(link, link);
} else if (entity.type === "text_link") {
let link = itemText.slice(entity.offset, entity.length);
console.log(link);
await pushToNotion(link, entity.url);
}
}
}
bot.api.setMyCommands([{ command: "start", description: "Starts the bot" }]);
bot.command("start", (ctx) => {
// Returns chat info
console.log(`Incoming chat`, ctx.chat);
});
// bot.on("message", (ctx) => console.log("Chat id", ctx.chat.id));
bot.on("message::url", async (ctx) => {
const links = [
ctx.msg?.text,
ctx.msg?.entities,
ctx.msg?.caption,
ctx.msg?.caption_entities,
];
const [text, entities, caption, captionEntities] = links;
console.log(ctx.msg);
if (entities) {
await redirect(text, entities);
} else if (captionEntities) {
await redirect(caption, captionEntities);
} else {
await ctx.reply("Unknown message structure");
}
});
bot.start({
onStart: () => console.log("Started...")
});