(2024-03-18 初稿 - 2025-02-23 追記・修正)
(2025-02-23追記)
pythonでようやくvenvを使えるようになったのと、投稿ができなくなっていたので、このページもvenvを使う方法に書き換え、twikitのパッケージを更新することにした。
スクリプトもasyncを利用する方法に書き換えて、正常動作を確認したところで、X(旧Twitter)からアカウントを凍結されてしまった。(T_T)
以下のスクリプトで完璧に動作すると思うが、利用する場合はくれぐれもアカウントの凍結にご注意を!!
(追記終了)
はじめに
X(旧 twitter)は、自分にとっては、ライフログを取る道具だったのだけど、度重なるAPIの変更で、最近は面倒になって放置中だった(笑)。
ところが、以下の記事を見つけて、ほんとに久しぶりにpythonを書いてみた。
この記事は、上記のサンプルや以下のドキュメントを見て、素人がpython3でtwikitを使って、tweetする方法と自らのtweetを取得するサンプルを記述する。
普段から、pythonを使っている方なら、もっと良いスクリプトが書けると思うので、あくまでもサンプルのつもり。
筆者はDebian 12(bookworm)を使っているが、twikitのインストールは、以下のとおり、とても行儀の悪い方法で行った。
$ pip3 install twikit --break-system-packages
皆さんは、仮想環境(venv)を作成してtwikitをインストールしてください。
(2025-02-23 追記)
上記は、本当にお行儀の悪い方法なので、以下では、~/pysrc/twikit/に仮想環境を作成し、twikitパッケージをインストールする方法を示す。
$ mkdir -p ~/pysrc/twikit/ # ディレクトリ作成 $ cd ~/pysrc/twikit $ python3 -m venv venv # 仮想環境の作成 $ source venv/bin/activate # アクティベート (venv)$ pip install twikit # パッケージのインストール
スクリプトは ~/pysrc.twikit ディレクトリ内に作成する
(追記終了)
作成したスクリプトについて
作成したスクリプトは、後述するが、基本的な使い方は以下のとおり。
コマンドライン引数
twk.py "つぶやきたいことをコマンドライン引数で指定する"
コマンドライン引数がないときは、自分のつぶやきを19個(?)取得する。countの数を変更しても、なぜか19個のtweetしか取得できない…^^;
筆者の場合は、ライフログ的な使い方を想定しているので、自分のつぶやきを取得することを重視している。
クッキー(cookie)
twikitは、毎回、ログイン環境を変更する仕様となっているようで、Xにログインするたびに、以下の通知やメールが届く。
Xの通知
ご利用のアカウント(@hogehoge)に新しい端末からログインがありました(2024年3月18日)。確認してください。
mailの警告
ご利用のアカウント(@hogehoge)に新しい端末からログインがありました。確認してください。
そこで、ドキュメントにもあるように、cookieを利用する。
cookieを保存しておき、次回起動時に読み込めば、ログインを省略してつぶやいたり、tweetを取得できたりする。
このスクリプトでは、cookieの保存場所を、以下にしてあるので、適当にディレクトリやファイル名を変更をしてください。
~/.config/twikit/twikit_cookies.json
その他
このスクリプトでは、以下の設定にしてあるので、こちらも適当に変更してください。
auth_info_1='hogehoge', auth_info_2='hogehoge@example.com', password='yourpassword'
もう一つ、twikitを使う上で、重要なこと。
「あまり頻繁に利用しないこと。」頻繁に利用すると、エラーになる。
筆者の場合、最低でも5分間は間隔をあけて、利用するようにしている。
作成したスクリプト
twikitのパッケージが2.3.3にアップデートしており、asyncを使うスクリプトに変更になっていたため、頑張って非同期スクリプトに挑戦してみた。
asyncのスクリプトは初めてのため、変なところがあったら、教えてください。
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# tweet with twikit
# ver 0.01 2024-03-08 start
# ver 0.02 2024-03-18 save cookie
# ver 0.03 2024-03-18 tweet and get tweets
# ver 0.04 2024-03-18 tweet output format 変更
# ver 0.05 2024-04-03 while get tweets error then loop 変更
# ver 0.06 2025-02-23 async twikit 2.3.3 対応
import os
import sys
import time
from datetime import datetime, timedelta, timezone
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta
from twikit import Client
import asyncio
cookie_file = 'twikit_cookies.json'
cookie_dir = os.path.expanduser("~/.config/twikit/")
cookie_path = cookie_dir + cookie_file
if not os.path.isdir(cookie_dir):
os.mkdir(cookie_dir)
client = Client('ja')
async def create_tweet(arg):
await client.create_tweet(arg)
async def get_tweet():
user = await client.get_user_by_screen_name('hymd3a')
user_id = user.id
while True:
tweets = await client.get_user_tweets(user_id, 'Tweets', count=20 )
print( len(tweets) )
if tweets:
break
time.sleep(1)
for tweet in tweets:
tw_jtime = parse(tweet.created_at) + relativedelta(hours=+9)
tw_strtime = tw_jtime.strftime("%Y-%m-%d %H:%M:%S")
print( '[%s] %s' % (tw_strtime, tweet.text) )
async def main():
# cookie
if os.path.isfile(cookie_path):
client.load_cookies(cookie_path)
else:
await client.login(
auth_info_1='hogehoge',
auth_info_2='hogehoge@example.com',
password='yourpassword'
)
client.save_cookies(cookie_path)
# 引数の数
# 2: tweetする
# other: tweetを得る
args = sys.argv
if len(args) == 2:
await create_tweet(args[1])
else:
await get_tweet()
asyncio.run(main())
(以下、oldなので参考までに)
#!/usr/bin/python3 # -*- coding: utf-8 -*- # tweet by twikit # ver 0.01 2024-03-08 start # ver 0.02 2024-03-18 save cookie # ver 0.03 2024-03-18 tweet and get tweets import os import sys from twikit import Client cookie_file = 'twikit_cookies.json' cookie_dir = os.path.expanduser("~/.config/twikit/") cookie_path = cookie_dir + cookie_file #print("cookie_fullpath= ", cookie_path ) if not os.path.isdir(cookie_dir): os.mkdir(cookie_dir) client = Client('ja') if os.path.isfile(cookie_path): client.load_cookies(cookie_path) else: client.login( auth_info_1='hogehoge', auth_info_2='hogehoge@example.com', password='yourpassword' ) client.save_cookies(cookie_path) # 引数の数 # 2: tweetする # other: tweetを得る args = sys.argv if len(args) == 2: client.create_tweet(args[1]) else: user = client.get_user_by_screen_name('hogehoge') user_id = user.id #print(user_id) tweets = client.get_user_tweets(user_id, 'Tweets', count=20 ) #print( len(tweets) ) for tweet in tweets: print( '=============' ) print( tweet.text ) print( tweet.created_at )
(old 終了)
スクリプトを実行するときには、実行権を与えてね。
$ ~/pysrc/twikit/venv/bin/python3 ~/pysrc/twikit/twk.py
(以下old)
$ chmod +x twk.py
(old終了)
おわりに
久しぶりに、pythonを使ったので、ネットでいちいち検索しながら作った。(^^ゞ
これくらいのスクリプトは、ネット検索しなくてもできるようになりたいけど、筆者の記憶力では無理っぽい…滝汗)