Pages

Search Mp3 on google

Saturday, August 2, 2025

1254

Blogger Auto-Poster Course

Create a Blogger Auto-Poster with Python (.exe) - Part 1: The Foundation

Welcome to the first part of our course! In this section, we will lay the essential groundwork for our application. Our goal is to create a simple Python script that can securely connect to your Google account and publish a hard-coded test post to one of your Blogger blogs. This will confirm our connection to the Blogger API is working perfectly.

What You'll Achieve in Part 1:

  • Set up a Google Cloud project and get the necessary API credentials.
  • Write a Python script to handle secure authentication using OAuth 2.0.
  • Successfully post a "Hello, World!" message to your blog programmatically.

Step 1: Google Cloud API Setup

This is the most critical step. We need to tell Google that we're building an application that needs to access Blogger on our behalf.

  1. Go to the Google Cloud Console: https://console.cloud.google.com/
  2. Create a New Project: If you don't have one already, click the project dropdown at the top and select "New Project". Name it something like "Blogger Auto Poster" and click Create.
  3. Enable the Blogger API: In the search bar at the top, type "Blogger API v3" and select it. Click the "Enable" button.
  4. Create Credentials:
    • On the left menu, go to "APIs & Services" > "Credentials".
    • Click "+ CREATE CREDENTIALS" at the top and select "OAuth client ID".
    • You may be prompted to "Configure Consent Screen". Choose "External" and fill in the required fields (App name, your email). Don't worry about the advanced settings for now. Save and continue.
    • For "Application type", select "Desktop app". This is very important.
    • Give it a name, like "Blogger Poster Script".
    • Click "Create".
  5. Download Your Credentials: A pop-up will appear. Click "DOWNLOAD JSON". Rename this downloaded file to client_secret.json and save it in a new folder on your computer where you will create your Python script.
Security Warning: The client_secret.json file is sensitive. Do not share it publicly or commit it to a public GitHub repository.

Step 2: Setting Up Your Python Environment

We'll use a virtual environment to keep our project's dependencies separate.

  1. Open a terminal or command prompt and navigate to your project folder.
  2. Create a virtual environment:
    python -m venv venv
  3. Activate it:
    • Windows:
      .\venv\Scripts\activate
    • Mac/Linux:
      source venv/bin/activate
  4. Install the required Google libraries:
    pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

Step 3: The Python Script - First Post

Create a new file named poster_part1.py in your project folder and add the following code.

Find Your Blog ID: Go to your Blogger dashboard and select the blog you want to post to. Your Blog ID is the long number in the URL. For example, in blogger.com/blog/posts/1234567890123456789, the ID is the bolded number.
import os import pickle from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from googleapiclient.discovery import build # --- CONFIGURATION --- CLIENT_SECRETS_FILE = "client_secret.json" SCOPES = ['https://www.googleapis.com/auth/blogger'] API_SERVICE_NAME = 'blogger' API_VERSION = 'v3' # PASTE YOUR BLOG ID HERE BLOG_ID = "YOUR_BLOG_ID_HERE" def get_credentials(): """Gets valid user credentials from storage or runs the OAuth2 flow.""" creds = None token_pickle_path = 'token.pickle' if os.path.exists(token_pickle_path): with open(token_pickle_path, 'rb') as token: creds = pickle.load(token) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( CLIENT_SECRETS_FILE, SCOPES) creds = flow.run_local_server(port=0) with open(token_pickle_path, 'wb') as token: pickle.dump(creds, token) return creds def main(): """Main function to authenticate and post to Blogger.""" print("Attempting to get credentials...") credentials = get_credentials() print("Credentials obtained successfully.") service = build(API_SERVICE_NAME, API_VERSION, credentials=credentials) post_title = "My First Automated Post" post_content = "

Hello, World! This is a test post from my new Python script. If you can see this, it means the connection to the Blogger API is working!

" body = {"title": post_title, "content": post_content} try: print(f"Publishing post to Blog ID: {BLOG_ID}...") posts = service.posts() posts.insert(blogId=BLOG_ID, body=body, isDraft=False).execute() print("🎉 Successfully published the post!") except Exception as e: print(f"An error occurred: {e}") if __name__ == '__main__': main()

Step 4: Run the Script!

Make sure you've replaced "YOUR_BLOG_ID_HERE" with your actual Blog ID.

  1. In your terminal, run the script:
    python poster_part1.py
  2. First Time Only: Your web browser will open, asking you to log in to your Google account and grant permission to the app.
  3. After you grant permission, the browser tab will close, and the script will continue.
  4. Check your terminal. You should see the success message!
  5. Check your blog. The new post should be live!

A new file named token.pickle will have appeared in your folder. This securely stores your authorization. The script won't ask you to log in again unless this file is deleted.




Create a Blogger Auto-Poster with Python (.exe) - Part 2: The Brains

Congratulations on completing Part 1! You now have a script that can connect and post to Blogger. In this part, we'll make it intelligent. We will replace the hard-coded test message with unique, high-quality content generated by Google's Gemini AI. We will also create a configuration file to make our script flexible and easy to manage.

