LoginSignup
14
19

More than 5 years have passed since last update.

【解答編】Mastodonで始めるPythonプログラミング!腕試しテスト50本ノック(初級編)

Last updated at Posted at 2018-01-04

本記事は、こちらの解答編となります。

Mastodonで始めるPythonプログラミング!腕試しテスト50本ノック(初級編)
https://qiita.com/itsumonotakumi/items/c3116df7e6b7ee1e169e

正月から家族サービスの片手間にちょこちょこと解答を作っておりましたが、ちょっと50問は多かったです。Python初級者から抜け出しきっていない匠にはハードでした。。。ホントに100本ノックにしなくて良かった(汗

今回はサンプルスクリプト集も兼ねておりますので、皆様のPython力向上&マストドンライフの一助になれば幸いです。

なお、解説付きの解答はこちらをご覧下さい。

【解説編】Mastodonで始めるPythonプログラミング!腕試しテスト50本ノック(初級編)
https://takulog.info/exercise-python-for-mastodon-1-answer/

前提

今回の解答は、下記の前提で記載しています。

  • なるべく requestsモジュール もしくは Mastodon.py を利用して、極力シンプルかつ読みやすいコードにする
    • Mastodon.py を優先的に使用する
  • Python初級者を対象とする
    • プログラミングの基礎知識はある
    • Pythonの基礎的な文法は分かる、あるいはリファレンスなどを読めば分かる
    • 実用的なプログラムはあまり作ったことがない
  • HTTPリクエストやAPIなど、ITに関する基礎知識が分かる
  • Mastodon APIおよび requestsモジュールMastodon.pyモジュールのリファレンスを読みながら利用できる。

サンプルスクリプト

GitHubからダウンロードできるようにしました。

サンプルスクリプト集

解答1.APIの操作準備

1. インスタンスへ疎通確認してください。
(ヒント:HTTPSポートへ何らか通信できればOK)

import requests as r

url = 'https://HOSTNAME'
res = r.get(url)
print(res.ok)

2. インスタンスへのREST APIへの疎通確認してください。
(対象APIやレスポンス値は問わない)

import requests as r

url = 'https://HOSTNAME/api/v1/instance'
res = r.get(url)
print(res.ok)

3. インスタンスへクライアント「Python_Exercise」を登録して、Client ID と Client Secret を取得してください。

from mastodon import Mastodon

url = 'https://HOSTNAME'
appname = 'Python_Exercise'
cid_file = 'client_id.txt'

Mastodon.create_app(
    appname,
    api_base_url=url,
    to_file = cid_file
)

4. インスタンスからアクセストークンを取得して、ファイル「access_token.txt」に保存してください。

from mastodon import Mastodon

url = 'HOSTNAME'
email = 'EMAIL@EXAMPLE.COM'
password = 'PASSWORD'
cid_file = 'client_id.txt'
token_file = 'access_token.txt'

mastodon = Mastodon(
    client_id=cid_file,
    api_base_url=url,
)
mastodon.log_in(
    username = email,
    password = password,
    to_file = token_file
)

5. 上記で保存したアクセストークンを表示してください

token_file = 'access_token.txt'
with open(token_file) as ft:
    print(str(ft.read())

解答2. トゥート投稿

1. 「はじめてのトゥート #Python練習」とトゥート(投稿)してください。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

mastodon.toot('はじめてのトゥート #Python練習')

2. 「2回目のトゥート #Python練習」というテキストと何か画像1つを添付してトゥート(投稿)してください。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'
imgfile1 = 'img1.png'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

img1 = mastodon.media_post(imgfile1)

img_files = [img1]
mastodon.status_post(
    status = 'はじめてのトゥート2 #Python練習',
    media_ids = img_files
    )

3. 「3回目のトゥート #Python練習」というテキストと何か画像4つを添付してトゥート(投稿)してください。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'
img_filenames = ['img1.png', 'img2.png', 'img3.png', 'img4.png']

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

imgs = []
for img in img_filenames:
    imgs.append(mastodon.media_post(img))

mastodon.status_post(
    status = '3回目のトゥート #Python練習',
    media_ids = imgs
    )

4. 「4回目のトゥート #Python練習」というテキストに、「CWの練習」という警告(CW)を付けて、トゥート(投稿)してください。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

mastodon.status_post(
    '4回目のトゥート #Python練習',
    spoiler_text='CWの練習'
    )

5. 「5回目のトゥート #Python練習」というテキストに、何か画像1つを添付して、NSFWで隠してトゥート(投稿)してください。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'
imgfile1 = 'img1.png'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

img1 = mastodon.media_post(imgfile1)

img_files = [img1]
mastodon.status_post(
    status = '5回目のトゥート #Python練習',
    sensitive=True,
    media_ids = img_files
    )

6. 「はじめての非掲載トゥート #Python練習」というテキストを、公開範囲「未収載」に設定してトゥート(投稿)してください。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

mastodon.status_post(
    'はじめての未収載トゥート #Python練習',
    visibility='unlisted'
    )

7. 「はじめての非公開トゥート #Python練習」というテキストを、公開範囲「非公開」に設定してトゥート(投稿)してください。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

mastodon.status_post(
    'はじめての非公開トゥート #Python練習',
    visibility='private'
    )

8. 「@test@itumonotakumi.m.to はじめてのダイレクトトゥート #Python練習」というテキストを、公開範囲「ダイレクト」に設定してトゥート(投稿)してください。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

mastodon.status_post(
    '@test@itumonotakumi.m.to はじめてのダイレクトトゥート #Python練習',
    visibility='direct'
    )

9. 「@test@itumonotakumi.m.to トゥート練習中 #Python練習」というテキストを下記の設定でトゥート(投稿)してください。

  • CW / 警告文「CW練習中」を付与すること
  • 何らか画像を1つ添付 / NSFWを付与すること
  • 公開範囲は「非公開」
import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'
imgfile1 = 'img1.png'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

img1 = mastodon.media_post(imgfile1)

img_files = [img1]
mastodon.status_post(
    status = '5回目のトゥート #Python練習',
    spoiler_text='CWの練習',
    sensitive=True,
    visibility='private',
    media_ids = img_files
    )

10. test@itumonotakumi.m.toに「メンション練習中 #Python練習」というテキストでメンションを送ってください。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

mastodon.toot('@test@itumonotakumi.m.to メンション練習中 #Python練習')

解答3. トゥート操作

1. 練習2-1で投稿したトゥートにお気に入りを付けてください。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# 最初のトゥート
mastodon.toot('はじめてのトゥート #Python練習')

# 最新トゥートにお気に入りを付ける
user_dict = mastodon.account_verify_credentials()
user_toots_dict = mastodon.account_statuses(user_dict['id'], limit=1)
mastodon.status_favourite(user_toots_dict[0]['id'])

2. 上記で付けたお気に入りをトゥートから外してください。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# 最新トゥートのお気に入りを解除する
user_dict = mastodon.account_verify_credentials()
user_toots_dict = mastodon.account_statuses(user_dict['id'], limit=1)
mastodon.status_unfavourite(user_toots_dict[0]['id'])

3. 練習2-1で投稿したトゥートをブーストしてください。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# 最新トゥートをブーストする
user_dict = mastodon.account_verify_credentials()
user_toots_dict = mastodon.account_statuses(user_dict['id'], limit=1)
mastodon.status_reblog(user_toots_dict[0]['id'])

4. 上記でブーストしたトゥートの、ブーストを解除してください。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# 最新のトゥートをブースト解除する
user_dict = mastodon.account_verify_credentials()
user_toots_dict = mastodon.account_statuses(user_dict['id'], limit=1)
mastodon.status_unreblog(user_toots_dict[0]['id'])

5. 練習2-1で投稿したトゥートを削除してください。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)


# 最新のトゥートを削除する
user_dict = mastodon.account_verify_credentials()
user_toots_dict = mastodon.account_statuses(user_dict['id'], limit=1)
mastodon.status_delet(user_toots_dict[0]['id'])

解答4. 自分のアカウント情報の取得

1. アカウント情報を取得して、JSON形式で表示しなさい。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# アカウント情報を取得・表示する
user_dict = mastodon.account_verify_credentials()
print(user_dict)

2. 自分のアカウント名(アカウント名@インスタンス名)のみ表示しなさい。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# アカウント名を表示する
user_dict = mastodon.account_verify_credentials()
print(user_dict['username'] + '@' + url)

3. 自分の表示名のみ表示しなさい。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# アカウントの表示名を表示する
user_dict = mastodon.account_verify_credentials()
print(user_dict['display_name'])

4. 自分のプロフィールの内容のみ表示しなさい。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# 自分のアカウントのプロフィールの内容を表示する
user_dict = mastodon.account_verify_credentials()
print(user_dict['note'])

5. 自分のフォロー数のみ表示しなさい。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# 自分のアカウントのフォロー数を表示する
user_dict = mastodon.account_verify_credentials()
print(str(user_dict['following_count']))

6. 自分のフォロワー数のみ表示しなさい。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# 自分のアカウントのフォロワー数を表示する
user_dict = mastodon.account_verify_credentials()
print(str(user_dict['followers_count']))

7. 自分のお気に入り数のみ表示しなさい。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id_pawoo.txt'
token_file = 'access_token_pawoo.txt'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# 自分のアカウントのお気に入り数を数える
next_id = ''
fav_count = 0

# 自分のアカウントのお気に入り数を数える
while True:
    # ローカルタイムラインの取得
    fetched_favs = mastodon.favourites(limit=40, max_id=next_id)

    # 新しいトゥートが取得できなかったらループ終了
    if len(fetched_favs) > 0:
        fav_count += len(fetched_favs)
    else:
        break

    # 80件以上のページネーションするための値取得
    favs_last = fetched_favs[len(fetched_favs)-1]
    if '_pagination_next' in favs_last.keys() and 'max_id' in favs_last['_pagination_next'].keys():
        next_id = favs_last['_pagination_next']['max_id']
    else:
        break

# お気に入り数を表示
print(fav_count)

8. 自分の最新トゥート10件をJSON形式で表示しなさい。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# 自分の最新トゥート10件を取得する
user_dict = mastodon.account_verify_credentials()
user_toots = mastodon.account_statuses(user_dict['id'], limit=10)

# トゥートを全て表示する
print(user_toots)

9. 自分の最新トゥート1件の時間と内容のみ表示しなさい。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# 自分の最新トゥート1件を取得する
user_dict = mastodon.account_verify_credentials()
user_toots_dict = mastodon.account_statuses(user_dict['id'], limit=1)

# トゥートの時間と内容を表示する
print(user_toots[0]['created_at'], user_toots[0]['content'])

10. 自分の最新トゥート1件のアプリ名のみ表示しなさい。

import sys
from mastodon import Mastodon

URL = sys.argv[1]
CID_FILE = 'client_id.txt'
TOKEN_FILE = 'access_token.txt'


def check_appname(toot):
    ''' アプリケーション名をチェックするルーチン '''
    if toot['application'] and toot['application']['name']:
        return(toot['application']['name'])
    elif toot['application'] and not toot['application']['name']:
        return('Web')
    else:
        return('Unknown')


def main():
    ''' メインルーチン '''
    # Mastodon初期化
    mastodon = Mastodon(
        client_id=cid_file,
        access_token=token_file,
        api_base_url=url
    )

    # 自分の最新トゥート1件を取得する
    user_dict = mastodon.account_verify_credentials()
    user_toots = mastodon.account_statuses(user_dict['id'], limit=1)

    # トゥートのアプリ名があれば表示する
    if user_toots[0]['reblog'] is None:
        print(check_appname(user_toots[0]))           # 通常のトゥートの場合
    else:
        print(check_appname(user_toots[0]['reblog'])) # ブーストされたトゥートの場合


if __name__ == '__main__':
    main()

解答5. 他人のアカウント情報の取得

1. アカウント「いつもの匠(itsumonotakumi@pawoo.net)」を検索して、その結果をJSON形式で表示しなさい。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'
username = 'itsumonotakumi@pawoo.net'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# 対象アカウントのユーザーIDを取得する。
user_list = mastodon.account_search(username, limit=1)
user_id = user_list[0]['id']

# 対象アカウントの情報を表示する。
user_dict = mastodon.account(user_id)
print(user_dict)

2. アカウント「いつもの匠(itsumonotakumi@pawoo.net)」の表示名を表示しなさい。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'
username = 'itsumonotakumi@pawoo.net'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# 対象アカウントのユーザーIDを取得する。
user_list = mastodon.account_search(username, limit=1)
user_id = user_list[0]['id']

# 対象アカウントの表示名を表示する。
user_dict = mastodon.account(user_id)
print(user_dict['display_name'])

3. アカウント「いつもの匠(itsumonotakumi@pawoo.net)」のプロフィール内容のみ表示しなさい。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'
username = 'itsumonotakumi@pawoo.net'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# 対象アカウントのユーザーIDを取得する。
user_list = mastodon.account_search(username, limit=1)
user_id = user_list[0]['id']

# 対象アカウントの表示名を表示する。
user_dict = mastodon.account(user_id)
print(user_dict['display_name'])

4. アカウント「いつもの匠(itsumonotakumi@pawoo.net)」のフォロー数のみ表示しなさい。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'
username = 'itsumonotakumi@pawoo.net'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# 対象アカウントのユーザーIDを取得する。
user_list = mastodon.account_search(username, limit=1)
user_id = user_list[0]['id']

# 対象アカウントのフォロー数を表示する。
user_dict = mastodon.account(user_id)
print(user_dict['following_count'])

5. アカウント「いつもの匠(itsumonotakumi@pawoo.net)」のフォロワー数のみ表示しなさい。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'
username = 'itsumonotakumi@pawoo.net'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# 対象アカウントのユーザーIDを取得する。
user_list = mastodon.account_search(username, limit=1)
user_id = user_list[0]['id']

# 対象アカウントのフォロワー数を表示する。
user_dict = mastodon.account(user_id)
print(user_dict['followers_count'])

6. アカウント「いつもの匠(itsumonotakumi@pawoo.net)」のお気に入り数のみ表示しなさい。

実は、これはちょっと問題のミスです。マストドンでは、他人のお気に入り内容とその数を確認することができません。そのため、この問題の正解は表示できないです。

もし解決方法をご存知の方がいらっしゃれば、ご教授ください。。。

7. アカウント「いつもの匠(itsumonotakumi@pawoo.net)」の最新トゥート10件をJSON形式で表示しなさい。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'
username = 'itsumonotakumi@pawoo.net'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# 対象アカウントのユーザーIDを取得する。
user_list = mastodon.account_search(username, limit=1)
user_id = user_list[0]['id']

# 対象アカウントの最新トゥート10件を取得する
user_toots = mastodon.account_statuses(user_id, limit=10)

# トゥートを全て表示する
print(user_toots)

8. アカウント「いつもの匠(itsumonotakumi@pawoo.net)」の最新トゥート1件の投稿時間と内容を表示しなさい。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'
username = 'itsumonotakumi@pawoo.net'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# 対象アカウントのユーザーIDを取得する。
user_list = mastodon.account_search(username, limit=1)
user_id = user_list[0]['id']

# 対象アカウントの最新トゥート1件を取得する
user_toots = mastodon.account_statuses(user_id, limit=1)

# トゥートの時間と内容を表示する
print(user_toots[0]['created_at'], user_toots[0]['content'])

9. アカウント「いつもの匠(itsumonotakumi@pawoo.net)」の最新トゥート1件のアプリ名のみ表示しなさい。

import sys
from mastodon import Mastodon

URL = sys.argv[1]
CID_FILE = 'client_id.txt'
TOKEN_FILE = 'access_token.txt'
USERNAME = 'itsumonotakumi@pawoo.net'

def check_appname(toot):
    ''' アプリケーション名をチェックするルーチン '''
    if toot['application'] and toot['application']['name']:
        return(toot['application']['name'])
    elif toot['application'] and not toot['application']['name']:
        return('Web')
    else:
        return('Unknown')

def main():
    ''' メインルーチン '''
    # Mastodon初期化
    mastodon = Mastodon(
        client_id=cid_file,
        access_token=token_file,
        api_base_url=url
    )

    # 対象アカウントのユーザーIDを取得する。
    user_list = mastodon.account_search(USERNAME, limit=1)
    user_id = user_list[0]['id']

    # 対象アカウントの最新トゥート1件を取得する
    user_toots = mastodon.account_statuses(user_id, limit=1)

    # トゥートのアプリ名があれば表示する
    if user_toots[0]['reblog'] is None:
        print(check_appname(user_toots[0]))           # 通常のトゥートの場合
    else:
        print(check_appname(user_toots[0]['reblog'])) # ブーストされたトゥートの場合

if __name__ == '__main__':
    main()

10. アカウント「いつもの匠(itsumonotakumi@pawoo.net)」の最新トゥート1件のお気に入りがついているか、ついているならお気に入り数を表示しなさい。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'
username = 'itsumonotakumi@pawoo.net'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# 対象アカウントのユーザーIDを取得する。
user_list = mastodon.account_search(username, limit=1)
user_id = user_list[0]['id']

# 対象アカウントの最新トゥート1件を取得する
user_toots = mastodon.account_statuses(user_id, limit=1)

# トゥートにお気に入り数によって処理を分岐する。
if user_toots[0]['favourited']:
    print(user_toots[0]['favourites_count'])
else:
    print('Not favourited')

解答6. タイムライン表示

1. インスタンスのホスト名(FQDN)を表示しなさい。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# インスタンスのドメイン名を表示する
instance = mastodon.instance()
print(instance['uri'])

2. インスタンスの説明のみ表示しなさい。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# インスタンスの説明を表示する
instance = mastodon.instance()
print(instance['description'])

3. インスタンスのMastodonのバージョンのみ表示しなさい。

import sys
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# インスタンスの説明を表示する
instance = mastodon.instance()
print(instance['version'])

4. インスタンスのローカルタイムラインのトゥートを10件表示しなさい。

import sys
import re
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'
conv = re.compile(r"<[^>]*?>")
toot_num = 10  # 取得するトゥートの件数

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# インスタンスのローカルタイムラインのトゥートを10件表示する
toots = mastodon.timeline_local()
for i in range(0, toot_num):
    toot_text = conv.sub("", toots[i]['content'])
    print("{:%Y-%m-%d %H:%M:%S}, {}".format(toots[i]['created_at'], toot_text))

5. インスタンスの連合タイムラインのトゥートを10件表示しなさい。

import sys
import re
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'
conv = re.compile(r"<[^>]*?>")
toot_num = 10  # 取得するトゥートの件数

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# インスタンスのローカルタイムラインのトゥートを10件表示する
toots = mastodon.timeline_public()
for i in range(0, toot_num):
    toot_text = conv.sub("", toots[i]['content'])
    print("{:%Y-%m-%d %H:%M:%S}, {}".format(toots[i]['created_at'], toot_text))

6. ハッシュタグ「#」のついたトゥートを最新10件のみ表示しなさい。

import sys
import re
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'
conv = re.compile(r"<[^>]*?>")
toot_num = 10  # 取得するトゥートの件数
hashtag = 'こんなマストドンは嫌だ'

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# インスタンスのローカルタイムラインのトゥートを10件表示する
toots = mastodon.timeline_hashtag(hashtag)
for i in range(0, toot_num):
    toot_text = conv.sub("", toots[i]['content'])
    print("{:%Y-%m-%d %H:%M:%S}, {}".format(toots[i]['created_at'], toot_text))

7. 自分が所属するインスタンスのローカルタイムラインのトゥートを100件表示しなさい。

import sys
import re
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'
conv = re.compile(r"<[^>]*?>")
toot_num = 100  # 取得するトゥートの件数

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# インスタンスのローカルタイムラインのトゥートを100件表示する
next_id = ''
toots = []

while (len(toots) < toot_num):
    # ローカルタイムラインの取得
    fetched_toots = mastodon.timeline(
        timeline='local',
        limit=80,
        max_id=next_id
    )

    # 新しいトゥートが取得できなかったらループ終了
    if len(fetched_toots) > 0:
        toots += fetched_toots
    else:
        break

    # 80件以上のページネーションするための値取得
    toots_last = len(toots)-1
    if toots[toots_last]['_pagination_next']['max_id'] is not None:
        next_id = toots[toots_last]['_pagination_next']['max_id']
    else:
        break

# 表示するトゥート数の上限を指定
max_len = toot_num if toot_num < len(toots) else len(toots)

# トゥートを整形して表示する
for i in range(0, max_len):
    toot_text = conv.sub("", toots[i]['content'])
    print("{}, {:%Y-%m-%d %H:%M:%S}, {}".format(
        i+1,
        toots[i]['created_at'],
        toot_text
        )
    )

8. 自分が所属するインスタンスの連合タイムラインのトゥートを100件表示しなさい。

import sys
import re
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'
conv = re.compile(r"<[^>]*?>")
toot_num = 100  # 取得するトゥートの件数

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# インスタンスの連合タイムラインのトゥートを100件表示する
next_id = ''
toots = []

while (len(toots) < toot_num):
    # 連合タイムラインの取得
    fetched_toots = mastodon.timeline(
        timeline='public',
        limit=40,
        max_id=next_id
    )

    # 新しいトゥートが取得できなかったらループ終了
    if len(fetched_toots) > 0:
        toots += fetched_toots
    else:
        break

    # 80件以上のページネーションするための値取得
    toots_last = len(toots)-1
    if toots[toots_last]['_pagination_next']['max_id'] is not None:
        next_id = toots[toots_last]['_pagination_next']['max_id']
    else:
        break

# 表示するトゥート数の上限を指定
max_len = toot_num if toot_num < len(toots) else len(toots)

# トゥートを整形して表示する
for i in range(0, max_len):
    toot_text = conv.sub("", toots[i]['content'])
    print("{}, {:%Y-%m-%d %H:%M:%S}, {}".format(
        i+1,
        toots[i]['created_at'],
        toot_text
        )
    )

9. ハッシュタグ「#」のついたトゥートを最新100件のみ表示しなさい。

import sys
import re
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client.txt'
token_file = 'access_token.txt'
conv = re.compile(r"<[^>]*?>")
toot_num = 100  # 取得するトゥートの件数
hashtag = 'こんなマストドンは嫌だ'  # ハッシュタグの指定

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# 指定したハッシュタグのついたトゥートを100件表示する
next_id = ''
toots = []

while (len(toots) < toot_num):
    # ハッシュタグのついたトゥートの取得
    fetched_toots = mastodon.timeline_hashtag(
        hashtag=hashtag,
        local=False,
        limit=40,
        max_id=next_id
    )

    # 新しいトゥートが取得できなかったらループ終了
    if len(fetched_toots) > 0:
        toots += fetched_toots
    else:
        break

    # 80件以上のページネーションするための値取得
    toots_last = len(toots)-1
    if toots[toots_last]['_pagination_next']['max_id'] is not None:
        next_id = toots[toots_last]['_pagination_next']['max_id']
    else:
        break

# 表示するトゥート数の上限を指定
max_len = toot_num if toot_num < len(toots) else len(toots)

# トゥートを整形して表示する
for i in range(0, max_len):
    toot_text = conv.sub("", toots[i]['content'])
    print("{}, {:%Y-%m-%d %H:%M:%S}, {}".format(
        i+1,
        toots[i]['created_at'],
        toot_text
        )
    )

10. 自分が所属するインスタンスのローカルタイムラインのトゥート200件表示しなさい。
表示形式: 時間/アカウント名/トゥート内容

import sys
import re
from mastodon import Mastodon

url = sys.argv[1]
cid_file = 'client_id.txt'
token_file = 'access_token.txt'
conv = re.compile(r"<[^>]*?>")
toot_num = 200  # 取得するトゥートの件数

mastodon = Mastodon(
    client_id=cid_file,
    access_token=token_file,
    api_base_url=url
)

# インスタンスのローカルタイムラインのトゥートを200件表示する
next_id = ''
toots = []

while (len(toots) < toot_num):
    # ローカルタイムラインの取得
    fetched_toots = mastodon.timeline(
        timeline='local',
        limit=40,
        max_id=next_id
    )

    # 新しいトゥートが取得できなかったらループ終了
    if len(fetched_toots) > 0:
        toots += fetched_toots
    else:
        break

    # 80件以上のページネーションするための値取得
    toots_last = len(toots)-1
    if toots[toots_last]['_pagination_next']['max_id'] is not None:
        next_id = toots[toots_last]['_pagination_next']['max_id']
    else:
        break

# 表示するトゥート数の上限を指定
max_len = toot_num if toot_num < len(toots) else len(toots)

# トゥートを整形して表示する
for i in range(0, max_len):
    toot_text = conv.sub("", toots[i]['content'])
    print("{}, {:%Y-%m-%d %H:%M:%S}/{}/{}".format(
        i+1,
        toots[i]['created_at'],
        toots[i]['account']['username'],
        toot_text
        )
    )

おわりに

なんとか50個の問題を作り終えました。いかがでしたでしょうか。

正直なところ、飛行機や電車での移動中など、様々な場所で作っていました。そのくらい時間が無くてギリギリでした(汗

また別の機会に、別の題材でチャレンジしてみたいと思います。

なお、今回の内容やソースコードが動かないなど、ご意見は下記にご連絡ください。

このエントリーをはてなブックマークに追加
Twitter: @itsumonotakumi
Mastodon: @itsumonotakumi@pawoo.net

14
19
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
14
19