Trying to create a Python bot to post to Wordpress site (Python)

125 views Asked by At

I am testing an auto posting bot to post content to a blog site set up on wordpress.org site hosted on siteground. I am still relatively new to this and after a lot of work I've managed to no longer receive 401 and 400 errors however when I run this code the output states 'Post Created Successfully' but on my posts page and blog page nothing is happening.

I have tried this without a defined user agent and then with a different, defined one, however the requests are being received but no posts are being created. Support from the host has suggested it is the user agent being flagged as 'bad bot' but I am not sure what that is and how to solve it since i am simply trying to post on my own test blog website.

import base64
import json
import urllib3

def create_post(title, content, username, password, url):
api_url = f"{url}/wp-json/wp/v2/posts"

    credentials = f"{username}:{password}"
    encoded_credentials = base64.b64encode(credentials.encode('utf-8')).decode('utf-8')
    
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Basic {encoded_credentials}",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36"
    }
    data = {
        "title": title,
        "content": content,
        "status": "publish"
    }
    
    http = urllib3.PoolManager(headers=headers)
    response = http.request('POST', api_url, body=json.dumps(data), headers=headers)
    
    if response.status == 200:
        print("Post created successfully.")
    else:
        print(f"Failed to create post. Status code: {response.status}")
        print("Response content:", response.data)

if __name__ == "__main__":
title = "Sample Blog Title"
content = "<p>This is a sample blog content.</p>"
username = "MY_USERNAME"
password = "MY_PASSWORD"
url = "https://gpayments.io/wp-login.php"

    create_post(title, content, username, password, url)

They stated that requests are succeeding, which are also shown by my sites access logs, however due to the User Agents being flagged as 'bad bots' they are being prevented from posting.

I was wondering if anyone had any suggestions, as I am completely stuck here and would like to eventually set up a bot that can consistently post automatically.

For reference, I have tried posting manually from Jupyter notebook, as well as uploaded the script directly to my siteground folders and executed via PuTTY but both give the same results.

Any suggestions would bee really appreciated, thank you!

0

There are 0 answers