What You'll Achieve in Part 2:

  • Set up the Google Gemini API for content generation.
  • Create a configuration file to store your blog details, topics, and backlink.
  • Modify the script to read the configuration, generate a unique article, and inject your backlink.

Step 1: Get Your Google Gemini API Key

We'll use Google's own AI to generate our content. This keeps everything in the Google ecosystem.

  1. Go to Google AI Studio: https://aistudio.google.com/
  2. Sign in with your Google account.
  3. On the left menu, click "Get API key".
  4. Click "Create API key in new project". A key will be generated for you.
  5. Copy this key and save it somewhere safe. We will use it in our configuration file. This key is secret!

Step 2: Install the Gemini Library

In your activated virtual environment, install the library for Google's Generative AI.

pip install google-generativeai

Step 3: Create the Configuration File

This file will hold all our settings, so we don't have to edit the Python code every time. Create a new file named config.ini in your project folder.

[DEFAULT] # Your main business website backlink BacklinkURL = https://www.your-business-website.com # The name of your business or website for the backlink text BacklinkAnchorText = check out our amazing services [Blog1] # The unique ID for your first blog BlogID = 1111111111111111111 # The topic for this blog. Be descriptive! Topic = a 400-word blog post about the benefits of remote work for small businesses # A title for the post. We'll ask the AI to generate a better one. Title = A Post About Remote Work [Blog2] # You can add more blogs like this BlogID = 2222222222222222222 Topic = a 400-word tutorial on how to bake sourdough bread for beginners Title = Sourdough Baking Guide

Fill this file out with your own details. For now, we will just use [Blog1]. We'll handle rotation in Part 3.

Step 4: The Upgraded Python Script

Create a new file named poster_part2.py. We will copy the authentication logic from Part 1 and add the AI and configuration logic.

Important: You'll need to create a new file on your computer named secrets.py and add your Gemini API key to it like this: GEMINI_API_KEY = "YOUR_API_KEY_HERE". This keeps your key out of the main script.
import os import pickle import configparser import google.generativeai as genai from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from googleapiclient.discovery import build try: from secrets import GEMINI_API_KEY except ImportError: print("Error: `secrets.py` file not found or GEMINI_API_KEY not set.") exit() CLIENT_SECRETS_FILE = "client_secret.json" SCOPES = ['https://www.googleapis.com/auth/blogger'] API_SERVICE_NAME = 'blogger' API_VERSION = 'v3' genai.configure(api_key=GEMINI_API_KEY) generation_config = {"temperature": 0.7, "top_p": 1, "top_k": 1, "max_output_tokens": 2048} model = genai.GenerativeModel(model_name="gemini-pro", generation_config=generation_config) def get_credentials(): # This function is identical to Part 1. creds = None token_pickle_path = 'token.pickle' if os.path.exists(token_pickle_path): with open(token_pickle_path, 'rb') as token: creds = pickle.load(token) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES) creds = flow.run_local_server(port=0) with open(token_pickle_path, 'wb') as token: pickle.dump(creds, token) return creds def generate_content(topic): print("Generating content with Gemini AI...") try: prompt = f"""You are an expert blog post writer. Your tone is helpful and informative. Task: Write a high-quality, engaging blog post based on the following topic. Topic: "{topic}" The output must be in this exact format: TITLE: [Your engaging and SEO-friendly title here] CONTENT: [The full blog post content here, in HTML format. Use p, h3, ul, li, and strong tags.]""" response = model.generate_content(prompt) parts = response.text.split("CONTENT:") title = parts[0].replace("TITLE:", "").strip() content = parts[1].strip() print("Content generated successfully.") return title, content except Exception as e: print(f"Error during AI content generation: {e}") return None, None def inject_backlink(content, url, anchor_text): paragraphs = content.split('

') middle_index = len(paragraphs) // 2 if paragraphs[middle_index]: backlink_html = f' {anchor_text}' paragraphs[middle_index] = paragraphs[middle_index] + backlink_html return '

'.join(paragraphs) def main(): config = configparser.ConfigParser() config.read('config.ini') target_blog = 'Blog1' blog_id = config[target_blog]['BlogID'] topic = config[target_blog]['Topic'] backlink_url = config['DEFAULT']['BacklinkURL'] backlink_text = config['DEFAULT']['BacklinkAnchorText'] title, content = generate_content(topic) if not title or not content: print("Could not generate content. Exiting.") return content_with_link = inject_backlink(content, backlink_url, backlink_text) credentials = get_credentials() service = build(API_SERVICE_NAME, API_VERSION, credentials=credentials) body = {"title": title, "content": content_with_link} try: print(f"Publishing post '{title}' to Blog ID: {blog_id}...") posts = service.posts() posts.insert(blogId=blog_id, body=body, isDraft=False).execute() print("🎉 Successfully published the AI-generated post!") except Exception as e: print(f"An error occurred during posting: {e}") if __name__ == '__main__': main()

