1 of 63

シェルスクリプト言語論

第4回 (2019-05-09)

https://richlab.org/j/2352

金沢大学総合メディア基盤センター�大野浩之�ユニバーサルシェルプログラミング研究所�松浦智之

このスライドのURL⇒ https://richlab.org/j/2y52

1

2 of 63

ShellScript Programming

#4 (2019-05-09)

https://richlab.org/j/2352

Information Media Center, Kanazawa Univ.�Hiroyuki Ohno, Ph.D.�Universal Shell Programming Lab.�Tomoyuki Matsuura

You can get this slide from https://richlab.org/j/2y52

2

3 of 63

第4回概要(2019-05-09)

  • シェルスクリプトとは何か(先週からの続き)
    • 前提:あらかじめ演習環境を整えてきてもらう
      • Twitterクライアント「恐怖!小鳥男」のインストール
      • 小鳥男を使って、シェルスクリプトに慣れ親しむ。
    • 到達目標
      • シェルスクリプトプログラミングを読んでみる
      • シェススクリプトを(見よう見まねで)書いてみる
    • 演習
    • 宿題(シェルスクリプト入門レベルの人向け)

3

4 of 63

Overview of #4(2019-05-09)

  • Introduction for ShellScript (part 2 of 2)
    • Prep.:Finishe installing software for exercises of the lecture
      • “kotoriotoko” A Twitter client with CUI
      • Make sure that kotoriotoko works correctly
    • Goal
      • Be able to read simple ShellScripts
      • Be able to make simple ShellScripts
    • Exercise
    • Assignment (for ShellScript beginners)

4

5 of 63

恐怖!小鳥男

5

6 of 63

“KOTORIOTOKO”�(The Little Birdman)

6

7 of 63

出たな小鳥男、お前は何者だ!

  • その正体は、Twitterの操作をUNIXコマンド化したコマンド群(の形をした怪人)
    • コマンドを叩けば、日常のTwitter操作がほどんどできる
      • tweet.sh "講義なう" → つぶやく
      • twtl.sh @SHARP_JP → タイムライン閲覧
      • twsrch.sh "五月病" → キーワード検索
      • retweet.sh 123456789 → リツイート
      • twfollow.sh @cupnoodle_jp → フォロー
      • dmtweet.sh -t @friend "最近どう?" → DMを送る
      • ……などなど
    • 入手先: https://github.com/ShellShoccar-jpn/kotoriotoko
      • 完全パブリックドメイン(CC0)であり、�誰でも、何の目的にも使用可能

7

8 of 63

“Kotoriotoko”, what are you?

  • “I’m a phantom who disguises myself as a Twitter client program.”
    • You can operate the Twitter with typing the following commands.
      • tweet.sh "Hello, there." → Tweet
      • twtl.sh @somebody → View one’s timeline
      • twsrch.sh "football" → Search by keyword
      • retweet.sh 123456789 → Retweet
      • twfollow.sh @somebody → Follow
      • dmtweet.sh -t @sb "What’s up" → Send a DM
      • ……etc
    • Get me from https://github.com/ShellShoccar-jpn/kotoriotoko
      • Complete Public Domain (CC0)�for everyone, for every purpose

8

9 of 63

小鳥男の恐るべき戦闘能力(性能) その1

  • インストールが超簡単
    • git clone https://github.com/ShellShoccar-jpn/kotoriotoko.git と打ち込むだけ!�(コマンド一発!)
      • gitコマンドがインストールされている場合
      • gitコマンドがインストールされていない場合でも、コマンド三発打つだけ。�wget https://github.com/ShellShoccar-jpn/kotoriotoko/archive/master.zip�unzip master.zip�chmod +x kotoriotoko/BIN/* kotoriotoko/TOOL/* kotoriotoko/UTL/*
    • RubyだPerlだJavaといった言語は一切不要!
      • curlまたはwgetコマンド、そしてOpenSSLだけあればいい。
    • 有名なUNIX用Twitterクライアントの多くは、Ruby 1.9以上+gem を要求する。
      • (やればわかるが)熟練していないとインストールが大変。
    • コンパイルももちろん不要

9

10 of 63

