Gaucheで作ったTwitter Botをレンタルサーバーで動くようにした(少し改良もあります)
前に作ったbotは、ずっと起動していなければならないため不便で、
個人的な都合のために止めてしまっていたため、動作再開のために、レンタルサーバー(land.to)で動作するように改良しました。
仕組みも少し変更しています。
プログラム
まず、ソースコードを載せておきます。
#!/home/httpd/tana/bin/gosh ; ニコニコ動画に投稿されたVOCALOIDの新曲を通知するTwitter bot ; 情報は「ぼかにゅー」http://vocanew.naniyueni.org/ から取得。 (use rfc.http) (use rfc.uri) (use net.twitter) (use sxml.ssax) (use sxml.sxpath) (use srfi-1) (use srfi-13) ; 設定 (load "/home/httpd/tana/oauthdata.scm") (define *last-rss-file* "/home/httpd/tana/lastrss-vnewsong") ; Twitter APIを使う準備 (define *cred* (make <twitter-cred> :consumer-key *consumer-key* :consumer-secret *consumer-secret* :access-token *access-token* :access-token-secret *access-token-secret*)) ; nico.msを使った形式にURLを短縮する (define (nico-ms url) (let* ((path (values-ref (uri-parse url) 4)) (id (string-drop path (string-index-right path #\/)))) (uri-compose :scheme "http" :host "nico.ms" :path id))) ; atom形式のXMLからエントリーのtitleとlinkのリストを取得 (define (get-title-and-link atom) (let ((sxml (ssax:xml->sxml (open-input-string atom) '((feed . "http://www.w3.org/2005/Atom"))))) (zip ((sxpath '(feed:feed feed:entry feed:title *text*)) sxml) ((sxpath '(feed:feed feed:entry feed:link @ href *text*)) sxml)))) ; http://vocanew.naniyueni.org/newsong(ぼかにゅーのAtom)を読み込む (define (load-atom) (values-ref (http-get "vocanew.naniyueni.org" "/newsong" :user-agent "vnewsong") 2)) ; 今回取得したデータには入っていて、前回取得したデータには入っていないものをすべて投稿 (let* ((atom (load-atom)) (entries (get-title-and-link atom))) (let ((last (if (file-exists? *last-rss-file*) (with-input-from-file *last-rss-file* (lambda () (read))) '()))) (for-each (lambda (entry) (twitter-update *cred* (string-append (car entry) " " (nico-ms (cadr entry))))) (reverse (lset-difference equal? entries last))) (with-output-to-file *last-rss-file* (lambda () (write entries))))) (display "Content-type: text/plain\n\n") (display "success")
Atomを読み込んだりするところはほとんど変わっていませんが、Gauche-net-twitterライブラリを使うようにして、
サーバーで動かすために、一定時間ごとに起動する方式にしました。(cronで実行しています)
新着を取り出す仕組みも変更したので、取れてないということはかなり減るはずです。
サーバーで動かす方法
http://qanda.me.land.to/wiki/index.php?%BB%C5%CD%CD ここを参考にしました。
こんな感じのcron設定用のスクリプト(setcron.cgi)
#!/bin/sh echo "Content-Type: text/plain" echo crontab - 2>&1 <<EOF MAILTO="" */20 * * * * /home/httpd/tana/public_html/vnewsong.cgi EOF crontab -l 2>&1
と、さっきのソースコード(ファイル名はvnewsong.cgi)と、
OAuth認証用のoauthdata.scm(Schemeプログラム、コードはこんな感じ)
(define *consumer-key* "consumer key") (define *consumer-secret* "consumer secret") (define *access-token* "access token") (define *access-token-secret* "access token secret")
こんなファイルを用意しておいて、
「lftp アカウント名@サーバー名.land.to」としてlftpで接続して
put vnewsong.cgi chmod 700 vnewsong.cgi cd / put oauthdata.scm cd public_html/ chmod 700 setcron.cgi exit
としてアップロードしてから、ブラウザでsetcron.cgiにアクセスしてcronを設定して、
もういちど「lftp アカウント名@サーバー名.land.to」で接続して
rm setcron.cgi exit
でsetcron.cgiを削除しました。