[Step-by-Step Guide] Find keywords, create and publish 150 articles to wordpress site in less than 30 minutes using GPTChat and Python/Google Colab

Worked well for me, but is there a way to generate image into the content as well?

And also do i need to run the code each time i need to write a post or it automatically loop through the keywords.txt and writes to wordpress?
You can automatically insert an image for example via the unsplash_api, which is easy to get.

But placing images inside the text, not sure about. Probably doable somehow but i think it makes the script (or any other similar) more complex than necessary.
 
You can automatically insert an image for example via the unsplash_api, which is easy to get.

But placing images inside the text, not sure about. Probably doable somehow but i think it makes the script (or any other similar) more complex than necessary.
Thanks
 
Worked well for me, but is there a way to generate image into the content as well?

And also do i need to run the code each time i need to write a post or it automatically loop through the keywords.txt and writes to wordpress?

Hello, i tried to add automatic images via openai API, but the quality of the pictures is not the best. I mean it is probably best to add pictures manually in any case. Because it takes 3-5 tries to get a good image from dalle or other tools.

But adding images automatically is possible I will add if there is interest. I can put it at the end of the post just for SEO, so it does not matter if the picture is not top notch.

It loops, you just specify where to begin and where to end. For example one day you do 0-50 and another day you do 51-100 i.e.
 
I confirm, the code is working.
I am able to flood my website with articles.
 
Now lets add image post function.

It uses openai API as wee (dalle api), so you should check how much does it cost, but I believe it is pretty cheap.

Here are the main settings, you can choose if you want to add images, and also if you wanna make them features images, or just put them at the end of post. Quality of Dalle images is pretty good, but sometimes you need to play with prompt to be able to create exactly the image you want.
Code:
create_and_add_an_image = "yes" #can be yes or no
make_the_image_featured = "yes" #can be yes or no
image_prefix = "A detailed high quality natural image about: "
image_resolution="512x512"

if you choose create_and_add_an_image and make_the_image_featured it will post the image as featured and add it to the post at the top left. You can also change HTML from the code as per your needs.

Here is complete code, which consist of 2 parts, the same as before:


#cell 1
Code:
import openai
import os
openai.api_key = "your_open_ai_api_key"

def upload_image(filename,your_site,your_user,your_password):
    import requests, json
    api_url_image = your_site+'/wp-json/wp/v2/media'
    the_pic = open(filename, 'rb').read()
    fnm = os.path.basename(filename)
    result = requests.post(
        url=api_url_image,
        data=the_pic,
        headers={ 'Content-Type': 'image/jpg','Content-Disposition' : 'attachment; filename=%s'% fnm},
        auth=(your_user, your_password)
        )

    response =result.json()
    the_image_id = response.get('id')
    the_image_url = response.get('guid').get("rendered")
    return (the_image_id, the_image_url)

def make_post(the_title,the_text,your_user,your_password,your_site,wordpress_category,the_image_id):
        import requests
        import base64
        your_credentials = your_user + ":" + your_password
        your_token = base64.b64encode(your_credentials.encode())
        your_header = {'Authorization': 'Basic ' + your_token.decode('utf-8')}
 
        api_url = your_site+'/wp-json/wp/v2/posts'
      
        if the_image_id>0:
            if not wordpress_category == "":
                data = {
                    'title' : the_title,
                    'status': 'publish',
                    'content': the_text,
                    'categories': 3,
                    'featured_media': the_image_id
                    ##'slug' : 'example-post',
                    }
            else:
                data = {
                    'title' : the_title,
                    'status': 'publish',
                    'content': the_text,
                    'featured_media': the_image_id
                    ##'slug' : 'example-post',
                    }
        else:
            if not wordpress_category == "":
                data = {
                    'title' : the_title,
                    'status': 'publish',
                    'content': the_text,
                    'categories': 3,
                    }
            else:
                data = {
                    'title' : the_title,
                    'status': 'publish',
                    'content': the_text,
                    }                  
              
              
        response = requests.post(api_url,headers=your_header, json=data)
        return response.json()

