+++ date = "2019-12-21" tags = ["mastodon"] title = "mastodonからtwitterに投稿する" slug = "mastodon" +++ この前、golangで使ってるlibがv2にupdateしたとかで書き直さなきゃいけなくて、面倒だと思ってたんだけど、mastodonとtwitter連携が面白そうだったので、それをネタにツールを書き直して、ついでに仕組みを作ってみました。 具体的には、mastodonにtwitterタグを付けて投稿すると、twitterにも投稿されるようにしてみる。 仕組みは、gh-actionsのcronが最短で5分ごとに回してくれるのに目をつけ、これ使えるなと思ってたので、使ってみた。(5分じゃgithubさんの負担大きすぎなので、15分で様子見してる。 [GitHub ActionsにCI/CD機能を搭載〜パブリックリポジトリでは無料で利用可能](https://github.blog/jp/2019-08-21-github-actions-now-supports-ci-cd/) gh-actionsでcron:m15を回して、mastodonはapiから投稿を取得、twitterタグがついてれば、jqで投稿を抜き出し、`date(unix-time)`で15分前のtimeとmastodonの投稿時間を比較し、大きければ新しい投稿と判断して、[syui/twg](https://github.com/syui/twg/releases)からtwitterに投稿するという感じ。 ```sh:.github/workflows/main.yml name: mastodon tweet on: push: branches: - master schedule: - cron: '*/15 * * * *' jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@master - run: | job_time=15 export GOPATH=$HOME/go export PATH=$PATH:$GOROOT/bin:$GOPATH/bin curl -sL https://github.com/syui/twg/releases/download/0.3/linux_amd64_twg -o twg chmod +x twg mkdir -p ~/.config/twg cat .config/twg/user.json| jq ".|=. + {\"Token\":\"${{ secrets.TWITTER_TOKEN }}\",\"Secret\":\"${{ secrets.TWITTER_SECRET }}\"}" > t mv t ~/.config/twg/user.json url=https://mstdn.syui.cf/api/v1 j=mastodon.json user_id=1 url="$url/accounts/$user_id/statuses?limit=40" curl -sSL "$url" -H "Authorization: Bearer ${{ secrets.MASTODON_ACCESS_TOKEN }}" > $j post=`cat $j|jq -r ".[]|select(.tags != [])|select(.tags|.[].name == \"twitter\")|.content"|sed -e 's/<[^>]*>//g' -e 's/#twitter//g'` if [ -z "$post" ];then echo no tag post exit fi date=`cat $j|jq -r ".[]|select(.tags != [])|select(.tags|.[].name == \"twitter\")|.created_at"` now=`date +%s -d "$job_time minutes ago"` for (( i=1;i<=`echo "$date"|wc -l`;i++ )) do date_t=`echo "$date"|awk "NR==${i}"` date_t=`date --date="$date_t" +%s` post_t=`echo "$post"|awk "NR==${i}"` if [ "$date_t" -gt "$now" ];then echo $post_t ./twg p "$post_t" fi done ``` twgはlocalで使えるようにして`~/.config/twg/user.json`からtoken,secretを抜き出し、github-repo-settingにてprivateな環境変数に登録しておく。mastodonも同じような感じで。 twgは、releasesからダウンロードしないと、appのコンシューマキーなどがバイナリに含まれないので、その場合、自身でtwitter devからappを作成、コンシューマなどをゲット後にbuildする必要があります。 また、ci上のtimeとmastodon-server上のtimeが合っているかは気にしなければいけません。合っていなければ調整する必要あり。unix-timeに変換するのは単純に比較演算するため。 これは本来のciの使い方じゃないけど、gh-actions、便利。 こういうのは、[zapier](https://zapier.com/)とか使えば、もっと簡単にできます。