Blog

API di Moderazione Commenti Instagram: Automatizza i Tuoi Commenti

Impara ad automatizzare i commenti Instagram usando la Graph API. Costruisci sistemi di moderazione, rispondi programmaticamente e gestisci i commenti su larga scala con TypeScript.

Di

+8

Pubblica ovunque. Una API.

Try Free

Gestire i commenti su più post Instagram diventa opprimente man mano che il tuo pubblico cresce. La moderazione dei commenti Instagram attraverso la Graph API ti permette di costruire sistemi automatizzati che recuperano, filtrano, rispondono e moderano i commenti programmaticamente. Questa guida ti accompagna nell'implementazione di una soluzione completa per la gestione dei commenti usando TypeScript.

Che tu stia costruendo una dashboard per social media, uno strumento di assistenza clienti o un sistema di engagement automatizzato, comprendere l'API commenti Instagram è essenziale. Copriremo tutto, dall'autenticazione di base ai flussi di lavoro avanzati di moderazione con analisi del sentiment.

Requisiti di Accesso all'API

Prima di poter automatizzare i commenti Instagram, devi avere l'accesso API configurato correttamente. La Instagram Graph API richiede un account Facebook Developer e un'app approvata con permessi specifici.

Permessi Richiesti

La tua app necessita di questi scope OAuth per lavorare con i commenti:

const INSTAGRAM_SCOPES = [
  'instagram_business_basic',           // Accesso base all'account
  'instagram_business_content_publish', // Pubblicazione contenuti
  'instagram_business_manage_comments', // Lettura e gestione commenti
  'instagram_business_manage_messages', // Richiesto per risposte private
];

Configurazione dell'Ambiente

Crea un file .env con le tue credenziali:

INSTAGRAM_CLIENT_ID=your_client_id
INSTAGRAM_CLIENT_SECRET=your_client_secret
INSTAGRAM_ACCESS_TOKEN=your_long_lived_token
INSTAGRAM_USER_ID=your_business_account_id

Implementazione dello Scambio Token

I token Instagram iniziano come token a breve durata (1 ora) e devono essere scambiati con token a lunga durata (60 giorni):

interface TokenResponse {
  access_token: string;
  token_type: string;
  expires_in: number;
}

async function exchangeForLongLivedToken(
  shortLivedToken: string,
  clientSecret: string
): Promise<TokenResponse> {
  const baseUrl = 'https://graph.instagram.com';
  
  const response = await fetch(
    `${baseUrl}/access_token?` +
    `grant_type=ig_exchange_token&` +
    `client_secret=${clientSecret}&` +
    `access_token=${shortLivedToken}`,
    { method: 'GET' }
  );

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`Token exchange failed: ${response.status} - ${errorText}`);
  }

  return response.json();
}

async function refreshLongLivedToken(
  currentToken: string
): Promise<TokenResponse> {
  const baseUrl = 'https://graph.instagram.com';
  
  const response = await fetch(
    `${baseUrl}/refresh_access_token?` +
    `grant_type=ig_refresh_token&` +
    `access_token=${currentToken}`,
    { method: 'GET' }
  );

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`Token refresh failed: ${response.status} - ${errorText}`);
  }

  return response.json();
}

Nota: I token a lunga durata devono essere aggiornati prima della scadenza. Configura un cron job per aggiornare i token almeno 7 giorni prima della scadenza.

Recupero dei Commenti sui Post

La base di qualsiasi sistema di moderazione commenti Instagram è il recupero efficiente dei commenti. L'API supporta la paginazione per gestire post con migliaia di commenti.

Recupero Base dei Commenti

interface InstagramUser {
  id: string;
  username: string;
}

interface InstagramComment {
  commentId: string;
  comment: string;
  created: string;
  from: InstagramUser;
  likeCount: number;
  replyCount: number;
  hidden: boolean;
  platform: 'instagram';
  replies: InstagramComment[];
}

interface CommentResponse {
  comments: InstagramComment[];
  pagination: {
    hasMore: boolean;
    cursor?: string;
  };
}

