Como criar uma ferramenta de análise de sentimentos no Twitter

npm init
npm install twitter-lite

Isso criará um novo projeto NodeJS e instalará o twitter-lite pacote. Este pacote facilita a interação com a API do Twitter.

Para autenticar nossas solicitações, usaremos um token de portador OAuth2.0. o twitter-lite O pacote tem uma maneira fácil de lidar com a autenticação do Twitter.

Vamos criar um novo index.js e adicione o seguinte código a ele:

const Twitter = require('twitter-lite');

const user = new Twitter({
    consumer_key: "YOUR_API_KEY",
    consumer_secret: "YOUR_API_SECRET",
});

// Wrap the following code in an async function that is called
// immediately so that we can use "await" statements.
(async function() {
    try {
        // Retrieve the bearer token from twitter.
        const response = await user.getBearerToken();
        console.log(`Got the following Bearer token from Twitter: ${response.access_token}`);
        
        // Construct our API client with the bearer token.
        const app = new Twitter({
            bearer_token: response.access_token,
        });
    } catch(e) {
        console.log("There was an error calling the Twitter API.");
        console.dir(e);
    }
})();

Ao executar isso, o console gera o seguinte:

Got the following Bearer token from Twitter: THE_TWITTER_BEARER_TOKEN

Impressionante, até agora tudo funciona. 🔥

Obtendo tweets recentes

A próxima parte é recuperar tweets recentes da API do Twitter.

No Documentação do Twitter você pode ver que há um ponto de extremidade para procurar tweets recentes.

Para implementar isso, adiciono o seguinte código ao index.js Arquivo:

const Twitter = require('twitter-lite');

(async function() {
    const user = new Twitter({
        consumer_key: "YOUR_API_KEY",
        consumer_secret: "YOUR_API_SECRET",
    });

    try {
        let response = await user.getBearerToken();
        const app = new Twitter({
            bearer_token: response.access_token,
        });

        // Search for recent tweets from the twitter API
        response = await app.get(`/search/tweets`, {
            q: "Lionel Messi", // The search term
            lang: "en",        // Let's only get English tweets
            count: 100,        // Limit the results to 100 tweets
        });

        // Loop over all the tweets and print the text
        for (tweet of response.statuses) {
            console.dir(tweet.text);
        }
    } catch(e) {
        console.log("There was an error calling the Twitter API");
        console.dir(e);
    }
})();

Ao executar isso, você pode ver muitos comentários do Twitter sobre Lionel Messi, o que significa que ele funciona perfeitamente! ⚽

"RT @TheFutbolPage: Some of Lionel Messi's best dribbles."

"RT @MagufuliMugabe: Lionel Messi 🐐 didn't just wake up one day  and become the best player in the world no  HE trained. So if your girl is…"

""RT @goal: The boy who would be King 👑 Is Ansu Fati the heir to Lionel Messi's throne?"

and many more... 

Executando análise de sentimentos

Para realizar a análise de sentimentos, vou usar a API de linguagem natural do Google Cloud. Com esta API, você pode obter a pontuação de sentimento de um texto com uma simples chamada de API.

Primeiro, vá para o Google Cloud Console para criar um novo projeto de nuvem.

Em seguida, vá para o API de linguagem natural e habilitá-lo para o projeto.

Por fim, precisamos criar uma conta de serviço para nos autenticar. Vá para o crie uma página de conta de serviço para criar uma conta de serviço.

Ao criar uma conta de serviço, você precisará baixar o json arquivo contendo a chave privada dessa conta de serviço. Armazene esse arquivo na pasta do projeto.

O Google tem um pacote NodeJS para interagir com a API de linguagem natural, então vamos usá-lo. Para instalá-lo, execute:

npm install @google-cloud/language

Para que o pacote de idiomas funcione, ele precisa saber onde está o arquivo de chave privada.

O pacote tentará ler um GOOGLE_APPLICATION_CREDENTIALS variável de ambiente que deve apontar para esse arquivo.

Para definir essa variável de ambiente, atualizo o script chave no package.json Arquivo.

"scripts": {
  "start": "GOOGLE_APPLICATION_CREDENTIALS='./gcloud-private-key.json' node index.js"
}

Observe que, para que isso funcione, você deve iniciar o script executando npm run start.

Com tudo isso configurado, podemos finalmente começar a codificar.

Eu adiciono um novo getSentiment função para o index.js Arquivo:

const language = require('@google-cloud/language');
const languageClient = new language.LanguageServiceClient();

async function getSentiment(text) {
    const document = {
        content: text,
        type: 'PLAIN_TEXT',
    };

    // Detects the sentiment of the text
    const [result] = await languageClient.analyzeSentiment({document: document});
    const sentiment = result.documentSentiment;

    return sentiment.score;
}

Essa função chama a API do Google Natural Language e retorna uma pontuação de sentimentos entre -1 e 1.

Vamos testá-lo com alguns exemplos:

getSentiment("I HATE MESSI");

Retorna o seguinte.

The sentiment score is -0.40

Similarmente:

getSentiment("I LOVE MESSI");

Retorna um sentimento maior. 🙌

The sentiment score is 0.89

Reunindo tudo isso

A última coisa a fazer é chamar o getSetiment função com o texto dos tweets.

No entanto, há um problema: apenas as primeiras 5.000 solicitações de API são gratuitas; depois disso, o Google cobrará pelas solicitações subsequentes de API.

Para minimizar a quantidade de chamadas de API, vou combinar todos os tweets em uma única sequência da seguinte maneira:

let allTweets = "";
for (tweet of response.statuses) {
	allTweets += tweet.text + "n";
}

const sentimentScore = await getSentimentScore(allTweets);
console.log(`The sentiment about ${query} is: ${sentimentScore}`);

Agora só preciso chamar a API uma vez em vez de 100 vezes.

A pergunta final é clara: o que o Twitter pensa sobre Lionel Messi? Ao executar o programa, ele fornece a seguinte saída:

The sentiment about Lionel Messi is: 0.2

Então, o Twitter é levemente positivo sobre Lionel Messi.

Conclusão

Criamos um programa NodeJS que interage com a API do Twitter para obter tweets recentes. Em seguida, envia esses tweets para a API do Google Cloud Natural Language para realizar uma análise de sentimentos.

Você pode encontrar uma versão ao vivo deste análise de sentimentos aqui.

Você também pode ver o código completo aqui no Github.