Categories We Write About

Build a quote-of-the-day SMS bot

Creating a simple quote-of-the-day SMS bot involves several steps. Here’s a breakdown of how to build one:

1. Choose the Technology Stack

  • Backend: Python (with Flask/Django), Node.js, or any other backend framework.

  • SMS API: Twilio, Nexmo, or other SMS service providers.

  • Database: SQLite, MySQL, or any cloud database to store quotes.

  • Scheduler: Cron jobs, Celery, or any task scheduler for sending messages at specific times.

2. Set Up Your Environment

  • Install required packages and libraries:

    • Python: Flask, Twilio

    • Node.js: express, twilio

  • Set up a virtual environment (if using Python):

    bash
    python3 -m venv venv source venv/bin/activate # On Linux/Mac venvScriptsactivate # On Windows

3. Create a Database of Quotes

  • Store quotes in a database. You can manually add them or scrape them from the web.

  • For a simple setup, use an SQLite database with a table like this:

    sql
    CREATE TABLE quotes ( id INTEGER PRIMARY KEY AUTOINCREMENT, text TEXT NOT NULL, author TEXT );
  • Example Quotes:

    idtextauthor
    1“The best way to predict the future is to create it.”Abraham Lincoln
    2“Success is not the key to happiness. Happiness is the key to success.”Albert Schweitzer

4. Set Up Twilio (or another SMS API)

  • Create an account with Twilio and get your API keys.

  • Install the Twilio SDK:

    bash
    pip install twilio
  • Use the Twilio API to send messages:

    python
    from twilio.rest import Client def send_sms(to, message): account_sid = 'your_account_sid' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) message = client.messages.create( body=message, from_='+1YourTwilioNumber', to=to ) return message.sid

5. Create a Flask API for Sending the Quote

Here’s an example of a Flask app that sends a random quote to a user daily.

python
from flask import Flask, jsonify import random import sqlite3 from datetime import datetime from twilio.rest import Client app = Flask(__name__) # Function to get a random quote def get_random_quote(): conn = sqlite3.connect('quotes.db') cursor = conn.cursor() cursor.execute('SELECT text, author FROM quotes ORDER BY RANDOM() LIMIT 1') quote = cursor.fetchone() conn.close() return quote # Function to send SMS using Twilio def send_sms(to, message): account_sid = 'your_account_sid' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) client.messages.create( body=message, from_='+1YourTwilioNumber', to=to ) # API to send daily quote @app.route('/send_quote/<user_number>', methods=['GET']) def send_daily_quote(user_number): quote, author = get_random_quote() message = f"Quote of the Day: '{quote}' - {author}" send_sms(user_number, message) return jsonify({'status': 'success', 'message': 'Quote sent successfully.'}) if __name__ == "__main__": app.run(debug=True)

6. Set Up a Scheduler for Daily SMS

You need to send the quote every day at a set time. For this, you can use a scheduler such as Cron or Celery.

Using Cron:

  • Open your crontab configuration:

    bash
    crontab -e
  • Add an entry to run the Flask app every day at a certain time:

    swift
    0 9 * * * /usr/bin/python3 /path/to/your/app.py

Using Celery:

  • Install Celery:

    bash
    pip install celery
  • Set up a periodic task in Celery to send a daily quote to the user.

7. User Interaction (Opt-In for Quotes)

You’ll need to handle user opt-ins:

  • Use an SMS API to receive replies (like “Start” to begin receiving quotes).

  • Store user phone numbers and preferences in the database.

Example code to listen for user opt-in:

python
from twilio.twiml.messaging_response import MessagingResponse @app.route('/sms', methods=['POST']) def sms_reply(): msg = request.form.get('Body').strip().lower() sender_number = request.form.get('From') resp = MessagingResponse() if msg == 'start': # Add number to database conn = sqlite3.connect('users.db') cursor = conn.cursor() cursor.execute('INSERT INTO users (phone_number) VALUES (?)', (sender_number,)) conn.commit() conn.close() resp.message("You will now receive daily quotes!") elif msg == 'stop': # Remove number from database conn = sqlite3.connect('users.db') cursor = conn.cursor() cursor.execute('DELETE FROM users WHERE phone_number = ?', (sender_number,)) conn.commit() conn.close() resp.message("You have unsubscribed from daily quotes.") else: resp.message("Please reply with 'Start' to receive daily quotes.") return str(resp)

8. Testing

  • Test your SMS bot by interacting with it through SMS and checking that it sends a quote correctly at the specified time.

  • Ensure that users can opt-in and opt-out of receiving quotes.

9. Deploy the Bot

  • Host the Flask app on a platform like Heroku, AWS, or DigitalOcean.

  • Set up your production database and environment.


That’s it! You now have a basic quote-of-the-day SMS bot ready to send motivational quotes to users every day.

Share This Page:

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories We Write About