Kotoiotoko’s terrible specs #1

  • Extremely Easy Install
    • Type “git clone https://github.com/ShellShoccar-jpn/kotoriotoko.git” That’s all!�(Only 1 command)
      • Don’t worry if you are not available “git” command, type the following 3 command instead of git.�wget https://github.com/ShellShoccar-jpn/kotoriotoko/archive/master.zip�unzip master.zip�chmod +x kotoriotoko/BIN/* kotoriotoko/TOOL/* kotoriotoko/UTL/*
    • No need any high level languages and middleware
      • Depends only on “cURL” and “OpenSSL” commands
    • Almost all of the other famous Twitter clients depend on Ruby.
      • It’s so hard to install them, you know.
    • No need Compiling, of course!

10

11 of 63

小鳥男の恐るべき戦闘能力(性能) その2

  • ほとんどのOS上で、どこでも動く!
    • コピーするだけで動くOS
      • ほとんどのLinux
      • macOS
      • Cygwin
      • Windows 10のUbuntu
    • コピー+curlまたはwget のインストールで動くOS
      • *BSD
      • 商用UNIXの多く
    • OSごとの固有のコードは、たった1ヶ所だけ
      • Cygwin上のpsコマンド(POSIX非準拠)のために1ヶ所だけ記述
      • 1つ1つ動作試験をしながら対応OSを増やした、わけではない。�始めから特定OSに依存するコードを書かなかっただけ。

11

12 of 63

Kotoiotoko’s terrible specs #2

  • Works on almost all of UNIX-like environments, moreover, works for good!
    • The following OSs require just copying to run kotoriotoko.
      • almost all of Linux
      • macOS
      • Cygwin
      • Windows Subsystem for Linux
    • The following OSs require copying and installing “cURL”+“OpenSSL” to run kotoriotoko.
      • *BSD
      • Most of Commercial UNIXs
    • Only 1 POSIX-incompatible code
      • To support Cygwin, which has a POSIX-incompatible “ps” command.
      • Basically, Kotoriotoko has no multi equivalent routines for multi-OS supporting.�Just caring about not to use POSIX-incompatible codes.

12

13 of 63

小鳥男のねらい

  • 脅威の互換性&インストールの容易さで、世界のコンピューターを制覇!
    • 世界中のユーザー達のコンピューターに小鳥男を送り込む
    • 世界中のユーザー達に小鳥男を使わせる
      • 自分自身を実況するもよし
      • 世界中のTwitter民の思いや行動を諜報するもよし
      • cron等と組み合わせて、ボットを作るもよし
    • POSIX中心主義の布教!(普及)

13

14 of 63

What Kotoriotoko aims

  • Conquer the world computers by the extreme compatibility and sustainability!
    • Step1. Send the Kotoriotoko program to the computers which are owned by the world users.
    • Step2. Make them use Kotoriotoko
      • They will tweet about themselves with Kotoriotoko.
      • They will use Kotoriotoko to observe various trends on Twitter.
      • They will make some “bots” in combination with cron.
    • And we can make the final achievement to propagate the POSIX Centric theory!

Bwahaha!

14

15 of 63

恐怖!小鳥男を使ってみる

15

16 of 63

Try to use Kotoriotoko

16

17 of 63

1-1) Twitterへの登録(アカウント登録)

  • https://twitter.com/signup
    • 普通にTwitterアカウントを作る
      • 既に持っているなら必要なし

17

18 of 63

1-1) Get a Twitter account (1 of 2)

  • https://twitter.com/signup
    • Sign up and get a Twitter account
      • If you don’t have it yet

18

19 of 63

1-2) 【任意】Twitterへの登録(電話番号登録)

  • https://twitter.com/signup
    • ツイート収集(後述)でも�遊びたい人は……�「モバイル設定」で�携帯電話の登録が必要
      • プログラムからの利用は、�やや審査が厳しい。
      • 電話番号を登録すると、�SMSで暗証番号が届く。
      • 届いた暗証番号を入力すれば�登録完了
    • しない人は、2)までスキップ

19

20 of 63

1-2) [option] Register your phone # on the account

  • https://twitter.com/signup
    • For the users who want to do�“A huge amount of Tweets AnalysisYou should also register your cell�phone number to get a developer�account
      • The exam for developer�account is stricter. And,�you have to pass SMS�authentication.
      • You can start the SMS-auth�from “Mobile” menu.
    • If you don’t need it, skip to 2).

20

21 of 63

1-3) 【任意】Twitterへ登録(アプリケーション登録)

  • https://developer.twitter.com/en/apps で“Create an App”を押し、必要事項を入力
    • App Name
      • アプリの名前。好きな名前でいい。
    • Application description
      • アプリのひとこと説明。何でもいい。
    • Website URL
      • アプリのサポートURL。
      • 思いつかなければ、https://github.com/ShellShoccar-jpn/kotoriotoko などでよい。
    • Callback URL
      • 小鳥男では使わない。空欄でよい。
    • などなど
    • 最後に、“Create”を押す。

