LoginSignup
13
16

More than 5 years have passed since last update.

twitterのbot作成

Last updated at Posted at 2014-01-21

MySQLデータベースからデータを取得して呟くbotを作成しました。

準備するもの:

  • アプリケーションの登録
  • twitteroauth
  • サーバ環境(データベース)

上の2つについてはこちらに詳しい説明があります↓
http://www.sdn-project.net/labo/oauth.html

サーバはcron(一定時間ごとにツイートさせることができる機能)が必要です。制作段階ではXAMPPを使っていました。

Code:

bot.php
<?php
require_once("./twitteroauth.php");

const C_KEY = 'consumer_key';
const C_SECRET = 'consumer_secret';
const A_TOKEN = 'access_token';
const A_SECRET = 'access_token_secret';

try{
    //データベースに接続。
    $dbh=new PDO('mysql:host=localhost; dbname=foo_db','user','password');
    //エラーを出力
    $dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);
    //SQLインジェクション攻撃への対策
    $dbh->PDO::setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    //クエリ発行
    $stmt = $dbh->query("select * from foo_db");
    //データを取得
    $tweet=$stmt->fetch(PDO::FETCH_ASSOC);
    $data=$tweet['data'];

    //OAuth認証
    $TwitterOAuth=new TwitterOAuth(C_KEY,C_SECRET,A_TOKEN,A_SECRET);
    //Twitter APIが1.1の場合
    $TwitterOAuth->host='https://api.twitter.com/1.1/';

    $status=$TwitterOAuth->post('statuses/update',['status'=>$data]);
} catch(PDOExcption $e){
    var_dump($e->getMessage());
    break;
}
//データベースを切断
$dbh = null;

実際に稼働させるにはtwitteroauth.phpとOAuth.phpをサーバに上げる必要があります。

参考(上記3つはドットインストール):

ツイッターボットを作る (全10回)
PHP入門(応用編) (全12回)
MySQL入門 (全19回)

PHP+PDO+MySQLの組み合わせではSQLインジェクション攻撃で複文呼び出しが可能
PHP - TwitterOAuthの正しい使い方

13
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
16