Motivational auto-posting using the Twitter API

image
After reading the article Makaveli Simple Twitter notification service , I decided to do something for twitter.com too.

I will not describe how I came to the conclusion of writing an autopost (bot) for twitter, which would be engaged in motivational “posting”. The essence of the service is that any user who is added to the readers every hour receives a motivational tweet. (Who cares about Twitter is @MotivatorForYou ).

This is just an example of how you can use twitter api to automate writing tweets.

So what was needed:


To work with twitter api you must first register your application. For this
  1. Go to https://dev.twitter.com/ , click "Create an app"
  2. Fill out the form and create the application
  3. So that our script can write tweets, it must be switched to the "Read and write" mode. To do this, go to "Settings" and select "Read and write". (Do not forget to save the changes with the button below)
  4. We return to the “Details” and get 4 keys for working with api (they will need to be entered in our script): Consumer key, Consumer secret, Access token, Access token secret (to get the last two, click the Create my access token button )

All. Now we can work with twitter api.

We are writing a script for posting:

  require_once "twitteroauth/twitteroauth.php"; // Файл из библиотеки для работы с api
  define("CONSUMER_KEY", "<Указываем Consumer key>");
  define("CONSUMER_SECRET", "<Указываем Consumer secret>");
  define("OAUTH_TOKEN", "<Указываем Access token>");
  define("OAUTH_SECRET", "<Указываем Access token secret>");
  $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_SECRET);
  $content = $connection->get('account/verify_credentials');
  $file = file_get_contents(dirname(__FILE__).'/data.txt'); // Получаем список сообщений для отправки
  $array = explode("\n",$file);
  $text = $array[mt_rand(0,sizeof($array) - 1)];
  $connection->post('statuses/update', array('status' => $text)); // Отправляем пост

That's all. Fill it on the server, tell the crown to send every hour.

Also popular now: