{"size": 1925, "ext": "js", "max_stars_repo_path": "telegram/index.js", "max_stars_repo_name": "maracuda/notion-integrations", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "telegram/index.js", "max_issues_repo_name": "maracuda/notion-integrations", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "telegram/index.js", "max_forks_repo_name": "maracuda/notion-integrations", "max_forks_repo_forks_event_min_datetime": "2022-01-04T17:24:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T17:24:05.000Z"}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1, "avg_line_length": 23.1927710843, "max_line_length": 76, "alphanum_fraction": 0.5381818182}
const { Client } = require("@notionhq/client");

const SHOW_LIST_TXT = "Покажи список";
const PAGE_ID = process.env.PAGE_ID;
const NOTION_TOKEN = process.env.NOTION_TOKEN;

const getObjectForTelegramResponse = (chatId, message) => {
  return {
    method: "sendMessage",
    chat_id: chatId,
    text: message,
    reply_markup: JSON.stringify({
      keyboard: [[{ text: SHOW_LIST_TXT }]],
    }),
  };
};

const getNotionList = (notion) => {
  return notion.blocks.children.list({ block_id: PAGE_ID }).then((resp) => {
    const mapped = resp.results
      .map((i) => {
        const firstLevel = (i.paragraph || i.to_do).text[0];
        if (firstLevel) {
          return firstLevel.text.content;
        }
      })
      .filter((i) => !!i);
    return mapped;
  });
};

const addToList = (notion, item) => {
  return notion.blocks.children.append({
    block_id: PAGE_ID,
    children: [
      {
        object: "block",
        type: "to_do",
        to_do: {
          text: [
            {
              type: "text",
              text: {
                content: item,
              },
            },
          ],
          checked: false,
        },
      },
    ],
  });
};

module.exports.main = (event) => {
  const notion = new Client({
    auth: NOTION_TOKEN,
  });

  if (event.message.text === SHOW_LIST_TXT) {
    return getNotionList(notion)
      .then((resp) => {
        return getObjectForTelegramResponse(
          event.message.chat.id,
          `-${resp.join("\n-")}\n\nhttps://www.notion.so/${PAGE_ID}`
        );
      })
      .catch((error) => {
        return getObjectForTelegramResponse(
          event.message.chat.id,
          JSON.stringify(error)
        );
      });
  }

  return addToList(notion, event.message.text).then((resp) => {
    return getObjectForTelegramResponse(
      event.message.chat.id,
      `Добавил "${event.message.text}" в список покупок!`
    );
  });
};
