Get mentions via Python scripts

If you use Python scripts you can get mentions this way:

import argparse
import datetime
import json
import requests
import sys
import os

BASE_API_URL = "https://api.smelter.ai/v1"


def get_mentions(token, account_name, channel_name, url=None, **filters):
    if not url:
        url = f"{BASE_API_URL}/mentions/{account_name}/{channel_name}"
    else:
        filters = None

    headers = {
        "Accept": "application/json",
        "Content-Type": "application/json",
        "Authorization": f"Bearer {token}",
    }

    r = requests.get(url, headers=headers, params=filters)
    if r.status_code != 200:
        raise Exception(f"Failed to get mentions: status_code={r.status_code}, text={r.text}")
    return r.json()


def print_mentions(token, account_name, channel_name, num_pages, **filters):
    url = None
    mention_ids = set()
    for i in range(num_pages):
        resp = get_mentions(token, account_name, channel_name, url=url, **filters)
        has_next_page = resp["has_next_page"]
        mentions = resp["data"]["mentions"]

        for m in mentions:
            mention_ids.add(m["mention_id"])
            print(f"{m['title']} from {m['url']} at {datetime.datetime.fromtimestamp(m['post_timestamp']).isoformat()}")

        if not has_next_page:
            print(f"No more pages, {i} is last one", file=sys.stderr)

        url = resp["next_page_url"]

    print(f"{len(mention_ids)} unique mentions collected", file=sys.stderr)


def main():
    parser = argparse.ArgumentParser(description="Smelter API example")
    parser.add_argument("--account-name", required=True)
    parser.add_argument("--channel-name", required=True)
    parser.add_argument("--token", required=False, default=os.environ.get("SMELTER_TOKEN"))
    parser.add_argument("--num-pages", required=False, type=int, default=1)
    parser.add_argument("--source-names", required=False, type=str)
    parser.add_argument("--sort-by", required=False, type=str, default="newest_insert_timestamp")

    args = parser.parse_args()
    filters = {
        "source_names": args.source_names.split(",") if args.source_names else [],
        "only_main_topic": True,
        "sort_by": args.sort_by
    }
    print_mentions(args.token, args.account_name, args.channel_name, args.num_pages, **filters)


if __name__ == "__main__":
    main()
Contacts