[Tutor] Responding Tweet: A Twitter Bot

Walter Prins wprins at gmail.com
Fri Feb 21 10:05:13 CET 2014


Hi,

On 21 February 2014 03:52, Zaki Akhmad <zakiakhmad at gmail.com> wrote:
> On Thu, Feb 20, 2014 at 7:39 PM, James Scholes <james at jls-radio.com> wrote:
>
>> Most decent Python libraries for accessing Twitter support the streaming
>> API.  This lets you keep a connection to the Twitter API alive and
>> process new data as it is received.  There is a simple (but out-of-date)
>> example on using streaming with the twitter package you linked to:
>> https://pypi.python.org/pypi/twitter/1.13.1
>
> My question is: how to execute this streaming API?
>
> My current approach is using cron to execute python script which has
> "check the streaming API" function:
>
> def check_mention:
>     if (mention):
>         tweet
>
> If I want to check every minute, then I should configure cron to
> execute this script every minute. Are there any other approach besides
> using cron?

With the caveat that I'm not familiar with the Twitter streaming API's
and that I literally only spend 3 minutes googling this, it seems to
me to be the case that the Twitter streaming API's is intended to be a
push style notification service.

This means you should not in principle ideally be polling the service
for updates yourself (e.g. using sleep/crong etc).  Instead, the docs
say that the streaming API can return an iterator that yields objects
as they're decoded from the stream.  Quote:

"The TwitterStream object is an interface to the Twitter Stream API
(stream.twitter.com). This can be used pretty much the same as the
Twitter class except the result of calling a method will be an
iterator that yields objects decoded from the stream. For example::"

It's highly preferable to not poll something if it will
generate/notify you of new objects, so you should be able to do
something like in their example.  Quote:

twitter_stream = TwitterStream(auth=UserPassAuth('joe', 'joespassword'))
iterator = twitter_stream.statuses.sample()

for tweet in iterator:
    # ...do something with this tweet... (e.g. check if you want to
retweet or something)

So the for loop should just block by itself until a new tweet/message
comes in at which point it will spring to life and hand it to your
code to process.

I hope that helps, and apologies if I misunderstood something or have
missed something that makes my comment irrelevant to your problem.

Walter


More information about the Tutor mailing list