10
13

More than 3 years have passed since last update.

Python / TweepyでOAuth認証してツイートする

Last updated at Posted at 2020-12-05

・まず、Twitter developer登録が必要であるが、このサイトを参考にした 
https://pocco.net/twitter-developer/
・developer登録をしたら、Twitter developer portalで、PROJECT APPの設定ボタンを押す(以下の設定ボタン)

スクリーンショット 2020-12-04 0.01.41.png

次に、Authentication settingsのEditボタンを押し、CALLBACK URLSにコールバックするURLを設定し(以下では、htt@://127.0.01:5000/authとした)、WEBSITE URLに、自身のURLを設定する

スクリーンショット 2020-12-04 0.04.15.png

上記設定を保存したら、以下のコードを作成
(実行イメージ)
①index.htmlを表示
②"twitter"のリンクをクリックすると、twitterの認証画面に飛ぶ
③認証すると、コールバックされて、index0.htmlが表示され、
④同時にtwitterに"テスト"と、ツイートされる

ninshou.py
import tweepy
from flask import Flask,request,render_template



#APIkey
CK=""
#API key secret
CS=""
#Access token
AT=""
#Access token secret
AS=""


# tweepy でアプリのOAuth認証を行う
#認証後に飛ばすサイトをコールバックという、OAurhHandlerの第3引数にコールバックするurlを設定
#コールバックするurlは、twitter_developersにあらかじめ登録しておく必要あり
callback_url="http://127.0.0.1:5000/auth"
auth = tweepy.OAuthHandler(CK, CS,callback_url)
#ユーザーが認証のurlをredirect_urlに入れる
redirect_url = auth.get_authorization_url()




app = Flask(__name__)

@app.route('/')
def main():
    #index.htmlにリンクを貼り、リンク先にredirect_urlを設定する
    return render_template('index.html',redirect_url=redirect_url)

#認証後にコールバックされるhttp://127.0.0.1:5000/authのhtmlの挙動を設定する
@app.route('/auth')
def main2():
    #http://127.0.0.1:5000/authには、後ろにoauth_token と oauth_verifierがくっついて
    #返されるので(URLパラメータ)以下の処理をする
    #URLパラメータは request.args で利用できる。以下の例では、
    #http://127.0.0.1:5000/auth?oauth_token= の"="以降を取得できる
    #defaultは、auth?以降がない場合の値を返すもの(例ではブランクを返す)
    oauth_token = request.args.get('oauth_token',default=' ',type=str)
    oauth_verifier = request.args.get('oauth_verifier',default=' ',type=str)
    #URLから oauth_token を取り出して、auth.request_token[‘oauth_token’] にセット
    auth.request_token['oauth_token'] = oauth_token
    #URLから、oauth_verifierを取り出して、oauth_token_secretにセット
    auth.request_token['oauth_token_secret'] = oauth_verifier
    #ここの処理は調べきれてません
    auth.get_access_token(oauth_verifier)
    #アクセストークンと、アクセルトークンシークレットをセット(通常のtweepyでツイートする処理と同様)
    auth.set_access_token(auth.access_token,auth.access_token_secret)
    api = tweepy.API(auth)
    api.update_status("テスト")

    return render_template('index0.html')


if __name__ == '__main__':
    app.run(debug=True)
index.html
{% extends 'layout.html' %}
{% block content %}
  <head>
    <title>test</title>
  </head>

  <body>
    <div class="container">
        <h1>Hello Jinja2</h1>
      <h1>テスト1</h1>
      <p><a href={{redirect_url}}>twitter</a>
  </div>
  </body>
{% endblock %}
layout.html
<!DOCTYPE html>
<html lang='ja'>
  <head>
      <!-- Required meta tags -->
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <style>body{padding:20px;}</style>
  </head>
  <body>
      {% block content %}
      {% endblock %}
  </body>
</html>
index0.html
{% extends 'layout.html' %}
{% block content %}
  <head>
    <title>m_league_ouen</title>
  </head>

  <body>
      <h1>テスト2</h1>
  </body>

{% endblock %}

認証はsessionを用いることもできる
sessionを用いると、値を関数外でも保持できる(例では関数外では使用していない)
以下は認証をsessionを使った別のやり方

ninshou2.py
import tweepy
from flask import Flask,request,render_template,session
import os


#APIkey
CK=""
#API key secret
CS=""
#Access token
AT=""
#Access token secret
AS=""


# tweepy でアプリのOAuth認証を行う
#認証後に飛ばすサイトをコールバックという、OAurhHandlerの第3引数にコールバックするurlを設定
callback_url="http://127.0.0.1:5000/auth"
auth = tweepy.OAuthHandler(CK, CS,callback_url)
#認証後にコールバック関数のurlの後ろにoauth_token と oauth_verifierがくっついて返されるurlを
#redirect_urlに入れる
redirect_url = auth.get_authorization_url()




app = Flask(__name__)

#sessionを使うために乱数を設定
app.secret_key = os.urandom(24)


@app.route('/')
def main():
    return render_template('index.html',redirect_url=redirect_url)

@app.route('/auth')
def main2():
    #request_tokenの値をsessionに保存
    session['request_token'] = auth.request_token
    #sessionはオブジェクトであり、sessionから、request_tokenの値を取得
    token = session.get('request_token')
    #sessionのrequest_tokenの値を削除する(該当なければNoneを返すようにしておく)
    session.pop('request_token',None)
    auth.request_token = token
    #URLから、oauth_verifierを取り出して、oauth_token_secretにセット
    oauth_verifier = request.args.get('oauth_verifier',default=' ',type=str)
    auth.get_access_token(oauth_verifier)
    #アクセストークンと、アクセルトークンシークレットをセット(通常のtweepyでツイートする処理と同様)
    auth.set_access_token(auth.access_token,auth.access_token_secret)
    api = tweepy.API(auth)
    api.update_status("テスト")


    return render_template('index0.html')


if __name__ == '__main__':
    app.run(debug=True)
10
13
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
10
13