【已解】推特api报错453,You currently have access to a subset of Twitter API v2 endpoints and limited v1.1...

摘要

当时使用免费推特api报错:
{‘errors’: [{‘message’: ‘You currently have access to a subset of Twitter API v2 endpoints and limited v1.1 endpoints (e.g. media post, oauth) only. If you need access to this endpoint, you may need a different access level. You can learn more here: https://developer.twitter.com/en/portal/product’, ‘code’: 453}]}

我傻傻的以为,需要购买基本版推特api,才能够访问,购买了基础版api后,结果新的api访问依然出错,还是无权限访问,显示1.1limited
403错误
但是仔细看了开发者面板的描述之后,觉得应该没错,能够访问这些结点,只是方式错了

基础版接口

基础版接口

免费版接口,仅提供两个接口,基本上只能测试玩玩,做不了实际开发,听说2月份削砍的,分了个basic出来

在这里插入图片描述
api对比

出错代码

import tweepy
# 替换为你自己的API密钥和令牌
consumer_key = 'xxxx'
consumer_secret = 'xxxx'
access_token = 'xxxx'
access_token_secret = 'xxxx'

# 使用API密钥和令牌进行身份验证
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

# 创建API对象
api = tweepy.API(auth)

username = 'target_username'

# 获取用户对象
user = api.get_user(screen_name=username)

# 打印用户信息
print("User ID:", user.id)
print("Screen Name:", user.screen_name)
print("Name:", user.name)

# 获取用户的最新推文
tweets = api.user_timeline(screen_name=username, count=10)
print("\nRecent Tweets:")
for tweet in tweets:
    print(f"{tweet.created_at} - {tweet.text}\n")

解决方法

按道理OAuth1.0验证可以通过,但是被403禁止拦截了,OAuth2.0又有点麻烦,所以想绕过这两个方式。

最后花了我一天一夜时间,研究出来了,根据api文档描述

官方文档描述
构造请求应该为:

GET https://api.twitter.com/1.1/favorites/list.json?count=200&screen_name=twitterdev

随即会返回一个json内容块,读取json即可,因此,我们可以构造一个例子:

# 设置 API 请求参数,注意参数之间没有空格,不然报错
    params = {
        'user.fields': 'name,public_metrics,description,created_at',
    }

    # 设置请求头,添加 Bearer 令牌
    headers = {
        'Authorization': f'Bearer {beartoken}',
        'Content-Type': 'application/json',
    }

这里的params参数可以在开发者文档(https://developer.twitter.com/en/docs/twitter-api/users/lookup/quick-start/user-lookup)中查阅:
开发者文档

随后发送用re发送请求,这里挑选了一个查找用户的接口,按照文档构造请求:

    response = requests.get(f'https://api.twitter.com/2/users/by/username/{username}', params=params, headers=headers)

得到的response就是文档中提到的json内容:

# 处理响应
    if response.status_code == 200:
        json_response = response.json()
        t = json_response["data"]['created_at']
        json_response["data"]['created_at'] = convert_utc_to_china(t, format="%Y年%m月%d日")
        print(json_response)
    else:
        raise Exception(f"Request returned an error: {response.status_code} {response.text}")

最后写个调用,测试一下:

成功

因为有人还是不会写re访问网页,这里贴个demo函数,试下调用

def remove_links(tweet_text):
    # 使用正则表达式匹配链接的模式
    link_pattern = r'https?://\S+|www\.\S+'

    # 使用 sub 方法替换链接为空字符串
    cleaned_text = re.sub(link_pattern, '', tweet_text)
    cleaned_text = cleaned_text.replace('\n\n', '\n')

    return cleaned_text


def get_tweet_info(tweet_url, beartoken=beartoken):
    # 从推文链接中截取推文ID
    tweet_id = tweet_url.split('/')[-1].split('?')[0]

    # 设置 API 请求参数
    params = {
        'ids': tweet_id,
        # 'tweet.fields': 'created_at,public_metrics,text.extended',
        'tweet.fields': 'created_at,note_tweet,public_metrics',
        # [attachments,author_id,context_annotations,conversation_id,created_at,edit_controls,edit_history_tweet_ids,
        # entities,geo,id,in_reply_to_user_id,lang,non_public_metrics,note_tweet,organic_metrics,possibly_sensitive,
        # promoted_metrics,public_metrics,referenced_tweets,reply_settings,source,text,withheld]
    }

    # 设置请求头,添加 Bearer 令牌
    headers = {
        'Authorization': f'Bearer {beartoken}',
        'Content-Type': 'application/json',
    }

    # 发送请求
    response = requests.get('https://api.twitter.com/2/tweets', params=params, headers=headers)

    # 处理响应
    if response.status_code == 200:
        json_response = response.json()
        # 将Unicode编码转换成中文编码
        # print(json.dumps(json_response, indent=4))
        text = json_response['data'][0]['text']
        if 'note_tweet' in json_response['data'][0].keys():
            # print(json_response['data'][0].keys())
            note_tweet = json_response['data'][0]['note_tweet']['text']
            text = note_tweet
        else:
            note_tweet = json_response['data'][0]['text']
        text = remove_links(text)
        json_response['data'][0]['text'] = text
        # tweet_text = json.loads(f'"{text}"')
        t = json_response['data'][0]['created_at']
        china_t = convert_utc_to_china(t)
        json_response['data'][0]['created_at'] = china_t
        return json_response
    else:
        raise Exception(f"Request returned an error: {response.status_code} {response.text}")

持续更新中。。。。。前人踩坑,后人享福,希望你早点看到。

2023年12月8日更新,api-401报错-解决办法

401报错
重新更新berar-token,修改进去就行了,我个人认为应该是请求次数过多,导致把个人应用的秘钥暂时禁用了。

2023年12月9日更新,text不返回长文-解决办法

添加note_tweet参数,可以返回长文本,text做不到返回长文本

    # 设置 API 请求参数
    params = {
        'ids': tweet_id,
        'tweet.fields': 'created_at,public_metrics,note_tweet',
        # [attachments,author_id,context_annotations,conversation_id,created_at,edit_controls,edit_history_tweet_ids,
        # entities,geo,id,in_reply_to_user_id,lang,non_public_metrics,note_tweet,organic_metrics,possibly_sensitive,
        # promoted_metrics,public_metrics,referenced_tweets,reply_settings,source,text,withheld]
    }

2023年12月11日更新,错误443

请求api次数过多,等一会再发送请求就可以了。

解决办法作api次数限制,基础版本限制25次每分钟,如果4个人同时使用程序,限制5次每分钟

# 设置点击时间记录
CLICK_TIMES = []
CLICK_LIMIT = CFG['CLICK_LIMIT']
# 请求函数。。。。。
global CLICK_TIMES
        time_now = datetime.now()
        if len(CLICK_TIMES) == CLICK_LIMIT:
            # 循环更新队列, 只储存一分钟之内的5次请求时间,其他时间去掉
            for t in CLICK_TIMES:
                if minutes_1(CLICK_TIMES[-1], t) or minutes_1(time_now, t):
                    CLICK_TIMES.remove(t)
                else:
                    break
        if len(CLICK_TIMES) < CLICK_LIMIT:
            CLICK_TIMES.append(time_now)
            print(f"get_limit = {CLICK_TIMES}")
        else:
            days, hours, minutes, seconds = calculate_time_click(time_now, CLICK_TIMES[0])
            # 当点击的5次请求都在一分钟之内,再次点击,此时报错
            messagebox.showerror("错误!", f"点击次数过多, 请{60 - seconds}秒后重试")
            return

2024年1月3日更新,api报错403错误

在这里插入图片描述
创建
在这里插入图片描述

重新创建项目,项目被自动支付失败关闭。重新创建项目和子app

  • 42
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
Pro REST API Development with Node.js is your guide to managing and understanding the full capabilities of successful REST development. API design is a hot topic in the programming world, but not many resources exist for developers to really understand how you can leverage the advantages. This book will provide a brief background on REST and the tools it provides (well known and not so well known). Understand how there is more to REST than just JSON and URLs. You will then cover and compare the maintained modules currently available in the npm community, including Express, Restify, Vatican, and Swagger. Finally you will code an example API from start to finish, using a subset of the tools covered. The Node community is currently flooded with modules; some of them are published once and never updated again - cluttering the entire universe of packages. Pro REST API Development with Node.js shines light into that black hole of modules for the developers trying to create an API. Understand REST API development with Node.js using this book today. What you’ll learn What REST really is and how you can use it to your advantage. How to use a variety of modules including JSON/Hal, Express, Restify, Vatican, and Swagger. How to build an example RESTful API from start to finish. How to troubleshoot any problems and move on with your API. Who this book is for This is book is designed for any Node.js developer who wants to fully understand REST API development. So often, the true capabilities of this method are not fully understood. This book will shed light on all aspects and make REST API development easy. Table of Contents Chapter 1: Rest 101 Chapter 2: API Design Best Practices Chapter 3: Node.js and REST Chapter 4: Architecting a REST API Chapter 5: Working with Modules Chapter 6: Planning Your REST API Chapter 7: Developing Your REST API Chapter 8: Troubleshooting

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值