def gpt_chat(all_params):
    the_keyword,the_prefix,the_temperature,the_max_tokens = all_params
    the_text = the_prefix + the_keyword + ":"
        #the_text =  the_prefix + the_text
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": the_text}],
        temperature=the_temperature,
        max_tokens=the_max_tokens
        )
 
    the_result = response["choices"][0]["message"]["content"]
 
    return the_result

def fix_ahrefs_keywords(file_with_keywords):
    #remove empty lines and non keyword lines from output of https://ahrefs.com/keyword-generator
    with open(file_with_keywords, 'r') as fyl:
        lines = fyl.readlines()
 
    good_lines = []
    for aline in lines:
        aline = aline.strip()
        if (not any(str.isdigit(x) for x in aline) or len(aline.split())>3) and not aline.strip()=="" and not "Sign up" in aline and not "N/A" in aline:
            good_lines.append(aline)
 
 
    
    with open(file_with_keywords, 'w') as f:
        for line in good_lines:
            f.write(f"{line}\n")

#load file with your keywords
file_with_keywords = "sample_data/keywords.txt"
#this step fixes the file with keywords from https://ahrefs.com/keyword-generator
fix_ahrefs_keywords(file_with_keywords)


#cell 2
Code:
# SETTINGS
begin_index = 11
end_index = 12
your_site = "yur site url"
your_user = "your site username"
your_password = "your site application password"
wordpress_category = "" # or you can add here a category id
title_is_keyword = "yes" #cam be "yes" or "no". If yes then the title is the keyword, if no then the title is created by GPTCHAT
remove_ai_detection = "no"

create_and_add_an_image = "yes" #can be yes or no
make_the_image_featured = "yes" #can be yes or no
image_prefix = "A detailed high quality natural image about: "
image_resolution="512x512"


#prefix = "Write an article about"
prefix = "Write a very extremelly long and detailed article about "
#load the fixed keywords
with open(file_with_keywords, 'r') as fyl:
    keywords = fyl.readlines()
keywords = [x.strip() for x in keywords]
 
#now we create posts using GPT-chat and post them to our wordpress site
for e,akeyword in enumerate(keywords):
 
    if e<begin_index or e>=end_index:continue #this makes sure we only add article from begin to end
    the_temperature = 0.7
    the_max_tokens = 2000
    all_params = akeyword,prefix,the_temperature,the_max_tokens
    print("we are writing post #",e,", using keyword:",akeyword)
    gptchat_article = gpt_chat(all_params)
    title = akeyword.title()


    the_image_url = ""
    the_image_id = -1
    if create_and_add_an_image == "yes":   
        response = openai.Image.create(
            prompt= image_prefix + akeyword,
            n=1,
            size=image_resolution
            )
      
        image_url = response['data'][0]['url']
        image_file = "sample_data/" + str(e)+'.jpeg'
        import urllib.request
      
        #download the image to file image_file
        urllib.request.urlretrieve(image_url, image_file)      
      
        if not make_the_image_featured=="yes":the_image_id = -1
      
        try:
            the_image_id,the_image_url = upload_image(image_file,your_site,your_user,your_password)
            print("image_url",the_image_url)                
        except Exception as error:
            print("we could not upload image",error)


    try:
        gptchat_article_list = gptchat_article.split("\n")
        if gptchat_article_list[0].count(".")<=1 and gptchat_article_list[1].strip()=="":
            title = gptchat_article_list[0]
            gptchat_article = gptchat_article.replace(title,"").strip()
            if title_is_keyword=="yes":
                title = akeyword.title()
    except:pass

    if not the_image_url.strip()=="":
        if make_the_image_featured=="yes":
            image_insert_html_code =  '<img src="'+the_image_url +'" alt="'+akeyword+'" style="float: left; margin-right: 10px;">'            
            gptchat_article = image_insert_html_code + gptchat_article
        else:
            image_insert_html_code =  '<img src="'+the_image_url +'" alt="'+akeyword+'" style="margin:10px;">'            
            gptchat_article =  gptchat_article + image_insert_html_code 
 
 
    #now we post to out wordpres site
    try:
        the_response = make_post(title,gptchat_article,your_user,your_password,your_site,wordpress_category,
,the_image_id
)
        the_link = the_response['guid']['rendered']
        print("the_link",the_link,"word count",len(gptchat_article.split()),"the_title:",title)
    except Exception as err:
        print("we have an error",err)
 
