How to Track Brand Mentions on Twitter and Log Them Using n8n

admin1234 Avatar

## Introduction

For marketing teams at startups and growing businesses, timely awareness of brand mentions on social media is critical to managing reputation, engaging with your audience, and identifying potential leads or issues. Twitter, as a real-time platform, offers a wealth of brand conversation data but manual monitoring is time-consuming and error-prone.

This article provides a step-by-step guide to building an automated workflow using n8n—a powerful open-source automation platform—that continuously tracks your brand mentions on Twitter and logs them into Google Sheets for easy analysis and action. This automation benefits marketing teams by providing near real-time, searchable, and centralized mention tracking without manual effort.

## Tools and Services Integrated

– **Twitter API v2**: For searching tweets mentioning your brand.
– **n8n**: Automation platform to build the workflow.
– **Google Sheets**: To log and archive the brand mentions.

You can extend or adapt this workflow later to send Slack notifications, create HubSpot tickets, or trigger sentiment analysis.

## Prerequisites

1. **n8n instance**: Hosted or local.
2. **Twitter API credentials** with elevated developer access to allow search queries.
3. **Google account** with a Google Sheet created to store mention data.

Make sure your Twitter developer project has access to the v2 API endpoints, especially the recent search endpoint.

## Overview of the Workflow Logic

1. **Trigger:** A scheduled trigger runs every 5 minutes.
2. **Twitter Search:** Query Twitter’s API for recent tweets mentioning your brand.
3. **Filter New Mentions:** Check against previously logged mentions to avoid duplicates.
4. **Log to Google Sheets:** Append new mentions along with metadata.
5. **Optional:** Add error handling and rate-limit awareness.

## Step-by-Step Tutorial

### Step 1: Setup the Scheduled Trigger

– Add an **Interval Trigger** node in n8n.
– Configure it to run every 5 minutes (you can adjust frequency based on API limits and business needs).

### Step 2: Configure Twitter API Credentials

– In n8n, create Twitter API credentials using your bearer token (Twitter API v2).
– If you have not done this, in n8n go to **Credentials > New > Twitter OAuth2 API** or create a **HTTP Request** node with Bearer Token header if native Twitter node lacks search support.

### Step 3: Add the Twitter Search Node

Since the native Twitter node in n8n primarily supports v1.1 endpoints and may lack recent search capabilities with v2, we’ll use an **HTTP Request** node:

– Add an **HTTP Request** node.
– Set the method to **GET**.
– URL: `https://api.twitter.com/2/tweets/search/recent`
– Query parameters:
– `query`: Your brand name or handle (e.g., `”YourBrandName” OR @YourBrandHandle`)
– `tweet.fields`: Specify fields like `created_at,author_id,public_metrics`
– `max_results`: Up to 100 (max allowed)
– Headers:
– `Authorization: Bearer `

Example query string for Twitter API v2 Recent Search:
“`
query=YourBrandName OR @YourBrandHandle&tweet.fields=created_at,author_id,public_metrics&max_results=100
“`

### Step 4: Process Twitter API Response

– The response will be JSON with an array of tweets.
– Use a **Set** or **Function** node to extract relevant data:
– Tweet ID
– Text
– Author ID
– Created At
– Retweet count, like count, reply count (from public_metrics)

Example JavaScript in a Function node:
“`javascript
return items.map(item => {
const tweet = item.json.data;
return {
json: {
id: tweet.id,
text: tweet.text,
author_id: tweet.author_id,
created_at: tweet.created_at,
retweet_count: tweet.public_metrics.retweet_count,
like_count: tweet.public_metrics.like_count,
reply_count: tweet.public_metrics.reply_count
}
};
});
“`

### Step 5: Filter Out Tweets Already Logged

– To avoid duplicates, you need to check if the tweet ID is already present in your Google Sheet.
– Add a **Google Sheets > Lookup Rows** node:
– Connect to your Google Sheet where you log tweets.
– Search by the Tweet ID column.

