Zeyad Etman
Home

Thoughts about software development and Life

  • Home
  • About
  • Gallery
  • Twitter
  • Github
  • Books
  • Notes
  • Building personal assistant bot with telegram

    0 Views

    6 min read

    notiontelegram-bottypescriptnodejs
    Bot Arm

    source

    In this post I’ll document what I’ve done to build a telegram bot that helps me track most of useful things i know, do, willing to share with public.

    Motivation

    I’ve created a wiki to share my bookmarks, links, articles, tools, …etc, but the problem was when you find good link or anything and want to add it to the wiki, in this situation I was open Gitbook dashboard, and searching for the document that i want to add to, then push and sync. That was taking a lot of time, and i had have to do this from my laptop super boring, isn’t it?

    The problem appears strongly when reading a book and add comments or notes, and want to track it or share it, similar thing to my IMDB reviews. All of this was annoying me to add to it, so I decided to build a bot that can collect these things and add them whenever I tell him to do so.

    Features

    Okay, now I’ve a problem with an idea to solve it. The first thing i was supposed to do is listing the main commands for this bot to understand.

    • /syncIMDB List all Movies/TV Series/Video Games ratings from IMDB.
    • /syncNotion Publishing pages to notes.zeyadetman.com from Notion.

    Starting the Bot Implementation

    So while I was thinking about how can i organize the bot object and its behaviors, I ended up with implement the Decorator design pattern.

    Decorator design pattern: In this pattern you have 4 main things:

    1. The main interface for your component and basic methods “without implementation”, in my case it’s the Bot.
    2. The main concrete component that implements the default behavior of component behaviors.
    3. The base decorator that act like a wrapper for concrete decorators.
    4. The concrete decorator is to call the object and alter it.

    Why? I have a monolithic class (Bot) with a bunch of behaviors and actions, like commands, configurations, messages, …etc, so i want to divide them into smaller classes that each class contains one behavior or action.

    I split the main features into multiple concrete decorators.

    • One to handle the BotCommands , every command starting with /
    1export class BotWithCommands extends DecoratorBot {
    2 private setCommands(bot) {
    3 bot.command("syncIMDB", syncIMDB);
    4 bot.start(start);
    5 bot.help(help);
    6 }
    7
    8 public launch() {
    9 this.setCommands(this.bot);
    10 super.launch();
    11 }
    12}
    13
    1import { DecoratorBot } from "../decorator";
    2import { documentEvent } from "./document";
    3
    4export class BotWithEvents extends DecoratorBot {
    5 private setEvents(bot) {
    6 bot.on("document", documentEvent);
    7 bot.on("sticker", (ctx: any) => ctx.reply("👍"));
    8 }
    9
    10 public launch() {
    11 this.setEvents(this.bot);
    12 super.launch();
    13 }
    14}
    15

    You can read the code to understand more about the implementation and the idea for these decorators.

    The final structure was something like this

    1.
    2├── commands
    3│   ├── help.ts
    4│   ├── index.ts
    5│   ├── start.ts
    6│   ├── syncIMDB.ts
    7│   └── syncNotion.ts
    8├── decorator
    9│   └── index.ts
    10├── events
    11│   ├── document.ts
    12│   └── index.ts
    13├── index.ts
    14├── types
    15└── utils
    16 ├── constants.ts
    17 ├── convert-name.ts
    18 └── writeFileToGithub.ts
    19

    /syncIMDB Create a list of my movies ratings

    This was the first thing i handled in the bot. The problem is I need to show a list of all my movies ratings, I use IMDB to track this, but IMDB doesn’t offer apis to get my ratings, So the solution that i use is exporting the ratings manually, and send this file to the bot telling him to update this file to re-format it into a json file, then add this file to the notes app, and GitHub action will redeploy the app updating the movies list on my notes app with these new ratings.

    I use nivo.rocks to visualize the genres and make the list more interactive. Please read my comment on how I implemented it.

    This was a little bit tricky especially because I’m using docusaurus.io but you can check the code for it from here.

    I use the same json file to add more pages with the same style.

    /syncNotion Notion integration

    The second thing is getting pages from notion. So the idea is creating a database on notion that contains multiple nested pages with their slugs/paths and this command will get the database by its id and fetching all pages under this databases including nested databases, then create commits with the files on Notes Repo on GitHub. That’s the idea I’ve came with.

    Here’s the code for it.

    1const handleDatabases = async (
    2 databaseId: string,
    3 pagesToPublish: any,
    4 parentSlug = ""
    5) => {
    6 return new Promise(async (resolve, reject) => {
    7 try {
    8 const { results } = await notion.databases.query({
    9 database_id: databaseId,
    10 });
    11 const pages = results.filter((res) => res.object === "page");
    12 pages.forEach(async (page: any) => {
    13 if (page?.properties?.Slug?.rich_text?.[0]?.plain_text) {
    14 pagesToPublish[page.properties.Slug.rich_text[0].plain_text] = {
    15 slug: page.properties.Slug.rich_text[0].plain_text,
    16 isPublish: page.properties?.Published?.checkbox || false,
    17 path: `${parentSlug || ""}${
    18 page.properties.Slug.rich_text[0].plain_text
    19 }`,
    20 page,
    21 };
    22 } else {
    23 return ctx.reply("Please add a slug to the page");
    24 }
    25 });
    26
    27 for await (let page of Object.values(pagesToPublish)) {
    28 const { slug, page: pageInfo } = page as any;
    29 const mdblocks = await n2m.pageToMarkdown(pageInfo.id);
    30 const finalMdBlocks = [];
    31 mdblocks?.forEach(async (block: any, index) => {
    32 if (index === mdblocks?.length - 1) {
    33 return;
    34 }
    35 if (block.type === "child_database") {
    36 const databaseId = block.parent.split("(").pop().split(")")[0];
    37 pagesToPublish[slug].children = {
    38 databaseId,
    39 slug,
    40 parentSlug: `${parentSlug || ""}${slug}`,
    41 };
    42 } else {
    43 finalMdBlocks.push(block);
    44 }
    45 });
    46
    47 pagesToPublish[slug].mdBlocks = finalMdBlocks;
    48 }
    49
    50 for await (let page of Object.keys(pagesToPublish)) {
    51 const { children, slug } = pagesToPublish[page] as any;
    52 if (children?.databaseId) {
    53 pagesToPublish[slug].childs = await handleDatabases(
    54 children.databaseId,
    55 {},
    56 `${children.parentSlug}`
    57 );
    58 }
    59 }
    60
    61 console.log(util.inspect(pagesToPublish, false, null, true));
    62 return resolve(pagesToPublish);
    63 } catch (error) {
    64 return reject(error.message);
    65 }
    66 });
    67};
    68

    And that’s works great with a sample of notion database like this:

    So if the page’s Published property is false, then the page will not be published to github repo, and if the page doesn’t have a Slug property it should gives an error, because the slug is a path of that file.

    The final command on telegram gave me this reply

    Wow! that’s totally awesome 😎


    Until then I’ll let this post ends in this point and will update it whenever I add new feature.

    …to be continued



    Updated at Tue Sep 28 2021

    Signature of the author