21

22 of 63

1-3) [option] Create an application account on Twitter

  • Click “Create an App” at https://developer.twitter.com/en/apps, and fill forms
    • App Name
      • App’s name as you like
    • Application description
      • Description for the app
    • Website URL
      • URL for information about the app
      • It’s OK to use https://github.com/ShellShoccar-jpn/kotoriotoko if you don’t have.
    • Callback URL
      • Keep it blank, “kotoriotoko” doesn’t use the function
    • And so forth
    • Finally, chick “Create” button

22

23 of 63

1-4) 【任意】Twitterへの登録(アプリID類の取得)

  1. 今作ったアプリのID類4種類を取得する。
    • https://developer.twitter.com/en/apps で今作った�アプリの横にある “Details” ボタンを押す。
    • 続いて“Keys and Access Tokens”�メニューに移動。
    • そこで“Consumer API keys”と�“Access token & access token secret”を�メモ(コピー)�する。

23

24 of 63

1-4) [option] Get keys and tokens for the application

  • Get 4 tokens for the app you created
    • Go back to https://developer.twitter.com/en/apps and�Click “Details” button for your app.
    • And click “Keys and Access Tokens”�tab
    • Copy the 2 pairs of tokens at�“Consumer API keys” and “Access�token & access token secret”

24

25 of 63

2) 小鳥男のインストール(コピー)

  • gitコマンドがある場合
  • gitコマンドがない場合
    • 適当なディレクトリーで�wget https://github.com/ShellShoccar-jpn/kotoriotoko/archive/master.zipunzip master.zipchmod +x kotoriotoko/BIN/* kotoriotoko/TOOL/* kotoriotoko/UTL/* �と打ち込む。

25

26 of 63

2) Install (copy) Kotoriotoko

  • If git command is available,
  • If not,
    • type the 3 following commands in a proper directory�wget https://github.com/ShellShoccar-jpn/kotoriotoko/archive/master.zipunzip master.zipchmod +x kotoriotoko/BIN/* kotoriotoko/TOOL/* kotoriotoko/UTL/*

26

27 of 63

3-a) 小鳥男の設定(ID登録、1-1)だけやった人向け)

  • ターミナル画面で次のコマンドを打ち込む�cd <小鳥男のインストールdir>/BIN�./getstarted.sh

  • 途中、WebブラウザでTwitterにアクセスするように求められるので�指示に従う。

  • そのTwitterサイトで与えられたPINコードをコピーして、�getstarted.shコマンドに対して打ち込む�

27

28 of 63

3-a) Configuration for the people who did only 1-1)

  • Type the following 2 commands.�cd <kotoriotoko_directory>/BIN�./getstarted.sh

  • The command will display a URL after booting. Then, copy-and-paste it to your web browser and open it.

  • The web page will give you a PIN code. Then, copy-and-paste it to the command and enter.�

That’s all.

28

29 of 63

3-b) 小鳥男の設定(ID登録、1-2)~をした人向け)

  • 手順1-3)で取得したIDを設定ファイルに書き込む

cd kotoriotoko (kotoriotokoをインストールしたディレクトリーに入る)

cd CONFIG (その中のCONFIGディレクトリーに入る )

cp COMMON.SHLIB.SAMPLE COMMON.SHLIB (サンプル設定ファイルを本番用にコピーする)

vi COMMON.SHLIB (設定ファイルを開く)

  • 設定ファイルの最後部に、先程コピーした4つのIDとログインIDを�下記のように追記

###############################################

# My account info

###############################################

readonly MY_scname='hogehoge'

readonly MY_apikey='1234567890123456789012345'

readonly MY_apisec='1234567890123456789012……'

readonly MY_atoken='1234567890-12345678901……'

readonly MY_atksec='1234567890123456789012……'

29

30 of 63

3-b) Configuration for the people who did up to 1-4)

  • Write the 4 tokens got at step 1-3) into the config file “COMMON.SHLIB”

cd kotoriotoko Go to kotoriotoko’s home directory

cd CONFIG And also go into “CONFIG” directory

cp COMMON.SHLIB.SAMPLE COMMON.SHLIB (Duplicate config file from the template)

