杰瑞科技汇

Python googlevoice

Of course! The googlevoice library for Python is a powerful, unofficial tool that allows you to programmatically interact with your Google Voice account. It's great for automating tasks like sending SMS, checking for new voicemails, and managing your inbox.

Python googlevoice-图1
(图片来源网络,侵删)

Here’s a comprehensive guide covering everything you need to know.


Important: The Modern Way (Using the API)

Before we dive into the googlevoice library, it's crucial to know that Google has deprecated the unofficial methods this library relies on. While it still works for many users, it is not guaranteed to work in the future.

For new projects, the recommended and future-proof method is to use Google's official Voice API. However, this requires a more complex setup with Google Cloud, OAuth 2.0, and billing. It's overkill for simple scripts.

Choose your path:

Python googlevoice-图2
(图片来源网络,侵删)
  • For quick, simple, personal scripts: Use googlevoice (as described below). It's easier but less stable.
  • For serious, long-term, or commercial applications: Use the Google Voice API. It's more complex but officially supported.

Installation

First, you need to install the library. It's best to do this in a virtual environment.

# Create a virtual environment (optional but recommended)
python -m venv googlevoice_env
# Activate the virtual environment
# On macOS/Linux:
source googlevoice_env/bin/activate
# On Windows:
googlevoice_env\Scripts\activate
# Install the library
pip install googlevoice

Authentication (The Tricky Part)

The googlevoice library doesn't use your Google password directly. Instead, it uses a cookie from your browser's session. This means you must first log in to Google Voice in your browser.

Step-by-Step Guide:

  1. Log in to Google Voice: Open your web browser (Chrome or Firefox is recommended) and go to https://voice.google.com. Log in with your account.

  2. Export Cookies: You need to get the cookies from your browser session and save them to a file.

    • Easiest Method (Recommended): Use a browser extension.

      • For Chrome: Install an extension like "Get cookies.txt".
      • For Firefox: Install an extension like "cookies.txt".
      • After installing, go to voice.google.com, click the extension's icon, and choose to export the cookies. Save the file as cookies.txt in the same directory where you will run your Python script.
    • Manual Method (Advanced): You can manually find and copy the cookies from your browser's developer tools, but this is much more tedious.

  3. Structure of cookies.txt: The file should look something like this. The googlevoice library needs the NID and HSID cookies to be present.

    # Netscape HTTP Cookie File
    # https://curl.se/docs/http-cookies.html
    # This file was generated by export-cookie.txt
    # https://chrome.google.com/webstore/detail/get-cookiestxt/bgaddhkoddajcdgocldbbfleckgcbcid
    .google.com TRUE    /   TRUE    0   NID 204=..._...
    .google.com TRUE    /   TRUE    0   HSID    ..._...
    # ... other cookies

Basic Usage

Here’s how to use the library in a Python script. Make sure your cookies.txt file is in the same directory.

import time
from googlevoice import Voice
# Initialize the Voice object
# The 'login' method will automatically find and use the 'cookies.txt' file
# in the current directory.
voice = Voice()
# If your cookies.txt is in a different location, specify the path:
# voice = Voice()
# voice.login(cookiefile='/path/to/your/cookies.txt')
print("Successfully logged in.")
# --- Example 1: Sending an SMS ---
try:
    print("Sending an SMS...")
    # The send() method takes a phone number and a text message
    voice.send('15551234567', 'Hello from my Python script!')
    print("SMS sent successfully!")
except Exception as e:
    print(f"Failed to send SMS: {e}")
# --- Example 2: Checking for new voicemails ---
print("\nChecking for voicemails...")
# The `inbox` is a list of all messages
all_messages = voice.inbox()
# Filter for voicemails
voicemails = [msg for msg in all_messages if msg.type == 'voicemail']
if voicemails:
    print(f"You have {len(voicemails)} new voicemail(s).")
    for msg in voicemails:
        print(f"- From: {msg.phoneNumber}, at: {msg.date}, duration: {msg.duration} seconds")
else:
    print("No new voicemails found.")