async function getMediaComments(
  accessToken: string,
  mediaId: string,
  options?: { limit?: number; cursor?: string }
): Promise<CommentResponse> {
  const baseUrl = 'https://graph.instagram.com';
  const limit = Math.min(options?.limit || 25, 50);
  
  let url = `${baseUrl}/${mediaId}/comments?` +
    `fields=id,text,timestamp,username,hidden,` +
    `from{id,username},like_count,` +
    `replies{id,text,timestamp,username,hidden,from{id,username},like_count}&` +
    `limit=${limit}&access_token=${accessToken}`;

  if (options?.cursor) {
    url += `&after=${options.cursor}`;
  }

  const response = await fetch(url);
  
  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`Failed to fetch comments: ${response.status} - ${errorText}`);
  }

  const data = await response.json();

  // Costruisci mappa di lookup per dati completi dei commenti
  const commentDataById = new Map<string, any>();
  (data.data || []).forEach((comment: any) => {
    commentDataById.set(comment.id, comment);
  });

  // Identifica gli ID delle risposte da filtrare dal livello superiore
  const allReplyIds = new Set<string>();
  (data.data || []).forEach((comment: any) => {
    (comment.replies?.data || []).forEach((reply: any) => {
      allReplyIds.add(reply.id);
    });
  });

  // Filtra solo i commenti di primo livello
  const topLevelComments = (data.data || [])
    .filter((comment: any) => !allReplyIds.has(comment.id));

  const comments: InstagramComment[] = topLevelComments.map((comment: any) => ({
    commentId: comment.id,
    comment: comment.text,
    created: comment.timestamp,
    from: {
      id: comment.from?.id,
      username: comment.from?.username || comment.username,
    },
    likeCount: comment.like_count || 0,
    replyCount: comment.replies?.data?.length || 0,
    hidden: comment.hidden || false,
    platform: 'instagram',
    replies: (comment.replies?.data || []).map((reply: any) => {
      const fullReplyData = commentDataById.get(reply.id) || reply;
      return {
        commentId: reply.id,
        comment: fullReplyData.text || reply.text,
        created: fullReplyData.timestamp || reply.timestamp,
        from: {
          id: fullReplyData.from?.id || reply.from?.id,
          username: fullReplyData.from?.username || reply.from?.username,
        },
        likeCount: fullReplyData.like_count || reply.like_count || 0,
        hidden: fullReplyData.hidden || false,
        platform: 'instagram',
        replies: [],
        replyCount: 0,
      };
    }),
  }));

  return {
    comments,
    pagination: {
      hasMore: !!data.paging?.next,
      cursor: data.paging?.cursors?.after,
    },
  };
}

Recupero di Tutti i Commenti con Paginazione

Per post con molti commenti, implementa la paginazione per recuperare tutto:

async function getAllComments(
  accessToken: string,
  mediaId: string,
  maxComments: number = 1000
): Promise<InstagramComment[]> {
  const allComments: InstagramComment[] = [];
  let cursor: string | undefined;
  
  while (allComments.length < maxComments) {
    const response = await getMediaComments(accessToken, mediaId, {
      limit: 50,
      cursor,
    });
    
    allComments.push(...response.comments);
    
    if (!response.pagination.hasMore || !response.pagination.cursor) {
      break;
    }
    
    cursor = response.pagination.cursor;
    
    // Rate limiting: attendi tra le richieste
    await new Promise(resolve => setTimeout(resolve, 100));
  }
  
  return allComments.slice(0, maxComments);
}

Build faster with Late

One API call to post everywhere. No OAuth headaches. No platform-specific code.

Free tier • No credit card • 99.97% uptime

Rispondere ai Commenti Programmaticamente

La capacità di rispondere ai commenti Instagram via API programmaticamente abilita l'engagement automatizzato, bot di assistenza clienti e gestione della community su larga scala.

Implementazione Risposta Pubblica

interface ReplyResult {
  replyId: string;
  success: boolean;
  error?: string;
}

async function replyToComment(
  accessToken: string,
  commentId: string,
  message: string
): Promise<ReplyResult> {
  const baseUrl = 'https://graph.instagram.com';
  
  try {
    const response = await fetch(
      `${baseUrl}/${commentId}/replies`,
      {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          message,
          access_token: accessToken,
        }),
      }
    );

    if (!response.ok) {
      const errorText = await response.text();
      return {
        replyId: '',
        success: false,
        error: `Reply failed: ${response.status} - ${errorText}`,
      };
    }

    const data = await response.json();
    return {
      replyId: data.id,
      success: true,
    };
  } catch (error) {
    return {
      replyId: '',
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error',
    };
  }
}

Risposta Privata (Messaggio Diretto)

Instagram permette di inviare un DM privato agli autori dei commenti. Questo è utile per scenari di assistenza clienti:

interface PrivateReplyResult {
  messageId: string;
  success: boolean;
  error?: string;
}