vi COMMON.SHLIB (Open the config file)

  • Add the following sentense after the tail of the config file�

###############################################

# My account info

###############################################

readonly MY_scname='hogehoge'

readonly MY_apikey='1234567890123456789012345'

readonly MY_apisec='1234567890123456789012……'

readonly MY_atoken='1234567890-12345678901……'

readonly MY_atksec='1234567890123456789012……'

30

31 of 63

4) 小鳥男をとりあえず動かしてみる

  • 小鳥男のプログラムディレクトリーに移動
    • cd ../BIN
  • ツイートコマンドを使ってみる
    • ./tweet.sh "ツイートなう。"
    • Webブラウザーで正しくツイートされたか�確認してみる。
  • 他のコマンドの詳細は�https://github.com/ShellShoccar-jpn/kotoriotoko�の後半に説明あり

31

32 of 63

4) Try to run

  • Go to kotoriotoko command directory
    • cd ../BIN
  • Try to run “tweet.sh” to submit a tweet
    • ./tweet.sh "Hello, this is kotoriotoko"
    • And find the tweet with your web browser�or Twitter app
  • See the following document for more�information about the other commands�https://github.com/ShellShoccar-jpn/kotoriotoko

32

33 of 63

4') 小鳥男 主なコマンドリファレンス

  • 書き込み系

tweet.sh 指定した文章をツイートする。(字数制限に注意)

(例)

./tweet.sh ツイート文 基本形

echo ツイート文 | ./tweet.sh ②標準入力からも送れる

./tweet.sh -r ツイートID ツイート文(返信したい人のID付きで) ③返信ツイートしたい場合

./tweet.sh -f 添付したい画像ファイル名 ツイート文 ④画像(4つまで)や動画(1つまで)付きにしたい場合

retweet.sh 指定したIDのツイートをリツイートする。

(例)

./retweet.sh ツイートID

deltweet.sh 指定したIDのツイートやリツイートを削除する。

(例)

./retweet.sh ツイートID

twfav.sh 指定したIDのツイートをいいねする。 いいねを取り消す。

twunfav.sh (例)

./twfav.sh ツイートID

./twunfav.sh ツイートID

33

34 of 63

4') Kotoriotoko Command reference

  • for writing

tweet.sh Tweet the message (Be careful of the length limitation!)

[example]

./tweet.sh Hello, there. (1)Basic

echo Hello, there. | ./tweet.sh (2)You can also use STDIN.

./tweet.sh -r tweetID message_with_“@somebody“ (3)Reply

./tweet.sh -f imagefile message (4)Tweet with images (up to 4 images)

retweet.sh Retweet the tweet

[example]

./retweet.sh tweetid

deltweet.sh Deleted the tweet

[example]

./deltweet.sh tweetid

twfav.sh Likt/Unlike the tweet

twunfav.sh [example]

./twfav.sh tweetid

./twunfav.sh tweetid

34

35 of 63

4') 小鳥男 主なコマンドリファレンス

  • 読み込み系

twtl.sh 指定したユーザー(無指定時は自分)のタイムラインを表示する

(例)

./twtl.sh 自分のタイムライン

./twtl.sh ユーザーID ②他人のタイムライン

./twtl.sh -n 最大表示件数 ユーザーID ③-nオプションで表示件数を変更可(最大100件)

twsrch.sh 指定したキーワードに該当するツイートを表示する(友達の非公開ツイートも可、5秒に1回の頻度で使用可)

(例)

./twsrch.sh キーワード1 キーワード2 ... ①複数キーワード(AND)指定可能

./twsrch.sh -m ツイートID キーワード ... ②指定ツイートID以前のものだけ検索(過去に遡れる)

./twsrch.sh -v キーワード ... ③-vオプションでツイートの詳細情報も取得できる

./twsrch.sh --rawout=ファイル名 キーワード ... ④--rawoutオプションで生のJSONデータも取得できる

btwsrch.sh 指定キーワードを含むツイートを検索する(公開ツイートのみ、2秒に1回の頻度で使用可)

stwsrch.sh 指定キーワードを含むツイートを検索する(ストリーミング、リアルタイムに検索しつづける、ただし英数)

35

36 of 63

4') Kotoriotoko Command reference

  • for reading

twtl.sh View the user’s timeline

[example]

./twtl.sh (1)my own timeline

./twtl.sh userID (2)other’s

./twtl.sh -n num userID (3)“-n” is to change the max number of tweet to view

