Skip to main content

Prerequisites

Before you begin, make sure you have:
1

Python 3.10+

The Mention Python Client requires Python 3.10 or higher. Check your version:
python --version
2

Mention API Credentials

You’ll need a Mention account and API credentials:
  • Access Token - OAuth2 token for authentication
  • Account ID - Your Mention account identifier
Get your credentials from the Mention Dashboard.

Installation

Install the Mention Python Client using pip:
pip install mention
For detailed installation instructions, see the Installation Guide.

Basic Usage

Initialize the Client

Create a client instance with your access token:
from mention import MentionClient

client = MentionClient(access_token="your-access-token")
Keep your access token secure! Never commit it to version control. Use environment variables instead (see Environment Setup).

Fetch Alerts

Alerts define what you want to monitor. Fetch all alerts for your account:
# Get all alerts
alerts_response = client.get_alerts(account_id="your-account-id")

# Access the alerts list
for alert in alerts_response.alerts:
    print(f"Alert: {alert.name}")
    print(f"ID: {alert.id}")
    print(f"Keywords: {alert.query.included_keywords}")

Get Mentions

Fetch mentions for a specific alert:
# Fetch recent mentions
mentions = client.get_mentions(
    account_id="your-account-id",
    alert_id="your-alert-id",
    limit=20
)

# Process mentions
for mention in mentions.mentions:
    print(f"Title: {mention.title}")
    print(f"Source: {mention.source_name}")
    print(f"Tone: {mention.tone}")
    print(f"URL: {mention.original_url}")
    print("---")

Filter Mentions

You can filter mentions by various criteria:
from datetime import datetime, timedelta

# Get mentions from the last 7 days
week_ago = datetime.now() - timedelta(days=7)

mentions = client.get_mentions(
    account_id="your-account-id",
    alert_id="your-alert-id",
    not_before_date=week_ago,
    tone="positive",  # Filter by sentiment
    source="twitter",  # Filter by source
    limit=100
)

print(f"Found {len(mentions.mentions)} positive mentions")

Complete Example

Here’s a complete example that demonstrates common operations:
from mention import MentionClient

# Initialize client
client = MentionClient(access_token="your-access-token")

# Get account information
account = client.get_account_me()
print(f"Account: {account.name}")
print(f"Email: {account.email}")

# Fetch all alerts
alerts = client.get_alerts(account.id)
print(f"\nFound {len(alerts.alerts)} alerts")

if alerts.alerts:
    # Get the first alert
    first_alert = alerts.alerts[0]
    print(f"\nProcessing alert: {first_alert.name}")
    
    # Fetch mentions for this alert
    mentions = client.get_mentions(
        account_id=account.id,
        alert_id=first_alert.id,
        limit=10
    )
    
    print(f"\nRecent mentions:")
    for i, mention in enumerate(mentions.mentions, 1):
        print(f"{i}. {mention.title}")
        print(f"   Source: {mention.source_name}")
        print(f"   Tone: {mention.tone}")
        print(f"   Published: {mention.published_at}")

Using Context Manager

For automatic resource cleanup, use the client as a context manager:
from mention import MentionClient

with MentionClient(access_token="your-token") as client:
    alerts = client.get_alerts("account-id")
    # Client is automatically closed when exiting the context

Environment Setup

Using Environment Variables

Store your credentials in a .env file:
.env
MENTION_ACCESS_TOKEN=your-access-token
MENTION_ACCOUNT_ID=your-account-id
Then load configuration from environment:
from mention import MentionClient, MentionConfig

# Load config from environment variables
config = MentionConfig.from_env()

# Create client from config
client = MentionClient.from_config(config)

# Now you can use the client
alerts = client.get_alerts(config.account_id)
The from_env() method automatically loads .env files from your current directory using python-dotenv.

Async Client

For async applications, use AsyncMentionClient:
import asyncio
from mention import AsyncMentionClient

async def main():
    async with AsyncMentionClient(access_token="your-token") as client:
        # All methods are async
        alerts = await client.get_alerts("account-id")
        
        if alerts.alerts:
            mentions = await client.get_mentions(
                account_id="account-id",
                alert_id=alerts.alerts[0].id,
                limit=10
            )
            
            for mention in mentions.mentions:
                print(f"{mention.title} - {mention.tone}")

# Run the async function
asyncio.run(main())

Pagination

Iterate through all mentions using automatic pagination:
# Process all mentions with automatic pagination
for mention in client.iter_mentions(
    account_id="account-id",
    alert_id="alert-id",
    limit=100  # Fetch 100 per page
):
    print(f"{mention.title} - {mention.published_at}")
    
    # The iterator automatically fetches the next page
    # when needed, so you can process all mentions

Error Handling

The client provides specific exception types for different errors:
from mention import (
    MentionClient,
    MentionAuthError,
    MentionNotFoundError,
    MentionRateLimitError,
    MentionAPIError
)

client = MentionClient(access_token="your-token")

try:
    alerts = client.get_alerts("account-id")
except MentionAuthError as e:
    print(f"Authentication failed: {e}")
except MentionNotFoundError as e:
    print(f"Resource not found: {e}")
except MentionRateLimitError as e:
    print(f"Rate limit exceeded. Retry after {e.retry_after} seconds")
except MentionAPIError as e:
    print(f"API error: {e.status_code} - {e}")

Next Steps

Now that you’ve completed the quickstart:

Explore the API

Learn about all available methods and models

Error Handling

Handle exceptions and implement retry logic

Async Client

Use AsyncMentionClient for async applications

Pagination

Work with paginated API responses

Build docs developers (and LLMs) love