How to automate tasks using Python and ChatGPT

Ever feel like you’re trapped on repeat—answering the same customer questions, skimming through endless articles, or trying to squeeze fifty social media posts out of one small idea? It’s exhausting.

Now imagine having a personal digital autopilot that takes over those time-sucking chores. Thanks to Python—one of the easiest and most flexible programming languages—and the brains of OpenAI’s ChatGPT, that’s no longer a “maybe someday” dream.

How to automate tasks using Python and ChatGPT

How to automate tasks using Python and ChatGPT

You can automate a surprising variety of tasks, freeing your headspace for creativity, strategy, and the kind of problem-solving that actually excites you.

This guide breaks it all down without the tech overload. No cryptic jargon, no drawn-out theory—just a clear, step-by-step path to building your first automation scripts and putting them to work.

Why Python and ChatGPT are a Match Made in Heaven 

So, why this specific duo? Think of it like a skilled craftsman and their ultimate, all-knowing tool.

  • Python is the Craftsman: It's the "doer." Python is fantastic at interacting with your digital world. It can read files, scrape websites, send emails, and connect to thousands of applications through Application Programming Interfaces (APIs). Its syntax is clean and readable, making it relatively easy for even non-programmers to pick up.
  • ChatGPT is the Brain: It's the "thinker." ChatGPT, accessed via the OpenAI API, excels at understanding and generating human-like text. It can summarize, translate, rephrase, classify, brainstorm, and even write code. It handles the cognitive load—the part of the task that requires reasoning or language understanding.

When you put them together, you get a powerful workflow: Python handles the logistics (getting the data, sending the output), and ChatGPT provides the intelligence to process it.

This combination allows you to automate tasks that were previously impossible without human intervention, like:

  • Automated Content Creation: Generate blog post drafts, social media captions, or product descriptions.
  • Intelligent Email Sorting: Automatically categorize incoming emails and draft replies to common questions.
  • Data Summarization: Condense long reports, articles, or customer reviews into concise summaries.
  • Sentiment Analysis: Instantly gauge the tone of customer feedback or social media mentions.

The possibilities are limited only by your imagination.

Getting Your Toolkit Ready: The Setup

Before we start building, we need to gather our tools. Don't worry, it's a straightforward process.

1. Install Python

If you don't already have Python on your machine, head over to the official Python website and download the latest version. During installation on Windows, make sure to check the box that says "Add Python to PATH." This little step will save you a lot of headaches later. For Mac and Linux users, Python is often pre-installed. You can check by opening your terminal and typing python3 --version.

2. Get Your OpenAI API Key

The API key is your secret password to communicate with ChatGPT.

  1. Go to the OpenAI Platform and create an account (or log in).
  2. Navigate to the "API keys" section in the dashboard menu.
  3. Click on “Create new secret key.” Give it a memorable name (e.g., "Python_Automation_Key") and copy it immediately.
  4. Important: Treat this key like a password. Don't share it publicly or commit it to a public code repository. The best practice is to store it as an environment variable, but for now, just keep it in a safe, private file.

A quick note on pricing: Using the OpenAI API isn't free, but it's incredibly cheap for most personal projects. You pay per amount of text processed. When you first sign up, you often get some free credits to experiment with, which is more than enough to get started.

3. Install the Necessary Python Library

With Python installed, you just need one more thing: the official OpenAI Python library. Open your terminal or command prompt and run this simple command:

Copy Code

Bash

pip install openai

This command tells pip, Python's package manager, to download and install the library that makes talking to the OpenAI API a breeze.

Your First Automation: The Article Summarizer

Let's build something practical. Imagine you have to read a dozen long news articles every morning. It’s time-consuming. Let's build a Python script that takes a URL, fetches the article's content, and asks ChatGPT to summarize it for you.

Step 1: The Basic Python Structure

First, let's create a Python file, let's call it summarizer.py. We'll start by setting up our connection to the OpenAI API.

Copy Code

Python

# Import the openai library

import openai



# Set your API key

# Best practice is to use environment variables, but for this example, we'll place it here.

# DO NOT share this key or commit it to public repositories.

openai.api_key = 'YOUR_API_KEY_HERE' 



def summarize_text(text_to_summarize):

    """

    This function takes a block of text and returns a summary using the ChatGPT API.

    """

    print("Sending text to ChatGPT for summarization...")

    

    try:

        response = openai.chat.completions.create(

            model="gpt-3.5-turbo",  # You can use "gpt-4" for higher quality but it's more expensive

            messages=[

                {"role": "system", "content": "You are a helpful assistant that summarizes text concisely."},

                {"role": "user", "content": f"Please summarize the following text in three key bullet points:\n\n{text_to_summarize}"}

            ]

        )

        # Extracting the content from the response

        summary = response.choices[0].message.content

        return summary

    except Exception as e:

        return f"An error occurred: {e}"

# Example Usage (we'll replace this with real article text later)

sample_text = """

Python is a high-level, interpreted, general-purpose programming language. 

Its design philosophy emphasizes code readability with the use of significant indentation.

Python is dynamically-typed and garbage-collected. It supports multiple programming paradigms,

including structured (particularly, procedural), object-oriented and functional programming.

It is often described as a "batteries included" language due to its comprehensive standard library.

"""

Copy Code

summary_result = summarize_text(sample_text)