twsrch.sh Search out tweets by the keywords

[example]

./twsrch.sh keword1 keyword2 ... (1)multiple keywords means “AND” search

./twsrch.sh -m tweetID keyword ... (2)“-m” means to search the more previous tweets than it

./twsrch.sh -v keyword ... (3)“-v” gives you more in detail

./twsrch.sh --rawout=filename keyword ... (4)“--rawout” also gives you the original date from Twitter API

btwsrch.sh Search out tweet more frequently (up to once in 2 seconds even though “twsrch.sh” is up to once in 5 secs)

stwsrch.sh Search out tweet in streaming mode (this is proper for real-time searching)

36

37 of 63

4') 小鳥男 主なコマンドリファレンス

  • フォロー関係

twfollow.sh 指定したユーザーをフォローする、

twunfollow.sh またはフォローをやめる

(例)

./twfollow.sh ユーザーID

./twunfollow.sh ユーザーID

twfer.sh 指定したユーザー(無指定時は自分)の

フォロワー一覧を表示する

(例)

./twfav.sh ユーザーID

./twfav.sh -n 最大表示件数 ユーザーID

twfing.sh 指定したユーザー(無指定時は自分)の

フォロー一覧を表示する

(例)

./twfing.sh ユーザーID

./twfing.sh -n 最大表示件数 ユーザーID

37

フォロー外しも、小鳥男+シェルスクリプトなら簡単だぞ

38 of 63

4') Kotoriotoko Command reference

  • for following

twfollow.sh Follow the user

twunfollow.sh Stop following the user

[example]

./twfollow.sh userID

./twunfollow.sh userID

twfer.sh View the follower list of the user

[example]

./twfav.sh userID

./twfav.sh -n number userID

twfing.sh View the following user list of the user

[example]

./twfing.sh userID

./twfing.sh -n number userID

38

Hey, @NHK_PR. It’s easy to unfollow a large number of users and make it automatic with using Kotoriotoko and ShellScript.

39 of 63

4') 小鳥男 全コマンド

  • 一覧を表示
    • 現在29個

    • 名前に全て�“tw”を含む

    • DM系は更に�“dm”を含む

    • 詳しくは、�“--help”�またはシェルスクリプト冒頭のコメント参照
  • すべて動詞的に命名してある。(コマンドだから)

39

[richie@ajito ~]$ ls kotoriotoko/BIN

bretwer.sh dmtwview.sh tweet.sh twtl.sh

btwsrch.sh favtws.sh twfav.sh twunfav.sh

btwtl.sh getbtwid.sh twfer.sh twunfollow.sh

deldmtw.sh getstarted.sh twfing.sh twvideoup.sh

deltweet.sh retweet.sh twfollow.sh twview.sh

dmtweet.sh retwer.sh twmediup.sh

dmtwrcv.sh retwers.sh twplsrch.sh

dmtwsnt.sh stwsrch.sh twsrch.sh

[richie@ajito ~]$

40 of 63

4') All command of Kotoriotoko

  • Try to display it.
    • Now 29.

    • Each commands�contain “tw”.

    • And DM commands�contain “dm”.

    • Run them with�“--help” for more info�or view each the header part comments
  • The names of them are like verbs because they are commands.

40

[richie@ajito ~]$ ls kotoriotoko/BIN

bretwer.sh dmtwview.sh tweet.sh twtl.sh

btwsrch.sh favtws.sh twfav.sh twunfav.sh

btwtl.sh getbtwid.sh twfer.sh twunfollow.sh

deldmtw.sh getstarted.sh twfing.sh twvideoup.sh

deltweet.sh retweet.sh twfollow.sh twview.sh

dmtweet.sh retwer.sh twmediup.sh

dmtwrcv.sh retwers.sh twplsrch.sh

dmtwsnt.sh stwsrch.sh twsrch.sh

[richie@ajito ~]$

41 of 63

小鳥男の使い道を考える

41

42 of 63

Suggest the Kotoriotoko’s usage

42

43 of 63

コマンドは動詞、シェルスクリプトで作文して活きる

  • 1000個の単語を覚えるだけでは、1000種類のメッセージしか伝えられない。�複数の単語を使い、作文することで無限の表現が可能になる。

  • コマンド(動詞)も、プログラム(作文)しなければ、できることなど高が知れている。�「恐怖!小鳥男」も、各コマンドをただ使うだけでは、大してスゴくない。

  • 「恐怖!小鳥男」も、複数のコマンドと一緒にプログラムで使うからこそ、�他Twitterクライアントを凌ぐ、恐るべき能力を発揮する。

