oauth2.0 代表另一个Twitter帐户使用Twitter API

vsnjm48y  于 2023-04-29  发布在  其他
关注(0)|答案(1)|浏览(219)

我如何使用twitter API代表另一个帐户(我拥有的)发布tweet?我有一个开发者帐户在我的主要twitter帐户,我创建了一个应用程序,我想用这个应用程序发布推文从不同的twitter帐户,而不是我的主要。我一直在努力理解文档,但我发现他们非常混乱,所以请不要回复类似“检查文档”的事情。先谢谢你了
我试图找到一种方法来构建一个oauth链接与范围和类似的东西,但我得到错误,即使我得到了它的工作,我不知道如何使用代码,我从auth。另外,我需要如何对API的请求进行授权,以便从其他帐户发布推文?

k5ifujac

k5ifujac1#

在这里,我正在使用Tweepy图书馆。

1.尝试引用此python代码以获取另一个帐户的访问令牌和访问密码。

# -*- coding: utf-8 -*-
# Copyright 2017 Twitter, Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0

# This script generates a user's access tokens which can be used to make requests on behalf of the user, also known as OAuth 1.0a (user context) authentication method
# Docs: https://developer.twitter.com/en/docs/authentication/oauth-1-0a/obtaining-user-access-tokens

import sys
import requests
from requests_oauthlib import OAuth1Session

#Prompt developer to enter App credentials
print("Enter the credentials for your developer App below.")
CONSUMER_KEY = input("Consumer key: ")
CONSUMER_SECRET = input("Consumer secret: ")
ACCESS_TOKEN = input("Access token: ")
TOKEN_SECRET = input("Access token secret: ")

# Request an OAuth Request Token. This is the first step of the 3-legged OAuth flow. This generates a token that you can use to request user authorization for access.
def request_token():

    oauth = OAuth1Session(CONSUMER_KEY, client_secret=CONSUMER_SECRET, callback_uri='oob')

    url = "https://api.twitter.com/oauth/request_token"

    try:
        response = oauth.fetch_request_token(url)
        resource_owner_oauth_token = response.get('oauth_token')
        resource_owner_oauth_token_secret = response.get('oauth_token_secret')
    except requests.exceptions.RequestException as e:
            print(e)
            sys.exit(120)
    
    return resource_owner_oauth_token, resource_owner_oauth_token_secret

# Use the OAuth Request Token received in the previous step to redirect the user to authorize your developer App for access.
def get_user_authorization(resource_owner_oauth_token):

    authorization_url = f"https://api.twitter.com/oauth/authorize?oauth_token={resource_owner_oauth_token}"
    authorization_pin = input(f" \n Send the following URL to the user you want to generate access tokens for. \n → {authorization_url} \n This URL will allow the user to authorize your application and generate a PIN. \n Paste PIN here: ")

    return(authorization_pin)

# Exchange the OAuth Request Token you obtained previously for the user’s Access Tokens.
def get_user_access_tokens(resource_owner_oauth_token, resource_owner_oauth_token_secret, authorization_pin):

    oauth = OAuth1Session(CONSUMER_KEY, 
                            client_secret=CONSUMER_SECRET, 
                            resource_owner_key=resource_owner_oauth_token, 
                            resource_owner_secret=resource_owner_oauth_token_secret, 
                            verifier=authorization_pin)
    
    url = "https://api.twitter.com/oauth/access_token"

    try: 
        response = oauth.fetch_access_token(url)
        access_token = response['oauth_token']
        access_token_secret = response['oauth_token_secret']
        user_id = response['user_id']
        screen_name = response['screen_name']
    except requests.exceptions.RequestException as e:
            print(e)
            sys.exit(120)

    return(access_token, access_token_secret, user_id, screen_name)

if __name__ == '__main__':
    resource_owner_oauth_token, resource_owner_oauth_token_secret = request_token()
    authorization_pin = get_user_authorization(resource_owner_oauth_token)
    access_token, access_token_secret, user_id, screen_name = get_user_access_tokens(resource_owner_oauth_token, resource_owner_oauth_token_secret, authorization_pin)
    print(f"\n User @handle: {screen_name}", f"\n User ID: {user_id}", f"\n User access token: {access_token}", f" \n User access token secret: {access_token_secret} \n")

参考:https://github.com/twitterdev/enterprise-scripts-python/blob/main/Engagement-API/generate_user_access_tokens.py

2.点击授权URL
3.将验证码粘贴到终端。

你会得到这样的最终输出。

User @handle: [YOUR_TWITTER_HANDLENAME]
User ID: [YOUR_TWITTER_USERID]
User access token: [YOUR_TWITTER_ACCESS_TOKEN]
User access token secret: [YOUR_TWITTER_ACCESS_SECRET_TOKEN]

4.然后,在python脚本中使用该访问令牌和密码从另一个帐户发送推文。请注意,需要使用相同的消费者令牌和main的秘密,以确保它的工作。

例如:

import tweepy
    
    CONSUMER_KEY = "YOUR_MAIN_ACCOUNT_CONSUMER_KEY"
    CONSUMER_SECRET = "YOUR_MAIN_ACCOUNT_CONSUMER_SECRET"

    # Comment out your main access token and secret
    # ACCESS_TOKEN = "YOUR_MAIN_TWITTER_ACCESS_TOKEN"
    # ACCESS_TOKEN_SECRET = "YOUR_MAIN_TWITTER_ACCESS_TOKEN_SECRET"
    
    # Use new token obtained from the authentication.
    ACCESS_TOKEN = "YOUR_ANOTHER_TWITTER_ACCESS_TOKEN"
    ACCESS_TOKEN_SECRET = "YOUR_ANOTHER_TWITTER_ACCESS_TOKEN_SECRET"
    
    # Authenticate to Twitter
    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
    
    # Create API object
    api = tweepy.API(auth)
    
    # Create a tweet
    api.update_status("Hello Tweepy!")

相关问题