# KOL Management

The **KOL (Key Opinion Leader) Management** feature in Bragabot enables projects to monitor and analyze the activity of their KOLs on Twitter. This feature tracks tweets related to specific KOLs and keywords, capturing engagement metrics and storing this data for further analysis and reporting. Unlike the Live Twitter Mentions and Tweets Forwarding features, KOL Management relies solely on a recent search mechanism, fetching tweets from the past 45 minutes. The feature also incorporates Braga Premium and Braga Pay-as-Go tiers to manage service access and billing.

## Architecture Overview

1. **Custom KOL Management Endpoint**: A dedicated service running in a Kubernetes pod that periodically searches for tweets related to KOLs and tracks engagement metrics.
2. **Bragabot Backend**: The core platform where KOL settings are managed, reports are generated, and data is displayed or exported.
3. **Database**: Stores information on KOLs, keywords, tracked tweets, and engagement metrics. It also records client tier details and billing information.

## Workflow



<figure><img src="https://1288977065-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FFxGgNZO7ar52lsrkVXYY%2Fuploads%2Fl1US727MutPhH4SObhtj%2Fdiagram%20(1).png?alt=media&#x26;token=c6dbb2ce-525f-4171-a849-99361a3cdec7" alt=""><figcaption><p>KOL Management Workflow</p></figcaption></figure>

## Components and Implementation Details

### **1. Custom Twitter Endpoint**

The Custom Twitter Endpoint is responsible for periodically searching Twitter for tweets related to tracked KOLs and keywords, capturing engagement metrics, and storing the data for reporting purposes.

### **1.1. Periodic Tweet Search for KOLs**

The service performs a search every 15 minutes to gather tweets related to the tracked KOLs and keywords. It processes these tweets to capture engagement metrics and stores them in the database for future reporting.

**Steps**:

1. **Fetching Active KOL Management Settings**:
   * The service queries the database to retrieve all groups where KOL Management is enabled.
   * For each group, it fetches the list of KOLs and associated keywords (hashtags, account mentions, or other terms) that needs to be tracked.
2. **Building Search Queries**:
   * The service constructs search queries for Twitter based on the KOLs and keywords defined for each group.
   * Queries include filters for specific tweet types, such as excluding replies or including only retweets or quote tweets.

**Code Example**: Constructing search queries for KOLs.

```python
def build_kol_search_queries(groups):
    queries = []
    for group in groups:
        if group.kol_management_active:
            for kol in group.kols:
                # Construct the base query using the Twitter handle
                base_query = f"from:{kol.twitter_handle}"
                
                # Append keywords to the base query
                for keyword in kol.keywords:
                    base_query += f" {keyword}"
                
                # Conditionally exclude replies, retweets, and quotes
                if not group.include_replies:
                    base_query += " -is:reply"
                if not group.include_retweets:
                    base_query += " -is:retweet"
                if not group.include_quotes:
                    base_query += " -is:quote"

                # Store the query with its corresponding group ID
                queries.append({"query": base_query, "group_id": group.id})
    
    return queries

# Usage
groups = fetch_active_kol_groups_from_db()
kol_search_queries = build_kol_search_queries(groups)
```

3. **Fetching Tweets for the Last 45 Minutes**:
   * The service uses the constructed queries to fetch tweets posted within the last 45 minutes. This timeframe is chosen to allow for capturing engagement metrics such as likes, retweets, and replies in this timeframe.

**Code Example**: Fetching tweets from the last 45 minutes.

```python
from bragabot_utils import TimeUtils

def fetch_kol_tweets(query):
    since_time = (TimeUtils.get_current_utc_time() - timedelta(minutes=45)).isoformat()
    full_query = f"{query['query']} since:{since_time}"
    return twitter_api.search_recent_tweets(query=full_query)

# Usage
for query in kol_search_queries:
    tweets = fetch_kol_tweets(query['query'])
```

4. **Processing and Storing Tweets**:
   * For each tweet fetched:
     * **Check Client Tier**: Determine if the group is on Braga Premium or Braga Pay-as-Go.
     * **Braga Premium**: The tweet and its metrics are stored directly.
     * **Braga Pay-as-Go**: Additional checks are performed to ensure sufficient funds are available. If funds are sufficient, the tweet is processed and stored; otherwise, it is logged for insufficient funds.
     * **Engagement Metrics**: The tweet's engagement metrics (e.g., impressions, likes, retweets, replies) are captured and stored in the database.

**Code Example**: Processing a KOL tweet and capturing engagement metrics.

```python
def process_kol_tweet(tweet, group):
    engagement_metrics = {
        "impressions": tweet['public_metrics']['impression_count']
        "likes": tweet['public_metrics']['like_count'],
        "retweets": tweet['public_metrics']['retweet_count'],
        "replies": tweet['public_metrics']['reply_count']
    }
    
    if group.client_tier == "premium":
        # Store the tweet and metrics directly
        store_kol_tweet_in_db(tweet, group.id, engagement_metrics)
    elif group.client_tier == "pay_as_you_go":
        if check_and_deduct_funds(group):
            store_kol_tweet_in_db(tweet, group.id, engagement_metrics)
        else:
            log_insufficient_funds(group)
    else:
        log_unsupported_tier(group)

# Usage
for tweet in tweets:
    process_kol_tweet(tweet, group)
```

### **1.2. Managing Client Tiers: Braga Premium vs. Braga Pay-as-Go**

The KOL Management feature includes checks to handle different client tiers. Braga Premium users receive all tweets and engagement metrics without additional charges, while Braga Pay-as-Go users must have sufficient funds for each processed tweet.

**Steps**:

1. **Checking Client Tier**:
   * For each group, the service checks whether the group is on Braga Premium or Braga Pay-as-Go.
2. **Handling Braga Pay-as-Go**:
   * If the group is on Braga Pay-as-Go, the service checks the available funds before processing each tweet. The required amount is deducted from the group's balance.

### **1.3. Reporting and Data Access**

The stored tweets and engagement metrics are available to clients via the Bragabot dashboard. Clients can view reports directly from the Bragabot Telegram Mini App or export the data in Google Sheets.

**Steps**:

1. **Generating Reports**:
   * When a client requests a report, the backend queries the database for the relevant tweets and metrics.
   * Reports can be generated for specific timeframes, KOLs, or keywords.
2. **Exporting to Google Sheets**:
   * The system provides an option to export the report data into Google Sheets

## **2. Bragabot Backend Integration**

**Overview**: The Bragabot Backend manages the settings for KOL Management, including tracking keywords and KOLs, client tier details, and report generation.

**Key Functions**:

* **KOL and Keyword Management**: Admins can add, remove, and manage KOLs and associated keywords to track.
* **Report Access and Export**: Admins can access and export KOL activity reports through the dashboard.



The **KOL Management** feature in Bragabot is a powerful tool for tracking and analyzing the social activity of Key Opinion Leaders. By leveraging a periodic search mechanism and capturing engagement metrics, Bragabot provides detailed insights into KOL performance, which can be accessed and exported by clients. The implementation supports both Braga Premium and Braga Pay-as-Go tiers, ensuring flexible access based on client needs. The modular design, operating within a dedicated Kubernetes pod, ensures the service is scalable and robust, making it an essential feature for projects looking to monitor and leverage KOL influence in their marketing strategies.
