TwitterBot Day 2

This post refers to work on the 5th of August which was day 52 of my #100daysofcode

I read the Twitter streaming API documentation in a bit more depth today. It seems that whilst you send a request in the format of ‘follow=1234&track=javascript’ the follow and track parameters (and the geo parameter for that matter) are treat with an OR operation. So I was not following all my tweets that also contained ‘javacsript’, I was following all my tweets and all tweets that contained ‘javacsript’. So I was making the typo correction reply to all my tweets, hence the apparent recursion.

So I need to restructure my code so that I follow myself and process the tweet text to find the mis-spelt words. Not a huge problem, regular expressions to the rescue?

Except not so fast with the regex. I mostly use regex for small search and replace or I copy and paste a pattern for things like email addresses.

I had a few runs through weird things like ‘/[hH][tT][mM][lL]/g’ until I remembered the ‘i’ flag for case insensitive (duh!). I also started doing this without making any actual tweets, I did not want another tweet spam fiasco like yesterday. As an aside it is quite interesting watching tweets goo by in the terminal, there is something satisfying about seeing them devoid of their decorations and reduced to their intrinsic text.

The final code (once I worked out that it is a pipe to delimit multiple groups, not a comma):

var stream = client.stream('statuses/filter', {follow:27426152});
stream.on('data', function(event) {
    var regEx = /javacsript|jaavscript/gi;
    var match = event.text.match(regEx);
    console.log(match);
    console.log(event.text);
    if(match !== null) {
        console.log(event.text);
        client.post('statuses/update',
            {status: '@nigeljohnwade Sorry, *javascript*', in_reply_to_status_id: event.id},
            function (err, tweet) {
                if (!err) console.log(tweet)
            }
        );
    }
});

stream.on('error', function(error) {
    throw error;
});

No huge utility in having myself correct myself if I mis-type javascript but I really couldn’t think of anything to make the bot do and I really wanted to go through the process of making one. Looking into the API and reading about some other twitterbots is starting to give me some ideas of how to maybe integrate with other services (the wordnik integration for @picktwobot is especially interesting) but for now it is another exercise to ‘tick done’ and a shell to come back to later.

Show your support

Clapping shows how much you appreciated Nigel Wade’s story.