小鳥男に無限の可能性を与えるのはシェルスクリプト!

43

44 of 63

Commands should be verbs. And should be used by ShellScript.

  • Even though you learn 1000 words, you can only tell 1000 messages. Composing sentences with the words gives you ways to tell various messages.�
  • That’s the same with the kotoriotoko commands. It’s not worth so much to use them individually.

  • The combination among kotoriotoko commands and other UNIX commands makes much greater ability than other Twitter apps.

ShellScript gives infinite ability to kotoriotoko!

44

45 of 63

小鳥男の応用例①

  • Twitter検索山崩し 「ネット検索山崩し」のTwitter版
  • 人数 - 2人以上
  • じゃんけんなどの手段によって順番を決める。
  • 最初のキーワードを twsrch.shで検索する。

./twsrch.sh -n 100 キーワード1 | awk 'END{print NR/5}'

  • 順番に検索するキーワードを述べてゆき、検索結果に該当する該当ツイート数を徐々に減らす。

./twsrch.sh -n 100 キーワード1 キーワード2 … | awk 'END{print NR/5}'

  • 該当件数が1件になれば勝ち(他のプレイヤーは全員負け)。
  • 該当件数が減らなかった場合(ただし100以上の時は除く)や、�件数が0件になってしまった場合は負け。

45

46 of 63

Application of Kotoriotoko #1

  • Tweet taking game
  • Players - 2 or more
  • First of all, decide the order for Twitter search
  • The 1st player does Twitter search with some one word.

./twsrch.sh -n 100 KEYWORD1 | awk 'END{print NR/5}'

  • The next player does it while adding another word.

./twsrch.sh -n 100 KEYWORD1 KEYWORD2 … | awk 'END{print NR/5}'

  • The player who has gotten only one tweet wins the game. (All other players lose)
  • Or the following player loses.
    • who has been able to reduce the number of tweets even adding a word for searching.
    • who has gotten no tweet by adding a word for searching.

46

47 of 63

小鳥男の応用例②

  • @NHK_PRのフォロー解除を自動化してあげる

[参考]発端→ https://twitter.com/NHK_PR/status/722229620871790594

    • 実行すると自分のフォローが解除されるので実行はしないように!
    • xargsコマンドの使い方は下記のページ参照

47

#!/bin/sh

dir=/home/HOGEUSER/kotoriotoko/BIN 小鳥男コマンドのディレクトリー設定

while [ 1 ]; do

$dir/twfer.sh -n 200 | ①フォロー者の一覧

awk '{print $NF}' | (ただし一度に得られるのは200人まで)を

tr -d '()' > /tmp/list.$$.txt 一時ファイルに書き出す。

[ -s /tmp/list.$$.txt ] || break ②一時ファイルが空(=フォロー者が0人)ならばループ終了。

cat /tmp/list.$$.txt | ③フォロー者を1人ずつ

xargs -n 1 $dir/twunfollow.sh 解除する。

done

rm -f /tmp/list.$$.txt

48 of 63

Application of Kotoriotoko #2

  • Unfollow all people I’m following automatically

    • CAUTION! This ShellScript will unfollow your following members actually.
    • See the following document about “xargs” command

48

#!/bin/sh

dir=/home/HOGEUSER/kotoriotoko/BIN set kotoriotoko's home

while [ 1 ]; do

$dir/twfer.sh -n 200 | 1)get the member IDs I'm folloing (up to 200),

awk '{print $NF}' |

tr -d '()' > /tmp/list.$$.txt and write it down into a temporary file

[ -s /tmp/list.$$.txt ] || break 2)Quit when the file already has no members

cat /tmp/list.$$.txt | 3)Unfollow the members one by one

xargs -n 1 $dir/twunfollow.sh

done

rm -f /tmp/list.$$.txt

49 of 63

小鳥男の応用例③

  • DMを使ってモーニングコールを送る(起きるまで何回も)

  • これをcrontabコマンドで登録し、例えば毎朝6時に実行する。

49

#!/bin/sh

twid=MY_ID 対象者のTwitterログインID

dir=/home/HOGEUSER/kotoriotoko/BIN 小鳥男コマンドのディレクトリー設定

while [ 1 ]; do

$dir/dmtwrcv.sh -n 100 | 今日の日付で

awk 'NR%4==1||NR%4==2' | 対象者からDMが来ていれば

