Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/eclipse/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用Tweepy作为Facebook Messenger bot的一部分保存OAuth请求令牌时出现问题_Python_Flask_Tweepy_Facebook Messenger Bot - Fatal编程技术网

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

Python 使用Tweepy作为Facebook Messenger bot的一部分保存OAuth请求令牌时出现问题,python,flask,tweepy,facebook-messenger-bot,Python,Flask,Tweepy,Facebook Messenger Bot,我正在使用Flask开发一个Facebook messenger机器人,并希望利用Twitter API实现该机器人的一个功能。因此,我使用Tweepy来简化流程。但是,我无法让OAuth在我的程序中工作。我认为问题的根源在于请求令牌没有正确保存或接收,因为当我执行auth.get\u access\u令牌时,我会收到一个错误——“OAuth没有对象请求\u令牌”或“字符串索引必须是整数”,这取决于我保存OAuth处理程序实例的方式。有时,它也无法获取请求令牌,并且不会将链接发送回用户。我试图通

我正在使用Flask开发一个Facebook messenger机器人,并希望利用Twitter API实现该机器人的一个功能。因此,我使用Tweepy来简化流程。但是,我无法让OAuth在我的程序中工作。我认为问题的根源在于请求令牌没有正确保存或接收,因为当我执行auth.get\u access\u令牌时,我会收到一个错误——“OAuth没有对象请求\u令牌”或“字符串索引必须是整数”,这取决于我保存OAuth处理程序实例的方式。有时,它也无法获取请求令牌,并且不会将链接发送回用户。我试图通过在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
        # ...

顺便说一句:如果可以,避免使用全局变量。维护全局状态可能会很快变得非常混乱。@tekknolagi我仍在为全局变量的名称未定义的问题而挣扎,但这似乎更容易调试-尽管我知道使用它们并不理想。如果你将它传递给几个函数,你会省去很多心痛。全局变量,特别是Python中的全局变量,是很困难的。