Ir para

[Guia passo a passo] Encontre palavras-chave, crie e publique 150 artigos no site wordpress em menos de 30 minutos.


Posts Recomendados

Boa tarde Guerreiros.

Hoje irei passar um conteúdo que eu achei na gringa e que vocês podem aplicar.

Então bora pra oq realmente interessa:

[Guia passo a passo] Encontre palavras-chave, crie e publique 150 artigos no site wordpress em menos de 30 minutos usando GPTChat e Python/Google Colab

  • Demora menos de 30 minutos para começar a postar 150 posts em seu site wordpress, e não deve demorar mais de 1 hora para tê-los todos online.
  • Método 100% gratuito, exceto que precisamos de uma chave de API GPTChat. Mas você pode obter uma avaliação gratuita de 5 dólares, então também pode ser gratuita
  • Criamos 150 palavras-chave usando a ferramenta gratuita ahrefs - https://ahrefs.com/keyword-generator
  • Colamos algum código no Google colab.
  • Certifique-se de não tornar pública sua colaboração do Google por segurança. Deve ser privado por padrão, mas é melhor verificar isso o tempo todo.
  • Este código é responsável por criar postagens via API GPTChat e postar em seu site wordpress.
  • Criamos credencial para site wordpress poder postar lá
  • Nós decidimos quantas postagens queremos e depois clicamos em um botão
  • Ele é postado automaticamente depois que clicamos em um botão.


Vamos começar...
1) Acesse https://ahrefs.com/keyword-generator e adicione qualquer palavra-chave desejada. Selecione as palavras-chave e as perguntas exatamente assim e cole-as em um arquivo txt. O arquivo de palavras-chave ficará assim, é confuso, mas iremos formatá-lo automaticamente usando python.
02) Agora precisamos criar nosso próprio Google Colab (que também é 100% gratuito), acesse https://colab.google/ e clique em Novo Notebook É assim que fica, só precisamos adicionar alguns linhas de código, crie o arquivo e estamos prontos para começar

keyword01.thumb.png.c69ded1dea57bc800fdeaaa6e1d74a0f.png

kwfile.thumb.png.df373fb0dcce01793bf7781e3e37c912.png

colaba.thumb.png.50e8ad8919b46a9991f42de8eadb47d8.png

colabb.thumb.png.7757df1de681bb34e2e29c239e24054f.png

 

 

 

 

 

 

Adicione este código à primeira linha, esta instalação openai:

 !pip install openai --quiet

 

Este código precisa ser adicionado à segunda linha, ele formata palavras-chave e contém todas as funções:
 

import openai
import os
openai.api_key = "your_open_ai_api_key"

def make_post(the_title,the_text,your_user,your_password,your_site,wordpress_category):
        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 not wordpress_category == "":
            data = {
                'title' : the_title,
                'status': 'publish',
                'content': the_text,
                'categories': 3
                ##'slug' : 'example-post',
                }
        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)

 

Adicione este código à terceira linha:
 

# 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"


#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()
 
    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
 
 
    #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)

 

Deve ficar assim:

03) O próximo passo é criar um arquivo com palavra-chave e colar as palavras-chave que já temos. Clicamos na pasta à esquerda e criamos um arquivo na pasta sample_data chamado keywords. 

4) Em seguida, clicamos nas palavras-chave e adicionamos as palavras-chave.

05) Agora que a parte da palavra-chave está concluída, só precisamos adicionar as credenciais do WordPress e estamos prontos para começar. Vamos para Usuários/perfil no painel do WordPress e então criamos um novo nome de senha do aplicativo. Este é apenas o nome da senha, não a usamos em nenhum outro lugar. Então, depois de adicioná-lo, clicamos em Adicionar nova senha do aplicativo. Esta é a senha que precisamos copiar e adicionar ao Google Colab.

06) Em seguida adicionamos nossas configurações que acabamos de criar:
 

 

 

 

 

colabb.thumb.png.7757df1de681bb34e2e29c239e24054f.png

colabmmmm1111.thumb.png.b485aa70d175c9c946fa9083da1145bd.png

wodpress.png.9e46058dc609dfcb2e8a1e19f41def6b.png

settings.thumb.png.39429ad8beeb29c77de373281a4683cf.png

 

Para controlar quantas postagens você publica, altere o início_index e o índice final. Por exemplo, se begin_index=0 e end_index=1 ele postará apenas os primeiros posts. Para postar em seu site, você precisa clicar no botão Executar em cada célula. Existem 3 células, então você precisa clicar todas as vezes.
 

 

 

Agora vamos adicionar a função de postagem de imagem.

Ele usa API openai como wee (dalle api), então você deve verificar quanto custa, mas acredito que seja bem barato.

Aqui estão as configurações principais, você pode escolher se deseja adicionar imagens, e também se deseja torná-las imagens características, ou apenas colocá-las no final do post. A qualidade das imagens Dalle é muito boa, mas às vezes você precisa brincar com o prompt para poder criar exatamente a imagem desejada.

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"

 

se você escolher create_and_add_an_image e make_the_image_featured ele postará a imagem como destaque e a adicionará à postagem no canto superior esquerdo. Você também pode alterar o HTML do código conforme suas necessidades.

Aqui está o código completo, que consiste em 2 partes, o mesmo de antes:

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)

 

#célula 2

# 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)

 

Bom é isso, agora usem a imaginação de vocês e façam muito dinheiro usando esses conhecimentos. 

Se você achou que esse post te ajudou me ajude também com um comentario e um amei nesse post.

colabmaaa.png

Editado por Espartano Milionário
As imagens tinham ficado muito pequenas
Link para o comentário
  • 2 semanas depois...
  • 4 meses depois...
Cara, esse tutorial tá insano! Bem explicado e parece que facilita demais a vida de quem tem site em Wordpress. Pena que não rolou um videozinho mostrando na prática, ia ser top ver isso funcionando ao vivo. A ideia de usar GPTChat e Python pra automatizar a criação de conteúdo é game changer, hein. Vou testar aqui e ver no que dá. Tamo no corre pra fazer a grana entrar!
Link para o comentário
Atenção: Este conteúdo tem mais de 6 meses desde que foi postado. Verifique se o método ensinado nele ainda é válido para os dias atuais.
Infelizmente, seu conteúdo contém termos que não permitimos. Caso esteja tentando publicar seu número de WhatsApp, lembre-se que isso é proibido expor no Fórum.
Responder

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emojis são permitidos.

×   Seu link foi automaticamente incorporado.   Mostrar como link

×   Seu conteúdo anterior foi restaurado.   Limpar o editor

×   Não é possível colar imagens diretamente. Carregar ou inserir imagens do URL.

Processando...
×
×