Roblox Friends API变更后Python好友请求代码失效如何修复?
问题
我尝试用Python编写Roblox好友请求工具,但在Roblox Friends API变更后代码无法正常工作。尽管请求返回200状态码,但并未成功发送好友请求,返回内容为{"success": true, "notificationMuted": true};而使用Postman发送相同请求可成功触发好友请求,返回内容为{"success": true, "isCaptchaRequired": false}。以下是我的Python代码:
import requests rcookie = "Example Cookie" # Security COOKIE Target_ID = 1 # Roblox x_csrf_res = requests.post( url = "https://groups.roblox.com/v1/groups/1/users", cookies = { ".ROBLOSECURITY": rcookie } ) if x_csrf_res.headers.get("x-csrf-token"): csrf = x_csrf_res.headers.get("x-csrf-token") test_res = requests.post( url = f"https://friends.roblox.com/v1/users/{Target_ID}/request-friendship", data = { "friendshipOriginSourceType": 0 }, headers = { "X-Csrf-Token": csrf }, cookies = { ".ROBLOSECURITY": rcookie } ) if test_res.status_code == 200: print("Send Friend!") print(test_res.text) else: print("Error!") print(test_res.status_code) print(test_res.text) else: print(f"Invalid Cookie! {x_csrf_res.status_code} {x_csrf_res.text}")
修复方案
核心问题:请求体格式不匹配
Python的requests.post使用data参数时,默认发送application/x-www-form-urlencoded格式的数据,但Roblox当前的好友API要求JSON格式的请求体。Postman默认会以JSON格式发送请求,这就是两者的关键差异。修改请求体参数
将data参数替换为json参数,让requests自动以JSON格式发送请求体:test_res = requests.post( url = f"https://friends.roblox.com/v1/users/{Target_ID}/request-friendship", json = { "friendshipOriginSourceType": 0 }, headers = { "X-Csrf-Token": csrf }, cookies = { ".ROBLOSECURITY": rcookie } )补充必要请求头(可选但推荐)
模拟真实浏览器的请求头可以降低被Roblox拦截的概率,添加User-Agent和Content-Type:headers = { "X-Csrf-Token": csrf, "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36", "Content-Type": "application/json" }优化CSRF Token获取方式
可以直接针对好友API端点发送OPTIONS请求来获取CSRF Token,比用群组接口更贴合场景:x_csrf_res = requests.options( url = f"https://friends.roblox.com/v1/users/{Target_ID}/request-friendship", cookies = { ".ROBLOSECURITY": rcookie } )
内容的提问来源于stack exchange,提问作者Shout
相关产品推荐
相关产品推荐