sed 's/^.*(@//' | 起きていると見なしてループ終了

tr '\n)' ' \n' |

grep $(date '+%Y/%m/%d') |

grep $twid |

awk 'END{exit (NR>0)?0:1}' || break

$dir/dmtweet.sh --to=$twid '朝だ、起きろ!'    起きていなければ対象者にDMを送信し

sleep 60 1分待つ

done

50 of 63

Application of Kotoriotoko #3

  • Send a wake-up call to me with Twitter DM (direct message)

  • It’s useful to register it in “crontab” of your host

50

#!/bin/sh

twid=MY_ID My twitter account ID

dir=/home/HOGEUSER/kotoriotoko/BIN kotoriotoko’s home directory

while [ 1 ]; do

$dir/dmtwrcv.sh -n 100 | Quit the script

awk 'NR%4==1||NR%4==2' | if I have sent a message (reply) this morning

sed 's/^.*(@//' | to me because it means I have already been

tr '\n)' ' \n' | wake.

grep $(date '+%Y/%m/%d') |

grep $twid |

awk 'END{exit (NR>0)?0:1}' || break

$dir/dmtweet.sh --to=$twid 'GET UP!'  Send a wake-up call and wait for 1 minute.

sleep 60

done

51 of 63

小鳥男の応用例④

  • 「#豆乳」を含むツイートをリツイートするbotを作る

  • これをcrontabコマンドで登録し、例えば1時間毎に実行する。

51

#!/bin/sh

dir=/home/HOGEUSER/kotoriotoko/BIN 小鳥男コマンドのディレクトリー設定

$dir/twsrch.sh -n 100 '#豆乳' | ①「#豆乳」を含むツイートを検索

awk 'NR%5==4||NR%5==0' | ②リツイート・いいね行とURL行のみ抽出

sed 's/^.*\///' | ③URL行から行末のツイートIDを抽出

tr '\n-' ' \n' | ④リツイート・いいね・ツイートIDを1行に横並びにする

grep -v RET | ⑤既に自分がリツイート済のもの(大文字”RET”)は除去

awk '{print $3}' | ⑥3列目にツイートIDのみ抽出

xargs -n 1 $dir/retweet.sh ⑦抽出したツイートIDを1つずつリツイートする

52 of 63

Application of Kotoriotoko #4

  • A Twitter bot retweet the tweets which have the word “#soymilk”

  • It’s useful to register it in “crontab” of your host

52

#!/bin/sh

dir=/home/HOGEUSER/kotoriotoko/BIN Kotoriotoko’s homedirectory

$dir/twsrch.sh -n 100 '#soymilk' | 1)search tweets which have the word "#soymilk"

awk 'NR%5==4||NR%5==0' | 2)pick up only lines having about retweet and URL

sed 's/^.*\///' | 3)pick up tweet-ID out of the URL string

tr '\n-' ' \n' | 4)arrange the infomations side by side

grep -v RET | 5)Remove one having "RET"(already retweeted by me)

awk '{print $3}' | 6)pick up only tweet-ID

xargs -n 1 $dir/retweet.sh 7)retweet the tweet one by one

53 of 63

小鳥男の応用例⑤

  • Yahoo!のリツイート数ランク(=注目記事)ベスト3

  • 検索条件指定は他にもいろいろある
    • いいねn個以上ツイートのみ⇒“min_faves:n”、画像付ツイートのみ⇒“filter:images

53

#!/bin/sh

dir=/home/HOGEUSER/kotoriotoko/BIN 小鳥男コマンドのディレクトリー設定

site=headlines.yahoo.co.jp Yahoo!ニュースのURLを検索キーワードに設定

$dir/twsrch.sh -n 100 min_retweets:1000 $site | ①1000リツイート以上のツイート最新100件を検索

awk 'NR%5==4||NR%5==0' | ②「リツイート・いいね」行と、URL行のみに絞り込む

sed 's/^- //' | ③行頭の“- ”を除去

sed 's/ret://' | ④(4行目にある)リツイート数記号の“ret:”を除去

sed 's/fav://' | ⑤(4行目にある)いいね数記号の“fav:”を除去

sed 's/^.*\///' | ⑥ツイートURLからツイートID以外の文字を除去

awk '{printf($0 "%s",(NF==2)?" ":"\n")}' | ⑦リツイート数・いいね数・ツイートIDを横並びにする

sort -k 1nr,1 | ⑧リツイート数で降順に並べ替え