print("\n--- Summary ---")

print(summary_result)

Let's break this down:

  • We import the openai library.
  • We set our api_key. Remember to replace 'YOUR_API_KEY_HERE' with your actual key.
  • The summarize_text function is where the magic happens.
  • openai.chat.completions.create() is the core function call.
  • model: We specify which ChatGPT model to use. gpt-3.5-turbo is fast and cost-effective.
  • messages: This is how we structure our conversation with the AI.
    • The system role sets the context. We're telling the AI its job is to be a summarizer.
    • The user role is our actual request, our prompt. Here, we instruct it to summarize the provided text.
  • We then extract the AI's response and print it.

Step 2: Fetching an Article from the Web

Now, how do we get the text from a live article? We'll need two more libraries: requests to fetch the webpage and BeautifulSoup4 to parse the HTML and extract just the article text.

Install them via your terminal:

Copy Code

Bash

pip install requests beautifulsoup4

To really get the hang of pulling data from websites, a structured learning path can make a huge difference. The concepts of HTML tags, selectors, and handling different website structures are foundational. If you're serious about this, checking out Uncodemy  Python for Web Scraping course is a fantastic next step. It covers these techniques in-depth, giving you the robust skills to scrape data from almost any site you encounter.

Now, let's add the web scraping logic to our script.

Copy Code

Python

import openai

import requests

from bs4 import BeautifulSoup



# --- Your API key and summarize_text function from above go here ---

openai.api_key = 'YOUR_API_KEY_HERE' 



def summarize_text(text_to_summarize):

    # (Same function as before)

    print("Sending text to ChatGPT for summarization...")

    try:

        response = openai.chat.completions.create(

            model="gpt-3.5-turbo",

            messages=[

                {"role": "system", "content": "You are a helpful assistant that summarizes text concisely."},

                {"role": "user", "content": f"Please summarize the following text in three key bullet points:\n\n{text_to_summarize}"}

            ]

        )

        summary = response.choices[0].message.content

        return summary

    except Exception as e:

        return f"An error occurred: {e}"



def get_article_text(url):

    """

    Fetches a URL and extracts the main article text using BeautifulSoup.

    """

    print(f"Fetching article from {url}...")

    try:

        response = requests.get(url)

        # Using BeautifulSoup to parse the HTML content

        soup = BeautifulSoup(response.content, 'html.parser')

        

        # This is a simple approach: find all paragraph tags (<p>)

        # More complex sites might require more specific selectors

        paragraphs = soup.find_all('p')

        

        # Join all the paragraph texts together

        article_text = ' '.join([p.get_text() for p in paragraphs])

        return article_text

    except Exception as e:

        return f"Failed to fetch or parse article: {e}"



# --- Main part of the script ---

article_url = 'https://www.example.com/some-interesting-article' # Replace with a real URL



article_content = get_article_text(article_url)



if "Failed" in article_content or "error" in article_content:

    print(article_content)

else:

    # We only summarize if the text isn't too short (to avoid summarizing error messages)

    if len(article_content) > 300:

        summary_result = summarize_text(article_content)

        print("\n--- Summary ---")

        print(summary_result)

    else:

        print("Article content was too short or could not be extracted properly.")

Now, when you run this script (after replacing the example.com URL with a real one), Python will visit the page, grab the text, pass it to ChatGPT, and print out a neat summary. You've just automated your morning reading!

Advanced Tips and Best Practices

Once you've got the basics down, keep these tips in mind to level up your automation game.

1. Master Prompt Engineering

The quality of your output depends almost entirely on the quality of your input (your prompt). Be specific.

  • Bad Prompt: "Write about my product."
  • Good Prompt: "Write three social media posts for Instagram about our new eco-friendly water bottle. The tone should be enthusiastic and youthful. Mention that it's made from recycled materials and keeps water cold for 24 hours. Include a call to action to 'Shop the link in bio!' and suggest 3-5 relevant hashtags."

Give the AI a role, a format, a tone, and clear constraints.

2. Handle Errors Gracefully

APIs can fail. Websites can be down. Your script should be resilient. Use try...except blocks in Python to catch potential errors (like network issues or API failures) so your program doesn't crash.

3. Be Mindful of Costs

Keep an eye on your API usage in the OpenAI dashboard. For text-heavy tasks, consider ways to shorten your input. For example, instead of sending a whole 5000-word article for sentiment analysis, maybe you only need to send the first and last paragraphs.

4. Stay Ethical

With great power comes great responsibility. Use these tools ethically. Don't build spam bots, generate misleading content, or automate tasks that violate terms of service. Always aim to build tools that help, not harm.

Your Automation Journey Starts Now

We’ve only just begun to tap into the possibilities. That same summarizer script can be tweaked to do almost anything—rephrase text, craft email replies, spark fresh ideas, or even sort and categorize customer feedback. You can hook it up to a file on your computer, a Google Sheet, or your go-to project management app.

When you combine Python’s organizational muscle with ChatGPT’s brainpower, you get something close to a digital superpower—a set of tools tailored exactly to you. So, which repetitive task will you automate first? Start small, play around, and before long you’ll have your own personal autopilot running in the background. The time you save is yours to claim back.

Placed Students

Our Clients

Partners

...

Uncodemy Learning Platform

Uncodemy Free Premium Features

Popular Courses