– Add an **IF** node:
– Condition: If the lookup returns zero rows (tweet not logged yet), then proceed to logging.
– Else, skip.

### Step 6: Append New Mentions to Google Sheets

– Use the **Google Sheets > Append Row** node.
– For each new tweet, append a row with columns:
– Tweet ID
– Text
– Author ID
– Created At
– Retweet Count
– Like Count
– Reply Count

– Connect this node to the IF node’s true output to only log new tweets.

### Step 7: Error Handling and Rate Limit Management

– Twitter API enforces strict rate limits, typically 450 requests per 15 minutes for recent search.
– Since we run every 5 minutes and fetch max 100 tweets, you should be well under limits. Still, add error handling:
– Use a **Error Trigger** in n8n to capture failed runs.
– In the HTTP Request node, handle HTTP status codes 429 (Too Many Requests) by pausing or retrying later.

– Use n8n’s **Execute Workflow** node conditionally with backoff or pause timers.

### Step 8: Workflow Overview Diagram

1. **Interval Trigger** (every 5 mins)
2. **HTTP Request** (Twitter Recent Search API)
3. **Function** (Extract Tweet Data)
4. **Google Sheets Lookup Rows** (Check for existing tweet ID)
5. **IF Node** (If tweet is new)
– Yes: **Google Sheets Append Row**
– No: Skip

## Tips for Robustness

– Store your last query timestamp to only fetch tweets newer than last run to reduce duplicates.
– Implement pagination (next_token in Twitter API) if you want to fetch more than 100 results.
– For brand names with special characters or common words, refine the search query with exact phrases and filters (e.g., `”Your Brand” lang:en -is:retweet`).
– Use environment variables in n8n for tokens and brand name queries to make workflow portable.

## Scaling and Adapting the Workflow

– **Multi-channel Integration:** Extend logging to other platforms like LinkedIn or Facebook using similar API calls.
– **Notifications:** Add Slack or Microsoft Teams nodes to alert marketing teams immediately upon new mention.
– **Sentiment Analysis:** Pipe tweet text through NLP services (Google Cloud NLP, IBM Watson) for sentiment scoring.
– **CRM Integration:** Link positive mentions to HubSpot contacts or create follow-up tasks automatically.
– **Custom Dashboards:** Feed the Google Sheets data into Google Data Studio or another BI tool for visualization.

## Common Errors and How to Fix Them

– **401 Unauthorized:** Check your Twitter API bearer token and credentials.
– **429 Too Many Requests:** Slow down the workflow trigger, implement retry/backoff.
– **Google Sheets Access Errors:** Ensure your Google credentials allow editing and API quota is sufficient.
– **Data Format Issues:** Validate JSON structure returned by Twitter and adjust Function node accordingly.

## Summary

Automating Twitter brand mention tracking enriches marketing intelligence with minimal manual effort. Using n8n and Google Sheets, you can set up a lightweight but scalable pipeline to gather, deduplicate, and store tweets mentioning your brand nearly in real-time.

The described workflow is modular and extendable to support notifications, sentiment analysis, and even lead capture workflows. With a bit of maintenance and tuning, it provides your marketing department with a continuous pulse on social conversations, improving responsiveness and brand visibility.

## Bonus Tip: Enhance Search Precision with Advanced Twitter Queries

To minimize noise and irrelevant mentions, use Twitter’s advanced operators such as:
– `from:` and `to:` (filter by users)
– `-is:retweet` to exclude retweets
– `lang:en` to filter by language
– Exact phrases in quotes

Example:
“`
“Your Brand” OR @YourBrandHandle -is:retweet lang:en since:2024-06-20T00:00:00Z
“`
Incorporate the `since` parameter dynamically by storing the timestamp of the last run to avoid fetching old tweets.

This makes your automation more efficient, ensuring the marketing team gets high-value brand mentions.

By following this practical guide, you can confidently implement and maintain an automated Twitter monitoring system that scales with your business needs.