head -n 3 | ⑨最初の3行(ベスト3)だけにする

awk '{print $3}' | ⑩ツイートID(各行の3列目)だけ表示する

xargs $dir/twview.sh ⑪ツイートIDから元のツイートを表示する

54 of 63

Application of Kotoriotoko #5

  • Make “Yahoo! news retweet number ranking” (best 3)

  • You can customize the search words and parameters
    • min_faves:n” … only tweets having n or more likes
    • filter:images” … only tweets having images

54

#!/bin/sh

dir=/home/HOGEUSER/kotoriotoko/BIN kotoriotoko's home directory

site=headlines.yahoo.com set yahoo's domain name as a search word

$dir/twsrch.sh -n 100 min_retweets:1000 $site | 1)search tweets having over 1000 retweets

awk 'NR%5==4||NR%5==0' | 2)picup lines having about retweet and URL

sed 's/^- //' | 3)shave "- " exists at the head of all lines

sed 's/ret://' | 4)shave "ret:" (the number of retweeted)

sed 's/fav://' | 5)shave "fav:" (the number of liked)

sed 's/^.*\///' | 6)pick up tweet-ID out of the URL string

awk '{printf($0 "%s",(NF==2)?" ":"\n")}' | 7)arrange the infomations side by side

sort -k 1nr,1 | 8)sort lines by retweet number (descending)

head -n 3 | 9)pick up only 3 lines (best 3)

awk '{print $3}' | 10)pick up only tweet-ID

xargs $dir/twview.sh 11)retweet the tweet one by one

55 of 63

宿題

55

56 of 63

Assignment

56

57 of 63

テーマ.「ツイートbot」をつくる

  • 悩めるTwitterユーザー
    • あなたは有名なTwitterユーザー。毎日さまざまなツイートをしており、楽しみにしているフォロワーも多数います。
    • しかし連休中、電波の届かない離島へ旅行にいくことになってしまいました。
    • 長期間ツイートがないと死亡説が流れる恐れがあるため、不在の間、自動でツイートするbotを作ることにしました。

57

58 of 63

Make a tweeting bot

  • Story:
    • You are a famous Twitter user and you post various tweets every day. So, there are a lot of followers who are looking forward to your tweets.
    • However, you have got to visit an island where you can’t use your cell phone for your vacation.
    • There is a risk which the rumors you are dead spread if you don't tweet for a while. So, you have to make a tweeting bot before the vacation.

58

59 of 63

テーマ1.「ツイートbot」をつくる

  • 問題

問1. 定時に挨拶をつぶやくbotを作りなさい。

問2. 時刻に応じて挨拶文を替えなさい。

問3. 不定期につぶやくように工夫しなさい。

問4. その他、あたかも人間がつぶやいているように� 見える工夫をしなさい。

59

60 of 63

Make a tweeting bot

  • Task

1. Make a bot which tweets something on 0,6,12,18 o’clock.

2. Modify the bot to change message each time.

3. Modify the bot to tweet as occasionally

4. Add your idea to the bot to seem as if the bot is a human.

60

61 of 63

テーマ1.「ツイートbot」をつくる

  • ヒント
    • Twitter用語は… 「ツイナビ」で検索 > ツイッターガイド > ツイッター用語集
    • botを作るにはcrontab
      • Cygwinやgnupackでcrontabを使うには http://www.amy.hi-ho.ne.jp/tachibana/cygwin/cron.html
      • ただしgnupackの人は apt-cyg install cron cygrunsrv でインストール
    • 問2で、時刻を得るコマンドはdate
    • 問3で、乱数を得るには�n=$(openssl rand 2 | od -A n -t u2 | tr -d ' ')
      • 変数$nに乱数(0~65535)が入る

61

62 of 63

Make a tweeting bot

  • Hint
    • Glossary: https://help.twitter.com/en/glossary
    • “crontab” (UNIX scheduler) is required for bots
      • https://en.wikipedia.org/wiki/Cron
      • It’s necessary to install or enable for WSL, Cygwin, gnupack
    • “date” command may be required for the 2nd question
    • The following command may be required for the 3rd�n=$(openssl rand 2 | od -A n -t u2 | tr -d ' ')
      • A random number (0~65535) will be set to “n”

62

63 of 63

講義スライド案内 ― Lecture Slide Index

  • Previous
    • #3 https://richlab.org/j/2g52
  • Next
    • #5 https://richlab.org/j/2562

63