# --- Example 3: Listing recent SMS ---
print("\nListing recent SMS messages...")
sms_list = [msg for msg in all_messages if msg.type == 'sms']
if sms_list:
    print(f"Found {len(sms_list)} SMS messages.")
    for msg in sms_list[-5:]: # Show the last 5
        print(f"- From: {msg.phoneNumber}, at: {msg.date}, snippet: '{msg.snippet}'")
else:
    print("No SMS messages found.")

Core Objects and Methods

The library revolves around a few key objects:

  • voice object: The main entry point. You use it to log in and perform high-level actions like sending messages.
  • Message object: Represents a single communication (SMS, call, or voicemail). Each message object has useful attributes:
    • msg.id: The unique ID for the message.
    • msg.phoneNumber: The phone number of the contact.
    • msg.date: The date and time of the message.
    • msg.type: The type of message ('sms', 'voicemail', 'missed', 'placed', 'received').
    • msg.snippet: A short text preview of the message.
    • msg.duration: (For voicemails/calls) The duration in seconds.

Common voice object methods:

  • voice.login(cookiefile='cookies.txt'): Authenticates using the cookie file.
  • voice.send(phone_number, text): Sends an SMS.
  • voice.search(query): Searches your messages. Returns a list of Message objects.
  • voice.inbox(): Gets all messages in your inbox.
  • voice.all(): Gets all messages (inbox, spam, etc.).
  • voice.trash(): Gets messages in the trash.

Common Message object methods:

  • msg.star(): Stars the message.
  • msg.unstar(): Unstars the message.
  • msg.delete(): Moves the message to the trash.
  • msg.forward(phone_number): Forwards the message to another number (works best for voicemails).

Complete Example: A Simple Voicemail Notifier

Let's create a script that checks for new voicemails every 5 minutes and prints a summary.

import time
from googlevoice import Voice
def check_voicemails(voice):
    """Checks for new voicemails and prints them."""
    print("\n--- Checking for new voicemails... ---")
    all_messages = voice.inbox()
    voicemails = [msg for msg in all_messages if msg.type == 'voicemail']
    if voicemails:
        print(f"You have {len(voicemails)} voicemail(s).")
        for msg in voicemails:
            print(f"  From: {msg.phoneNumber} ({msg.date}) - Duration: {msg.duration}s")
            # You could add logic here to play the audio file
            # audio_url = msg.mp3() # This gets the URL to the MP3 file
            # print(f"  Audio URL: {audio_url}")
    else:
        print("No new voicemails found.")
def main():
    """Main function to run the notifier."""
    try:
        voice = Voice()
        voice.login()
        print("Logged in successfully. Starting notifier...")
        while True:
            check_voicemails(voice)
            print("Waiting for 5 minutes before next check...")
            time.sleep(300) # Wait for 5 minutes (300 seconds)
    except Exception as e:
        print(f"An error occurred: {e}")
        print("Please make sure you are logged in to voice.google.com in your browser")
        print("and that 'cookies.txt' is in the correct location.")
if __name__ == "__main__":
    main()

Troubleshooting & Common Issues

  • googlevoice.util.LoginError: Unable to login.

    • Cause: The most common error. It means the library couldn't authenticate.
    • Solution:
      1. Make sure you are logged into voice.google.com in your browser.
      2. Verify that cookies.txt exists and is in the same directory as your script.
      3. Double-check that your cookies.txt file contains the NID and HSID cookies. You can regenerate the file by logging out and back in on Google Voice.
      4. Google may have changed its login process, which could break the library.
  • googlevoice.util.LoginError: Verification required.

    • Cause: Google is requiring a 2-Step Verification (2SV) code.
    • Solution: This is a major limitation of the cookie-based method. You cannot programmatically solve 2SV. You must disable 2FA for your Google account, or use the official Google Voice API which supports OAuth 2.0.
  • requests.exceptions.ConnectionError

    • Cause: A network issue or Google Voice might be temporarily down.
    • Solution: Check your internet connection and try again later.
  • The script suddenly stopped working.

    • Cause: Google's cookies have expired. This is normal and happens periodically (e.g., every few weeks or after a password change).
    • Solution: Simply log in to Google Voice in your browser again to refresh the cookies. Your script should then work without any code changes.
分享:
扫描分享到社交APP
上一篇
下一篇