How to generate hundreds of content for Hashnode using AI
How to generate hundreds of blog posts using AI with one click
Regularly creating engaging and informative blog posts is a key challenge for content creators and building a successful blog. With advancements in AI, tools like OpenAI have made it possible to automate content creation. As a Developer Advocate, I love sharing knowledge and writing blog posts. I am quite an active writer on Dev.to, Medium, Dzone and Hashnode. But let's accept that coming up with fresh ideas and writing consistently can be a bit overwhelming. I could automate this process using AI as everybody around me is trying to apply AI to their monotonous daily work routine. That's what I did, and I'm here to show you how you can do it too. This AI assistant can generate blog posts on various topics and publish them directly to Hashnode, making it a breeze to keep your blog updated.
Why Use AI for Content Creation?
I usually use AI for content generation for a few reasons:
Save time on brainstorming new ideas for a new article.
Writing a summary of my articles.
Explaining quite common steps of long developer documentation.
Since English is not my native, so I also use AI to correct my grammar mistakes.
Maintain a regular posting schedule without feeling tired.
To produce SEO-friendly content.
Sometimes to generate short code samples in Python for tutorials. Be aware that you need to be an experienced software engineer to review AI-generated code, and correct and optimize it if it is necessary. When I ask AI to write code, I always know what should be the final ideal code.
Generate thousands of posts quickly to meet increased demand from our marketing team.
While AI can significantly accelerate content creation, it's important to remember that it cannot replace human creativity and intuition. The AI-generated content should be reviewed and refined to ensure it aligns with your voice and meets your quality standards.
There are several powerful paid AI tools available today that can help with content generation. However, I could not find a specific example where I can post automatically AI-generated content to Hashnode. So, I decided to develop my free-to-use tool from scratch and share my experience with the community.
Setting Up the AI Powered Content Generator
The process involves simply writing a Python script to use OpenAI to generate content and Hashnode GraphQL to publish it. We use AI models like OpenAI's GPT4o to create written content automatically. These models can generate coherent, informative, and engaging content based on the input knowledge and prompts you provide. The Hashnode GraphQL API allows us to interact programmatically with Hashnode's blogging platform. It provides powerful features for creating, managing, and retrieving content. With this API, you can publish posts, manage user profiles, retrieve publication details, and more, all through GraphQL queries and mutations. You can also play with the API playground.
Let's learn how you can set up it yourself.
Prerequisites
To start with this project, you'll need the following:
Your Hashnode publication ID and user ID
Python is installed on your machine.
Download and Install Pip to manage project packages.
Step 1: Set Up Your Environment
Create a .env file to store your API keys and other credentials. This will help keep your secrets safe and make your code cleaner.
OPENAI_API_KEY=your_openai_api_key
HASHNODE_API_KEY=your_hashnode_api_key
HASHNODE_PUBLICATION_ID=your_hashnode_publication_id
HASHNODE_USER_ID=your_hashnode_user_id
TOPICS="List of semicolon separated topics you want to generate content about"
Step 2: Install the required libraries
Install the necessary Python libraries. Use the following pip commands to install the required libraries:
pip install openai requests python-dotenv
Step 3: Generate a Blog Post Using OpenAI
Use the OpenAI API to generate a blog post based on a given action. Here's a full sample code snippet (hashnode_content_generator.py) to get you started:
import os
import openai
import requests
from dotenv import load_dotenv
import json
# Load environment variables
load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
HASHNODE_API_KEY = os.getenv("HASHNODE_API_KEY")
HASHNODE_PUBLICATION_ID = os.getenv(
"HASHNODE_PUBLICATION_ID"
)
HASHNODE_USER_ID = os.getenv("HASHNODE_USER_ID")
# OpenAI API settings
openai.api_key = OPENAI_API_KEY
def read_file(file_path):
with open(
file_path, "r", encoding="utf-8"
) as file:
return file.read()
def generate_post(topic):
assistant_description = read_file(
"assistant_description.txt"
)
prompt_template = read_file(
"prompt_template.txt"
)
response = openai.chat.completions.create(
model="gpt-4o",
response_format={"type": "json_object"},
messages=[
{
"role": "system",
"content": f"{assistant_description}",
},
{
"role": "user",
"content": f"{topic} {prompt_template}",
},
],
max_tokens=2000,
temperature=0.5,
)
post_content = response.choices[
0
].message.content.strip()
post_json = json.loads(post_content)
return (
post_json["title"],
post_json["subtitle"],
post_json["contentMarkdown"],
)
def generate_cover_image(topic_name):
response = openai.images.generate(
model="dall-e-3",
prompt=f"Draw image for: {topic_name}",
quality="standard",
n=1,
)
image_url = response.data[0].url
return image_url
def publish_to_hashnode(
title, subtitle, content, cover_image_url
):
url = "https://gql.hashnode.com/"
headers = {
"Authorization": f"{HASHNODE_API_KEY}",
}
query = """
mutation PublishPost($input: PublishPostInput!) {
publishPost(input: $input) {
post {
id
}
}
}
"""
variables = {
"input": {
"title": title,
"subtitle": subtitle,
"publicationId": HASHNODE_PUBLICATION_ID,
"contentMarkdown": content,
"disableComments": False,
"publishAs": HASHNODE_USER_ID,
"settings": {
"scheduled": False,
"enableTableOfContent": False,
"slugOverridden": False,
"isNewsletterActivated": False,
"delisted": False,
},
"coverImageOptions": {
"coverImageURL": cover_image_url
},
"tags": [
{"id": "56744721958ef13879b94d67"}
],
}
}
response = requests.post(
url,
json={
"query": query,
"variables": variables,
},
headers=headers,
)
return response.json()
def main():
topics = os.getenv("TOPICS").split(";")
for topic in topics:
title, subtitle, content = generate_post(
topic
)
print(
f"Generated Post Content for topic '{topic}':"
)
print(content)
cover_image_url = generate_cover_image(
topic
)
print(
f"Generated cover image for topic '{topic}':"
)
print(cover_image_url)
response = publish_to_hashnode(
title,
subtitle,
content,
cover_image_url,
)
print(
f"Hashnode Response for topic '{topic}':"
)
print(response)
if __name__ == "__main__":
main()
The above script generates blog posts based on custom knowledge and instructions you write for AI in assistant_description.txt and prompt_template.txt. Additionally, it creates a cover image for each post using OpenAI's DALL-E model, ensuring the visual appeal matches the content's quality.
Step 4: Define Sample Files for AI
Create assistant_description.txt with the following content:
You are a great content creator for Python developers. You have deep knowledge of the latest technologies. Your task is to help generate informative and engaging blog posts about our product.
Create prompt_template.txt with the following content:
Write a blog post at least 500 words on how to style about {topic}. Use simple words as it's written by a human Python developer. Blog post should be SEO friendly, use powerful keywords.
...
To get the best results from OpenAI, you might need some tips:
Clearly state what you want the AI to generate while you craft your prompt.
Give background information or a detailed description. Provide more information about your topic. For example, you can also use OpenAI's assistant API to provide more details about the topic by uploading a file. Additionally, integrating vector search capabilities can help the AI understand and reference your custom knowledge base, making the content even more relevant and accurate. For more details, you can refer to the OpenAI API documentation or explore how to use markdown files to train your AI with specific knowledge.
Show the AI how you want the content structured.
Indicate the desired tone or style of writing.
Step 5: Running the script
To run the script, simply execute the following command in your terminal:
python hashnode_content_generator.py
When you run the script, it performs the following tasks:
Generates post content: Using OpenAI, the script generates blog post content based on the topics provided. It outputs the generated title, subtitle, and content for each topic.
Creates cover image: The script uses OpenAI's DALL-E model to generate a cover image for each blog post topic and outputs the URL of the generated image.
Publishes to Hashnode: The script publishes the generated blog posts along with their cover images to Hashnode using its GraphQL API. It outputs the response from Hashnode, confirming the publication of each post.
You will see printed messages in your terminal for each step, showing the generated content, image URL, and Hashnode's response with the created post ID. This way, you can verify the successful execution of the script and the creation of your blog posts.
Conclusion
This script demonstrated how you can leverage AI to generate hundreds of blog posts for various topics, saving valuable time for other important tasks.
I hope this post inspires you to explore the possibilities of AI in content generation. Happy blogging! Follow me on LinkedIn to stay updated about new articles I share.