Automate WordPress Post Share on Twitter
The following Python script will pick up a random post from your WordPress MySQL database and share it on Twitter. Since even simple shared hosting providers support Python, you can set up this script as a cron jon to share posts periodically. Shared posts are temporary saved in the database in order to not repeat them until a certain amount of shared posts has been reached (customizable via the --repeat-limit
option). PyMySQL and Tweepy are required, so make sure to install them before running the script:
pip install pymysql tweepy
When invoking the script you will need to pass your MySQL, Twitter API and SMTP credentials. SMTP is used to send an email with the proper traceback when the execution fails (but feel free to comment out the send_error_email()
definition and call if you don't need that feature.)
For example:
python ./wpshare.py \ --repeat-limit 30 --db-host mysql.mywordpresssite.com \ --db-port 3306 \ --db-name mysql_database_name \ --db-user mysql_database_user \ --db-password mysql_database_password_123 \ --tw-consumer-key YvcXqGktK22oQsuf8czI3bXvk \ --tw-consumer-secret pe9RtHehkg9cMstJgidpKMOcNt8eLIv2QeG51tR8qXUDdt2jow \ --tw-access-token kc7c4FvxZN7hH8AowEuQ-znPBzkdzOCU6i29ehTF2CRvZFbaIN \ --tw-access-token-secret Sm4LqyguaaaNyEYpVVXCmlqgjhC9N3BNWt6l5EpsmFtzd \ --email-to admin@mywordpresssite.com \ --email-from noreply@mywordpresssite.com \ --email-password noreply_password_123 \ --smtp-host smtp.mywordpresssite.com \ --smtp-port 465
python .\wpshare.py ` --repeat-limit 30 ` --db-host mysql.mywordpresssite.com ` --db-port 3306 ` --db-name mysql_database_name ` --db-user mysql_database_user ` --db-password mysql_database_password_123 ` --tw-consumer-key YvcXqGktK22oQsuf8czI3bXvk ` --tw-consumer-secret pe9RtHehkg9cMstJgidpKMOcNt8eLIv2QeG51tR8qXUDdt2jow ` --tw-access-token kc7c4FvxZN7hH8AowEuQ-znPBzkdzOCU6i29ehTF2CRvZFbaIN ` --tw-access-token-secret Sm4LqyguaaaNyEYpVVXCmlqgjhC9N3BNWt6l5EpsmFtzd ` --email-to admin@mywordpresssite.com ` --email-from noreply@mywordpresssite.com ` --email-password noreply_password_123 ` --smtp-host smtp.mywordpresssite.com ` --smtp-port 465
Some of these parameters are optional, see lines 173-193 in the code below for default values. SSL is used by default for sending emails. If you want to use TLS instead, include the --smtp-tls
parameter. If you want to test the script before it actually tweets anything, pass the --test
option, which will print the tweet content instead of sending it to the API. Emails get printed too when --test
is present, although you still need to provide valid credentials.
Without further ado, here's the code. It is pretty simple so you can easily tweak it according to your needs. I've been using it in production for a couple of years.
Donate ❤️
Found our post useful? You can support us with a little donation!
Comments