Last edited:
Worked well for me, but is there a way to generate image into the content as well?

And also do i need to run the code each time i need to write a post or it automatically loop through the keywords.txt and writes to wordpress?

Now it is able to post images as well.

I confirm, the code is working.
I am able to flood my website with articles.

Thanks, you can also use the new version of the code that can add images as well.
 
I have successfully published the article! This is amazing and will change my workflow. Thank you. However, I don't quite understand the third step regarding the process of adding keywords. Can I input them manually? Or does this relate to the first step? thank you.
 
I have successfully published the article! This is amazing and will change my workflow. Thank you. However, I don't quite understand the third step regarding the process of adding keywords. Can I input them manually? Or does this relate to the first step? thank you.

Did you use the version that also adds photos in the post? [in one of my posts on this page]

To answer your question, yes, you can add keywords manually as well in the file. This will work just fine. I just made this script that filter out any non keywords and empty lines that you get when you you copy/paste from ahrefs.
 
Amazing article, thanks a lot. Tested and works pretty well
 
we have an error list indices must be integers or slices, not str




 
we have an error list indices must be integers or slices, not str


try to remove line
Code:
print("the_link",the_link,"word count",len(gptchat_article.split()),"the_title:",title)

or just add # in front of it.

from
Code:
    #now we post to out wordpres site
    try:
        the_response = make_post(title,gptchat_article,your_user,your_password,your_site,wordpress_category)
        the_link = the_response['guid']['rendered']
        print("the_link",the_link,"word count",len(gptchat_article.split()),"the_title:",title)
    except Exception as err:
        print("we have an error",err)
 
i want to try this today, but i wish to ask a question, what if i have two to three same keywords , will the code skip some or post it all ?
 
i got this error File "<ipython-input-8-11dffa4f5db4>", line 82 ,the_image_id ^SyntaxError: invalid syntax

I found error, an extra comma:

change last part:
Code:
    #now we post to out wordpres site
    try:
        the_response = make_post(title,gptchat_article,your_user,your_password,your_site,wordpress_category,
,the_image_id
)

with this
Code:
    #now we post to out wordpres site
    try:
        the_response = make_post(title,gptchat_article,your_user,your_password,your_site,wordpress_category
,the_image_id
)

or just remove comma after wordpress_category. Then let me know if it works.
 
i want to try this today, but i wish to ask a question, what if i have two to three same keywords , will the code skip some or post it all ?
It would post all keywords, but deduplicating keywods is pretty easy.
 
I found error, an extra comma:

change last part:
Code:
    #now we post to out wordpres site
    try:
        the_response = make_post(title,gptchat_article,your_user,your_password,your_site,wordpress_category,
,the_image_id
)

with this
Code:
    #now we post to out wordpres site
    try:
        the_response = make_post(title,gptchat_article,your_user,your_password,your_site,wordpress_category
,the_image_id
)

or just remove comma after wordpress_category. Then let me know if it works.
it worked with not errors, but this issues now is that, it didnt add any post to my WP
 
I just re-tried the same code, and it works fine.

#1 - maybe you did not have enough keywords
If you use this it would only post article and photo based on the first keyword.
Code:
begin_index = 0
end_index = 1

#2 maybe username was not correct.
The username should be username from wordpress install not the name of the the application password.
 
Back
Top