3
1

More than 3 years have passed since last update.

TypeScript + Node.jsで書くTwitterBotの作り方

Posted at

はじめに

おはようございます。こんにちは。こんばんは。
Watatakuです。
今回の内容はTypeScript + Node.jsで書くTwitterBotの作り方です。

この記事の対象者は以下のとおりです。

対象者

  • 初学者
  • モダン環境でTwitterBotが作りたいって方

書かないこと

  • TwitterAPIキーの取得方法

プロジェクト作成

作業ディレクトリに行き、以下のコマンドを入力する。

$ mkdir twitter-bot
$ cd twitter-bot
$ touch index.ts
$ npm init

typescriptを使えるようにする

$ npm install -D typescript
$ npm install -D @types/node
$ npx tsc --init

$ npm install -D ts-node

ts-nodeはjsのトランスパイルなしにtsコードを実行してくれます。
sc --initでtsconfig.jsonも生成しておきます。

その他必要なモジュールのインストール

$ npm install express
$ npm install -D @types/express

$ npm install twitter
$ npm install -D @types/twitter

Twitter Botを作る

index.ts
import express from "express";
import Twitter from "twitter";
import {
  customerKey,
  customerSeacret,
  accsessTokenKey,
  accsessTokenSeacret,
} from "../seacretDirectory/seacret";

const app: express.Express = express();

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

//CROS対応(というか完全無防備:本番環境ではだめ絶対)
app.use(
  (req: express.Request, res: express.Response, next: express.NextFunction) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "*");
    res.header("Access-Control-Allow-Headers", "*");
    next();
  }
);

// 型定義
type Message = {
  message: string;
};
type Params = {
  status: string;
};

const client: Twitter = new Twitter({
  consumer_key: customerKey(),
  consumer_secret: customerSeacret(),
  access_token_key: accsessTokenKey(),
  access_token_secret: accsessTokenSeacret(),
});

const message: Message = {
  message: "Bad Request",
};

//get
app.get("/api", (req: express.Request, res: express.Response) => {
  res.send(JSON.stringify(message));
});

//post
app.post("/api", (req: express.Request, res: express.Response) => {
  const detail_id = req.query.id;
  if (detail_id === "") {
    res.send(JSON.stringify(message));
  } else {
    const params: Params = {
      status:
        "ツイートしたいこと。"
    };

    client.post("statuses/update", params, (tweet: Twitter.ResponseData) => {
      if (tweet) {
        res.json(tweet);
      } else {
        res.json("ツイートできませんでした。");
      }
    });
  }
});

//put
app.put("/api", (req: express.Request, res: express.Response) => {
  res.send(JSON.stringify(message));
});

//delete
app.delete("/api", (req: express.Request, res: express.Response) => {
  res.send(JSON.stringify(message));
});

const port: string | number = process.env.PORT || 8080;
app.listen(port);
console.log("ポート番号" + port + "でWebサーバが立ち上がりました");

実行

$ npx ts-node index.ts

localhost:8080/apiにpostメソッドでアクセスのみツイートされ、その他メソッドのアクセスでは「Bad Request」

最後に

もし間違いとかあればご連絡いただけると幸いです。

以上がTypescript + node.jsでのTwitterBotの作り方でした。TwitterBotを作る際の参考になれば幸いです。

3
1
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
3
1