Step 5: Run the Upgraded Script

Make sure your config.ini and secrets.py files are correctly filled out.

python poster_part2.py

The script will now generate a unique article based on your topic, add your backlink, and post it to your blog. Check the result!




Create a Blogger Auto-Poster with Python (.exe) - Part 3: The Final Product

You've made it to the final part! We have a powerful script, but running it from the command line every day isn't practical. In this part, we will package our Python script into a standalone Windows Executable (.exe) file. This allows you to run it on any Windows computer without needing to install Python. We will also add the logic to rotate through your blogs and learn how to schedule it to run automatically every day.

What You'll Achieve in Part 3:

  • Add rotation logic to post to a different blog each day.
  • Install PyInstaller to package Python applications.
  • Bundle your script and all its files into a single .exe file.
  • Learn how to use Windows Task Scheduler to automate the entire process.

Step 1: The Final Script with Rotation

Create a new file, auto_poster_final.py. This version will include logic to read a small text file, see which blog it posted to last, and post to the next one in the list from your config.ini.

# auto_poster_final.py # This script combines everything and adds rotation logic. # [ All the imports and functions from poster_part2.py go here ] # get_credentials(), generate_content(), inject_backlink() etc. # For brevity, only the new main() function is shown below. # Copy all the code from poster_part2.py and just replace the main() function with this one. def main(): """Main function with rotation logic.""" config = configparser.ConfigParser() config.read('config.ini') # --- ROTATION LOGIC --- blog_sections = [s for s in config.sections() if s.startswith('Blog')] if not blog_sections: print("No blog sections (e.g., [Blog1], [Blog2]) found in config.ini. Exiting.") return last_index_file = 'last_blog.txt' last_index = -1 if os.path.exists(last_index_file): with open(last_index_file, 'r') as f: try: last_index = int(f.read()) except (ValueError, TypeError): last_index = -1 current_index = (last_index + 1) % len(blog_sections) target_blog = blog_sections[current_index] with open(last_index_file, 'w') as f: f.write(str(current_index)) print(f"--- Today's Target Blog: {target_blog} ---") # --- END ROTATION LOGIC --- blog_id = config[target_blog]['BlogID'] topic = config[target_blog]['Topic'] backlink_url = config['DEFAULT']['BacklinkURL'] backlink_text = config['DEFAULT']['BacklinkAnchorText'] # 1. Generate Content title, content = generate_content(topic) if not title or not content: print("Could not generate content. Exiting.") return # 2. Inject Backlink content_with_link = inject_backlink(content, backlink_url, backlink_text) # 3. Authenticate and Post print("Getting Google credentials...") credentials = get_credentials() service = build(API_SERVICE_NAME, API_VERSION, credentials=credentials) body = {"title": title, "content": content_with_link} try: print(f"Publishing post '{title}' to Blog ID: {blog_id}...") posts = service.posts() posts.insert(blogId=blog_id, body=body, isDraft=False).execute() print(f"🎉 Successfully published to {target_blog}!") except Exception as e: print(f"An error occurred during posting: {e}") # Don't forget the other functions (get_credentials, etc.) and this line at the end! if __name__ == '__main__': main()

Step 2: Install PyInstaller

PyInstaller is the tool that performs the magic of converting our .py script into an .exe. In your activated virtual environment, run:

pip install pyinstaller

Step 3: Create the Executable (.exe)

Now, we'll use PyInstaller. We need to tell it to include our important data files.

Run this command from your terminal, in your project directory:

pyinstaller --onefile --noconsole --add-data "config.ini;." --add-data "client_secret.json;." --add-data "token.pickle;." --hidden-import="secrets" auto_poster_final.py

Command Breakdown:

  • --onefile: Bundles everything into a single .exe file.
  • --noconsole: Prevents the black command window from popping up. It will run silently in the background (perfect for automation).
  • --add-data "file;.": This is crucial. It tells PyInstaller to include these necessary files in the package.
  • --hidden-import="secrets": Tells PyInstaller to make sure it includes our secrets.py file.

After it finishes, you will find a dist folder. Inside, you'll find your auto_poster_final.exe file. This is your program! You can now move this `.exe` file to any Windows computer and it will run.

Step 4: Schedule with Windows Task Scheduler

This is the final step to "set it and forget it".

  1. Press the Windows Key and type "Task Scheduler", then open it.
  2. In the right-hand "Actions" pane, click "Create Basic Task...".
  3. Name: Give it a name like "Daily Blogger Post". Click Next.
  4. Trigger: Choose "Daily" and click Next. Set a time you want it to run (e.g., 9:00 AM every day).
  5. Action: Choose "Start a program". Click Next.
  6. Start a Program: Click "Browse..." and find your auto_poster_final.exe file in the dist folder.
  7. Click Next, then review the details and click "Finish".
Congratulations! You have successfully built and automated a custom content generation and publishing tool. Your computer will now automatically run your program every day, posting new content to your blogs in rotation.

No comments:

Post a Comment