Twitter bot tutorial

Twitter is heavily becoming a source of traffic and with there extremely powerful api , it’s very easy to automate stuff via Twitter bots.

Today i am going to show you a tutorial for very simple but yet very powerful bot which if used effectively can drive great traffic on sites. These bots simply search twitter stream for predefined keywords and tweet target messages to the tweeters. These bots can be set via cron to read stream every few minutes and make responses in real time.

For newbies and starters all Twitter API documentation can be found here , From here we are going to use Search API methods and Status Update REST api method for sending predefined tweets to the users.

Search API can give output both in JSON and ATOM(XML) format , And can take several parameters for searching twitter stream. We are going to use just the query(q) parameter to provide keyword to the search ,A complete parameter list can be found here .

So , Let’s take the parameter query as PHP problem and send them our link of in the tweet. For this we will first search the twitter stream for the keyword PHP problem

< ?php
$url = "";

The response of this query is in a XML format so we will use simplexml PHP extension for converting this XML data in native PHP object. simplexml_load_file function loads and converts xml data directly from the url. It can be easily then traversed via a Php object.

$data = simplexml_load_file($url);

Now the data can be traversed via a foreach loop , $data->entry contains a array of all tweet entries. We will take them one by one in $value. Tweet username can be accessed via $value->author->uri to whom we will be tweeting the predefined message.

foreach ($data->entry as $value)
	$from_name = $value->author->uri;
	$from_name = str_replace ("", "", $from_name);
    	$message = "@$from_name Hey Buddy you can find solution to your problems at #php";

Now we have the users who are looking for help in PHP language (via PHP problem keyword), Now using Twitter PHP wrapper we will tweet this message to the users. This can be easily achieved via CURL, However for the sake of the tutorial we will use mytwitter php class for tweeting back to users.

		require_once( 'mytwitter.php' );
		$twitter =  new MyTwitter('phpcollection', '**********');
 		$result = $twitter->updateStatus($message);

Complete code can be downloaded here

Update: We are also now on github, you can download files directly from

21 thoughts on “Twitter bot tutorial”

  1. Well, it totally depends how you use it, Using it for spam purpose may make twitter your user id as spam, However , if you go slow as few updates per hour. You would be fine.

  2. Learn PHP October 8, 2011 at 4:26 am
    The file went kaput after changing servers , will upload again.

    When ?

  3. Hello,

    would u have examples of code for accepting/responding to follow requests from other accounts?

Leave a Reply