async function sendPrivateReply(
  accessToken: string,
  igUserId: string,
  commentId: string,
  message: string
): Promise<PrivateReplyResult> {
  const baseUrl = 'https://graph.instagram.com';
  
  try {
    const response = await fetch(
      `${baseUrl}/${igUserId}/messages`,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${accessToken}`,
        },
        body: JSON.stringify({
          recipient: {
            comment_id: commentId,
          },
          message: {
            text: message,
          },
        }),
      }
    );

    if (!response.ok) {
      const errorText = await response.text();
      
      // Gestisci casi di errore specifici
      if (errorText.includes('551') || errorText.toLowerCase().includes('already')) {
        return {
          messageId: '',
          success: false,
          error: 'Una risposta privata è già stata inviata a questo commento. Instagram permette solo una risposta privata per commento.',
        };
      }
      
      if (errorText.includes('10903')) {
        return {
          messageId: '',
          success: false,
          error: 'Il commento è più vecchio di 7 giorni. Le risposte private devono essere inviate entro 7 giorni.',
        };
      }
      
      return {
        messageId: '',
        success: false,
        error: `Private reply failed: ${response.status} - ${errorText}`,
      };
    }

    const data = await response.json();
    return {
      messageId: data.message_id || data.id,
      success: true,
    };
  } catch (error) {
    return {
      messageId: '',
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error',
    };
  }
}

Nota: Instagram permette solo UNA risposta privata per commento, e deve essere inviata entro 7 giorni dalla pubblicazione del commento. Pianifica la tua automazione di conseguenza.

Nascondere ed Eliminare Commenti

Una moderazione efficace dei commenti Instagram richiede la capacità di nascondere commenti inappropriati o eliminare le proprie risposte.

Nascondere e Mostrare Commenti

async function hideComment(
  accessToken: string,
  commentId: string
): Promise<{ success: boolean; error?: string }> {
  const baseUrl = 'https://graph.instagram.com';
  
  try {
    const response = await fetch(
      `${baseUrl}/${commentId}?hide=true&access_token=${accessToken}`,
      { method: 'POST' }
    );

    if (!response.ok) {
      const errorText = await response.text();
      return {
        success: false,
        error: `Hide failed: ${response.status} - ${errorText}`,
      };
    }

    return { success: true };
  } catch (error) {
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error',
    };
  }
}

async function unhideComment(
  accessToken: string,
  commentId: string
): Promise<{ success: boolean; error?: string }> {
  const baseUrl = 'https://graph.instagram.com';
  
  try {
    const response = await fetch(
      `${baseUrl}/${commentId}?hide=false&access_token=${accessToken}`,
      { method: 'POST' }
    );

    if (!response.ok) {
      const errorText = await response.text();
      return {
        success: false,
        error: `Unhide failed: ${response.status} - ${errorText}`,
      };
    }

    return { success: true };
  } catch (error) {
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error',
    };
  }
}

Eliminare Commenti

Puoi eliminare solo i commenti che hai fatto tu (le tue risposte):

async function deleteComment(
  accessToken: string,
  commentId: string
): Promise<{ success: boolean; error?: string }> {
  const baseUrl = 'https://graph.instagram.com';
  
  try {
    const response = await fetch(
      `${baseUrl}/${commentId}?access_token=${accessToken}`,
      { method: 'DELETE' }
    );

    if (!response.ok) {
      const errorText = await response.text();
      return {
        success: false,
        error: `Delete failed: ${response.status} - ${errorText}`,
      };
    }

    return { success: true };
  } catch (error) {
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error',
    };
  }
}

Filtraggio Commenti e Regole di Moderazione

Costruire un sistema di moderazione automatizzato richiede la definizione di regole per quali contenuti segnalare, nascondere o a cui rispondere.

Motore di Regole di Moderazione

interface ModerationRule {
  id: string;
  name: string;
  type: 'keyword' | 'regex' | 'sentiment' | 'spam';
  pattern?: string;
  keywords?: string[];
  action: 'hide' | 'flag' | 'delete' | 'reply';
  replyTemplate?: string;
  enabled: boolean;
}

interface ModerationResult {
  commentId: string;
  triggered: boolean;
  matchedRules: string[];
  action: 'hide' | 'flag' | 'delete' | 'reply' | 'none';
  replyMessage?: string;
}

class CommentModerator {
  private rules: ModerationRule[];

  constructor(rules: ModerationRule[]) {
    this.rules = rules.filter(r => r.enabled);
  }

  evaluate(comment: InstagramComment): ModerationResult {
    const matchedRules: string[]

Una API. 13+ piattaforme.

Integra i social in minuti, non settimane.

Progettato per sviluppatori. Apprezzato dalle agenzie. Fidato da 6.325 utenti.