Imagine waking up each day with a fresh dose of inspiration delivered straight to your phone. In this tutorial, we’re going to create an automated motivational message sender using Python and WhatsApp. By the end of this post, you’ll have a functional application that leverages the power of OpenAI’s GPT-3.5 Turbo to generate motivational messages that can be sent via WhatsApp using the pywhatkit library.
Use Case
This project is not only a fun exercise in Python programming but also a practical application of integrating AI with messaging platforms. Whether you want to inspire your friends, motivate your team, or simply enjoy sending uplifting messages, this project will help you automate that process. Imagine a small script running on your server every day at 9 AM, sending out a motivational quote to your WhatsApp contacts. Let’s dive in!
Initializing OpenAI Client
This snippet demonstrates how to initialize the OpenAI client using an API key stored in an environment variable, which is a best practice for managing sensitive information.
📚 Recommended Python Learning Resources
Level up your Python skills with these hand-picked resources:
Academic Calculators Bundle: GPA, Scientific, Fraction & More
Academic Calculators Bundle: GPA, Scientific, Fraction & More
ACT Test (American College Testing) Prep Flashcards Bundle: Vocabulary, Math, Grammar, and Science
ACT Test (American College Testing) Prep Flashcards Bundle: Vocabulary, Math, Grammar, and Science
Leonardo.Ai API Mastery: Python Automation Guide (PDF + Code + HTML
Leonardo.Ai API Mastery: Python Automation Guide (PDF + Code + HTML
100 Python Projects eBook: Learn Coding (PDF Download)
100 Python Projects eBook: Learn Coding (PDF Download)
HSPT Vocabulary Flashcards: 1300+ Printable Study Cards + ANKI (PDF)
HSPT Vocabulary Flashcards: 1300+ Printable Study Cards + ANKI (PDF)
import os
from openai import OpenAI # Updated OpenAI SDK (v1.0+)
# Initialize OpenAI client
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY")) # Make sure OPENAI_API_KEY is set
Prerequisites and Setup
Before getting started, ensure you have the following:
Generating a Motivational Message
This function illustrates how to interact with the OpenAI API to generate a motivational message based on a predefined prompt, showcasing error handling in API calls.
def get_motivational_message(day_of_week):
"""
Uses OpenAI GPT-3.5 Turbo to generate a motivational message.
"""
prompt = f"Write a short commentary about Sunil Gavaskar."
try:
response = client.chat.completions.create(
model="gpt-3.5-turbo", # Using GPT-3.5 Turbo for cost efficiency
messages=[
{"role": "system", "content": "You are an expert in Sports (Cricket)."},
{"role": "user", "content": prompt}
]
)
return response.choices[0].message.content.strip()
except Exception as e:
return f"Error generating message: {str(e)}"
- Basic Python knowledge: Familiarity with Python syntax and libraries.
- Python environment: Make sure you have Python 3.6 or higher installed.
- OpenAI API Key: Sign up for OpenAI and get your API key, which is necessary for accessing the GPT-3.5 Turbo model.
- WhatsApp Web setup: Ensure you have WhatsApp Web linked to your phone.
- Required libraries: Install openai and pywhatkit using pip. You can do this by running
pip install openai pywhatkitin your terminal.
Core Concepts Explanation
Before we jump into the implementation, let’s break down some core components of our project.
Getting Current Day of the Week
This snippet shows how to obtain the current date and format it to retrieve the day of the week, which is useful for time-sensitive applications.
import datetime
# Get current day and time
now = datetime.datetime.now()
day_of_week = now.strftime("%A") # e.g., "Monday"
1. OpenAI API Integration
The OpenAI API allows us to harness the power of AI for generating text-based content. In our case, we will be using the GPT-3.5 Turbo model, which is efficient and cost-effective for generating short motivational messages. By initializing the OpenAI client with our API key, we can easily make requests to generate content based on predefined prompts.
2. WhatsApp Messaging with pywhatkit
pywhatkit is a Python library that simplifies sending messages through WhatsApp Web. By specifying the recipient’s phone number and the message, we can automate the process of sending motivational quotes directly to WhatsApp. One important aspect of using this library is the scheduling functionality, which allows us to send messages at a specific time.
3. Working with Date and Time
To create time-sensitive messages, we’ll use Python’s datetime module. This module allows us to retrieve the current day of the week and format it appropriately. In our case, it helps us personalize the motivational message based on the day, adding relevance and appeal.
Step-by-Step Implementation Walkthrough
Now that we’ve covered the essential concepts, let’s dive into the step-by-step implementation of our automated motivational message sender.
Combining Messages
This code combines a hardcoded introduction with a dynamically generated motivational message, demonstrating string formatting and message composition.
# Generate the message
motivational_message = get_motivational_message(day_of_week)
# Combine with a hardcoded prefix
final_message = (
"Hi! This is an automated message sent via Python using OpenAI GPT-3.5 Turbo.\n\n"
f"Your motivational message for {day_of_week}:\n\n{motivational_message}"
)
Step 1: Initialize the OpenAI Client
The first step in our implementation is to set up the OpenAI client. This involves importing the necessary libraries and initializing the client with the API key stored as an environment variable. This is a recommended best practice to keep sensitive information like API keys secure.
Step 2: Generate a Motivational Message
Next, we’ll define a function that generates a motivational message. This function will communicate with the OpenAI API, sending it a prompt to create a short commentary about a specific topic—in our case, Sunil Gavaskar. Handling potential errors during the API call is crucial, as it ensures our application runs smoothly even if the API encounters issues.
Step 3: Get the Current Day of the Week
Using the datetime module, we retrieve the current date and format it to get the day of the week. This information will be used to personalize the message we send, making it relevant to the day.
Step 4: Combine Messages
After generating the motivational message, we’ll combine it with a hardcoded introduction. This string composition is vital for creating a friendly and engaging message that sets a positive tone for the recipient.
Step 5: Schedule and Send the WhatsApp Message
Finally, we’ll use the pywhatkit library to send our message via WhatsApp. By scheduling the message to be sent two minutes in advance of the current time, we ensure that the recipient receives it at the desired time without any delays.
Advanced Features or Optimizations
Once you have the basic implementation working, consider adding more advanced features:
Scheduling a WhatsApp Message
This snippet demonstrates how to use the `pywhatkit` library to schedule a WhatsApp message, highlighting the integration of Python with external messaging services.
import pywhatkit as kit
# Schedule WhatsApp message (2 minutes ahead)
send_time_min = now.minute + 2
try:
kit.sendwhatmsg(
phone_no="+7330651452", # Replace with recipient's number
message=final_message,
time_hour=now.hour,
time_min=send_time_min
)
print(f"✅ Message scheduled for {day_of_week} at {now.hour}:{send_time_min:02d}")
except Exception as e:
print(f"❌ Failed to send: {str(e)}")
- Dynamic Recipient List: Modify the script to accept a list of phone numbers to send messages to multiple contacts at once.
- Customizable Prompts: Allow users to input their own prompts for generating messages, offering more variety and personalization.
- Message Logging: Implement logging to keep track of sent messages, which can help in debugging and monitoring message delivery.
- Improved Error Handling: Enhance error handling to manage network issues or incorrect input gracefully.
Practical Applications
This project can serve various practical applications beyond just sending motivational messages:
- Daily reminders for tasks or events.
- Inspirational quotes for teams in a work environment.
- Health and wellness tips sent to clients or colleagues.
- Event notifications, such as meeting reminders or deadlines.
Common Pitfalls and Solutions
As with any project, you may encounter some common pitfalls:
- API Key Issues: Ensure that the API key is correctly set in your environment variables. If you receive authentication errors, double-check your key and its permissions.
- WhatsApp Message Not Sending: If messages fail to send, verify that your WhatsApp Web is connected and that your computer’s browser is active during the scheduled time.
- Rate Limits: Be mindful of OpenAI’s API rate limits. Sending too many requests in a short time can result in temporary bans.
Conclusion and Next Steps
Congratulations! You’ve successfully built an automated motivational message sender in Python with WhatsApp integration. This project not only demonstrates your ability to integrate AI with messaging platforms but also serves as a foundation for more complex applications.
As next steps, consider experimenting with the advanced features mentioned above or even extending the application to support other messaging platforms, such as Telegram or Slack. The possibilities are endless!
Happy coding, and may your messages always inspire!
About This Tutorial: This code tutorial is designed to help you learn Python programming through practical examples. Always test code in a development environment first and adapt it to your specific needs.
Want to accelerate your Python learning? Check out our premium Python resources including Flashcards, Cheat Sheets, Interivew preparation guides, Certification guides, and a range of tutorials on various technical areas.


