const axios = require('axios');
const NOTION_API_URL = 'https://api.notion.com/v1';
const NOTION_TOKEN = process.env.KEYBOARD_NOTION_BLOG_INTERNAL_SECRET;
console.log('š Creating new blog post in Notion...');
const randomCovers = [
'https://images.unsplash.com/photo-1486312338219-ce68d2c6f44d?w=1500&q=80',
'https://images.unsplash.com/photo-1516321318423-f06f85e504b3?w=1500&q=80',
'https://images.unsplash.com/photo-1461749280684-dccba630e2f6?w=1500&q=80',
'https://images.unsplash.com/photo-1498050108023-c5249f4df085?w=1500&q=80',
'https://images.unsplash.com/photo-1504639725590-34d0984388bd?w=1500&q=80',
'https://images.unsplash.com/photo-1611224923853-80b023f02d71?w=1500&q=80',
'https://images.unsplash.com/photo-1519389950473-47ba0277781c?w=1500&q=80',
'https://images.unsplash.com/photo-1517077304055-6e89abbf09b0?w=1500&q=80',
'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=1500&q=80',
'https://images.unsplash.com/photo-1434030216411-0b793f4b4173?w=1500&q=80',
'https://images.unsplash.com/photo-1551288049-bebda4e38f71?w=1500&q=80',
'https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=1500&q=80',
'https://images.unsplash.com/photo-1555421689-491a97ff2040?w=1500&q=80',
'https://images.unsplash.com/photo-1581291518857-4e27b48ff24e?w=1500&q=80',
'https://images.unsplash.com/photo-1531297484001-80022131f5a1?w=1500&q=80'
];
async function findBlogDatabase() {
try {
const response = await axios({
method: 'POST',
url: `${NOTION_API_URL}/search`,
headers: {
'Authorization': `Bearer ${NOTION_TOKEN}`,
'Notion-Version': '2022-06-28',
'Content-Type': 'application/json'
},
data: {
filter: {
value: 'database',
property: 'object'
}
}
});
const blogDb = response.data.results.find(db =>
db.title?.[0]?.plain_text?.toLowerCase().includes('blog')
);
if (blogDb) {
console.log(`ā
Found blog database: ${blogDb.title[0].plain_text} (ID: ${blogDb.id})`);
return blogDb;
} else {
throw new Error('No database with "Blog" in the title found');
}
} catch (error) {
console.error('ā Error finding blog database:', error.response?.data || error.message);
throw error;
}
}
async function getDatabaseSchema(databaseId) {
try {
const response = await axios({
method: 'GET',
url: `${NOTION_API_URL}/databases/${databaseId}`,
headers: {
'Authorization': `Bearer ${NOTION_TOKEN}`,
'Notion-Version': '2022-06-28'
}
});
return response.data;
} catch (error) {
console.error('ā Error getting database schema:', error.response?.data || error.message);
throw error;
}
}
async function createBlogPost(databaseId, blogData) {
try {
const coverImage = blogData.useRandomCover
? randomCovers[Math.floor(Math.random() * randomCovers.length)]
: null;
if (coverImage) {
console.log('š¼ļø Selected random cover image');
}
const seoDescription = blogData.seoDescription ||
`Discover insights about ${blogData.title.toLowerCase()}. ${blogData.content.substring(0, 100)}...`;
const slug = blogData.title.toLowerCase()
.replace(/[^a-z0-9\s-]/g, '')
.replace(/\s+/g, '-')
.replace(/-+/g, '-')
.trim('-');
const pageData = {
parent: {
database_id: databaseId
},
properties: {
'Title': {
title: [{ text: { content: blogData.title } }]
},
'Status': {
status: { name: blogData.status }
},
'Category': {
select: { name: blogData.category }
},
'Tags': {
multi_select: Array.isArray(blogData.tags)
? blogData.tags.map(tag => ({ name: tag.trim() }))
: blogData.tags.split(',').map(tag => ({ name: tag.trim() }))
},
'Publish Date': {
date: { start: new Date().toISOString().split('T')[0] }
},
'Framer Slug': {
rich_text: [{ text: { content: slug } }]
},
'SEO Description': {
rich_text: [{ text: { content: seoDescription } }]
},
'Content': {
rich_text: [{ text: { content: blogData.content } }]
}
},
children: [
{
object: 'block',
type: 'paragraph',
paragraph: {
rich_text: [{
type: 'text',
text: { content: 'š ' + blogData.content },
annotations: { bold: true }
}]
}
},
{
object: 'block',
type: 'divider',
divider: {}
},
{
object: 'block',
type: 'heading_2',
heading_2: {
rich_text: [{ text: { content: 'Introduction' } }]
}
},
{
object: 'block',
type: 'paragraph',
paragraph: {
rich_text: [{
text: { content: `Welcome to this post about ${blogData.title.toLowerCase()}. This content was created automatically and is ready for you to customize and expand upon.` }
}]
}
},
{
object: 'block',
type: 'callout',
callout: {
rich_text: [{
text: { content: '⨠This blog post was created using automation! Edit and customize as needed.' }
}],
icon: { emoji: 'āØ' }
}
},
{
object: 'block',
type: 'heading_3',
heading_3: {
rich_text: [{ text: { content: 'Key Points' } }]
}
},
{
object: 'block',
type: 'bulleted_list_item',
bulleted_list_item: {
rich_text: [{ text: { content: 'Automatically generated content structure' } }]
}
},
{
object: 'block',
type: 'bulleted_list_item',
bulleted_list_item: {
rich_text: [{ text: { content: 'SEO-optimized slug and description' } }]
}
},
{
object: 'block',
type: 'bulleted_list_item',
bulleted_list_item: {
rich_text: [{ text: { content: 'Professional cover image automatically selected' } }]
}
},
{
object: 'block',
type: 'paragraph',
paragraph: {
rich_text: [{
text: { content: 'Add your own content here and customize this post to make it uniquely yours!' }
}]
}
}
]
};
if (coverImage) {
pageData.cover = {
type: 'external',
external: {
url: coverImage
}
};
}
const response = await axios({
method: 'POST',
url: `${NOTION_API_URL}/pages`,
headers: {
'Authorization': `Bearer ${NOTION_TOKEN}`,
'Notion-Version': '2022-06-28',
'Content-Type': 'application/json'
},
data: pageData
});
return response.data;
} catch (error) {
console.error('ā Error creating blog post:', error.response?.data || error.message);
throw error;
}
}
async function main() {
try {
const blogData = {
title: '{{title}}',
status: '{{status}}',
category: '{{category}}',
tags: {{tags}},
author: '{{author}}',
content: '{{content}}',
seoDescription: '{{seoDescription}}' || null,
useRandomCover: {{useRandomCover}}
};
console.log(`š Creating blog post: "${blogData.title}"`);
const blogDb = await findBlogDatabase();
await getDatabaseSchema(blogDb.id);
const newPost = await createBlogPost(blogDb.id, blogData);
const verifyResponse = await axios({
method: 'GET',
url: `${NOTION_API_URL}/pages/${newPost.id}`,
headers: {
'Authorization': `Bearer ${NOTION_TOKEN}`,
'Notion-Version': '2022-06-28'
}
});
console.log('\nā
SUCCESS! Blog post created and verified!');
console.log('š Details:');
console.log(` š Title: ${verifyResponse.data.properties.Title?.title?.[0]?.text?.content}`);
console.log(` š Status: ${verifyResponse.data.properties.Status?.status?.name}`);
console.log(` š·ļø Category: ${verifyResponse.data.properties.Category?.select?.name}`);
console.log(` š·ļø Tags: ${verifyResponse.data.properties.Tags?.multi_select?.map(tag => tag.name).join(', ')}`);
console.log(` š¼ļø Cover: ${verifyResponse.data.cover ? 'Notion cover image set' : 'No cover'}`);
console.log(` š URL: ${verifyResponse.data.url}`);
console.log(` š Page ID: ${newPost.id}`);
} catch (error) {
console.error('ā Script failed:', error.message);
}
}
main();