前提・実現したいこと
Jsonモジュールとtweepyを使い、読み込みエラーが出た場合はログイン認証させ、アクセストークンとアクセストークンシークレットを保存し、再読み込みしてキーをセットし、アカウント名を出力させる。
発生している問題・エラーメッセージ
Traceback (most recent call last): File "login.py", line 52, in <module> me = api.me() tweepy.error.TweepError: Token request failed with code 401, response was '{"err ors":[{"code":32,"message":"Could not authenticate you."}]}'.
下記コードにtry文が三つあり、三つともtryの方向で処理が出来ましたが、me = api.me()でエラーが出ます。
該当のソースコード
Python
import sys import os import tweepy import pathlib import json import requests try: print("try1") #load api key json_open = open('apikeys.json', 'r') json_load = json.load(json_open) consumer_key = json_load['api']['api_key'] consumer_secret = json_load['api']['api_key_secret'] except Exception: #set api key api_key_input = input("Enter your api key:") api_key_secret_input = input("Enter your api key secret:") path = './apikeys.json' f = open(path, 'w') #Jsonファイルを生成。 f.write('{\n') f.write(' "api":{\n') f.write(f' "api_key":"{api_key_input}",\n') f.write(f' "api_key_secret":"{api_key_secret_input}"\n') f.write(' }\n') f.write('}') try: print("try2") json_open = open('settings.json', 'r') json_load = json.load(json_open) access_token = json_load['auth']['access_token'] access_token_secret = json_load['auth']['access_token_secret'] auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token,access_token_secret) api = tweepy.API( auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True ) print("api") me = api.me() print(f'ログインが完了しました。:{me.user_name}') except: # get access token from the user and redirect to auth URL auth_url = auth.get_authorization_url() print('Authorization URL:' + auth_url) # ask user to verify the PIN generated in broswer verifier = input('PIN:').strip() auth.get_access_token(verifier) path = './settings.json' f = open(path, 'w') #Jsonファイルを生成。 f.write('{\n') f.write(' "auth":{\n') f.write(f' "access_token":"{auth.access_token}",\n') f.write(f' "access_token_secret":"{auth.access_token_secret}"\n') f.write(' }\n') f.write('}') try: print("try3") json_open = open('settings.json', 'r') json_load = json.load(json_open) access_token = json_load['authtoken']['access_token'] access_token_secret = json_load['authtoken']['access_token_secret'] print(f"{access_token}\n{access_token_secret}") except Exception: pass # authenticate and retrieve user name auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token,access_token_secret) api = tweepy.API( auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True ) print("api") me = api.me() print(f'ログインが完了しました。:{me.user_name}')
試したこと
Jsonファイルの修正やtry,except文の見直し。
補足情報(FW/ツールのバージョンなど)
Python 3.8.2
Windows 10 Home
Visual Studio Code
まだ回答がついていません
会員登録して回答してみよう