0
0

More than 1 year has passed since last update.

【Python覚書】twitterAPI TEST on centos stream 8(003)_twitter投稿まで

Posted at

はじめに

今月の初めの方にTwitter APIの申請したのですが、4回ほど審査を繰り返し、やっと使えるようになりました。
ただ、審査承認がおりてから、なかなか時間を作ることが出来ず放置していたので、とりあえず、APIを使った投稿だけ試してみようと思います。

tweepyのインストール

pip install tweepy

タイムラインのツイートを取得

sample_program01.py
import tweepy

# 取得したキーを格納
myAPIKey = "xxxxxxxxxxxxxxxxxxxxx"
myAPISecret = "xxxxxxxxxxxxxxxxxxxxx"
myAccessToken = "xxxxxxxxxxxxxxxxxxxxx"
myAccessSecret = "xxxxxxxxxxxxxxxxxxxxx"

# Twitter API認証
auth = tweepy.OAuthHandler(myAPIKey, myAPISecret) 
# アクセストークン設定
auth.set_access_token(myAccessToken, myAccessSecret) 
# オブジェクト設定
api = tweepy.API(auth) 

#タイムライン取得
result = api.home_timeline(count=1)

for tweet in result:
    print('='*80)
    print('ツイートID : ', tweet.id)
    print('ツイート時間 : ', tweet.created_at)
    print('ツイート本文 : ', tweet.text)
    print('ユーザ名 : ', tweet.user.name) 
    print('スクリーンネーム : ', tweet.user.screen_name) 
    print('フォロー数 : ', tweet.user.friends_count) 
    print('フォロワー数 : ', tweet.user.followers_count) 
    print('概要 : ', tweet.user.description) 
    print('='*80)
================================================================================
ツイートID :  1476809584132395008
ツイート時間 :  2021-12-31 06:56:57+00:00
ツイート本文 :  記事を投稿しました! 【Python覚書】selenium on raspberry pi(002) on #Qiita https://t.co/Zb1ftBCDHI
ユーザ名 :  おーちゃん
スクリーンネーム :  384XZdN05sRFoqh
フォロー数 :  0
フォロワー数 :  0
概要 :  特に好きな作家:東野圭吾、京極夏彦
特に好きな本:悪意、女郎蜘蛛の理
趣味:パソコン、読書、動画視聴

IT技術、株、読書感想について、まったりつぶやくつもりで始めたけど、特に考えなしに投稿してます。
================================================================================

おー。。。
キチンと取得できている事に感動。

続けてTwitter投稿(失敗)

sample_program02.py
# 投稿テスト
api.update_status("投稿テスト")
Traceback (most recent call last):
  File "studyData.py", line 17, in <module>
    api.update_status("投稿テスト")
  File "/usr/local/lib/python3.8/site-packages/tweepy/api.py", line 46, in wrapper
    return method(*args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/tweepy/api.py", line 1121, in update_status
    return self.request(
  File "/usr/local/lib/python3.8/site-packages/tweepy/api.py", line 257, in request
    raise Unauthorized(resp)
tweepy.errors.Unauthorized: 401 Unauthorized

権限不足で失敗しているようです。

WS671636.JPG

twitter Developperのダッシュボードから権限付与

WS671637.JPG

アクセストークンの再発行

WS671638.JPG

Callback URIとWebサイトはまだ設定していないので、「example.com」のものを利用させていただく。

再実行して成功!

再度、下記のpythonを実行

sample_program03.py
# 投稿テスト
api.update_status("投稿テスト")

WS671639.JPG

ようやく、スタートラインに立てたというところですね。
これから、調べて活用させていただきます。

0
0
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
0
0