使用 Tweepy 作为 Facebook Messenger 机器人的一部分保存 OAuth 请求令牌时出现问题

Issue with saving OAuth request token using Tweepy as part of Facebook Messenger bot

我正在使用 Flask 开发一个 Facebook Messenger 机器人,并想利用 Twitter API 来实现该机器人的一项功能。因此,我使用 Tweepy 来简化流程。但是,我无法在我的程序中使用 OAuth。我认为问题的根源是请求令牌未保存或未正确接收,因为当我执行 auth.get_access_token 时出现错误 - "OAuth has no object request_token" 或 "string indices must be integers" 取决于我的方式正在保存 OAuth 处理程序实例。有时,它也无法获取 request_token 并且不会将 link 发送回用户。我试图通过在我的 oauth_verification() 函数中打印出请求令牌来检查这一点,但它是空白的。我已经坚持了几个小时,任何帮助将不胜感激。我的代码如下:

PAT = '[pat here]'
auth = tweepy.OAuthHandler('[key here]', '[secret here]')
auth_req_token = ''

@app.route('/', methods=['GET'])
def handle_verification():
  print("Handling Verification.")
  if request.args.get('hub.verify_token', '') == '[verification token]':
    print("Verification successful!")
    return request.args.get('hub.challenge', '')
  else:
    print("Verification failed!")
    return 'Error, wrong validation token'

@app.route('/', methods=['POST'])
def handle_messages():
  print("Handling Messages")
  payload = request.get_data()
  print(payload)
  for sender, message in messaging_events(payload):
    print("Incoming from %s: %s" % (sender, message))
    parse_message(PAT, sender, message)
  return "ok"

def parse_message(PAT, sender, message):
  original_message = message
  message = str(message.decode('unicode_escape'))
  message = message.replace("?", "")
  if message.isdigit():
    oauth_verification(PAT, sender, original_message.decode("utf-8"))
  else:
    split_msg = message.split(" ")
    print(split_msg)
    try:
      platform = split_msg[split_msg.index("followers") - 1]
      does_location = split_msg.index("does") + 1
      have_location = split_msg.index("have")
      name = split_msg[does_location:have_location]
      name = " ".join(name)
      print("Name: " +name + " Platform: " + platform)
      init_oauth(name, PAT, sender)
    except ValueError:
      reply_error(PAT, sender)

def init_oauth(name, token, recipient):
  try:
    redirect_url = auth.get_authorization_url()
    auth_req_token = auth.request_token
    r = requests.post("https://graph.facebook.com/v2.6/me/messages",
    params={"access_token": token},
    data=json.dumps({
      "recipient": {"id": recipient},
      "message": {"text": "Please login to Twitter, and reply with your verification code " + redirect_url}
    }),
    headers={'Content-type': 'application/json'})
  except tweepy.TweepError:
      print('Error! Failed to get request token.')

def oauth_verification(token, recipient, verifier):
  auth.request_token = auth_req_token
  try:
    auth.get_access_token(verifier) # issue is here - I am able to get authentication link, but not able to get access token
    api = tweepy.API(auth)
    r = requests.post("https://graph.facebook.com/v2.6/me/messages",
    params={"access_token": token},
    data=json.dumps({
      "recipient": {"id": recipient},
      "message": {"text": "Successfully authenticated Twitter!"}
    }),
    headers={'Content-type': 'application/json'})
  except tweepy.TweepError:
      print('Error! Failed to get access token.')

由于auth_req_token是一个全局变量,需要使用global关键字来改变它在init_oauth中的值:

def init_oauth(name, token, recipient):
    global auth_req_token
    try:
        redirect_url = auth.get_authorization_url()
        auth_req_token = auth.request_token
        # ...