You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Go调用Twitter API v2发推文?遇403权限问题求解决

问题解决思路与Go语言实现方案

问题根源

你当前使用的github.com/dghubble/go-twitter库调用的是Twitter API v1.1的statuses/update接口,而免费开发者账号没有该接口的访问权限,仅能使用API v2的核心推文创建接口。

具体解决步骤

1. 更换为支持API v2的Go库

放弃原v1.1的库,使用专门适配Twitter API v2的github.com/g8rswimmer/go-twitter/v2库,执行安装命令:

go get github.com/g8rswimmer/go-twitter/v2

2. 修改代码适配v2接口

以下是调整后的完整示例代码:

package main

import (
	"context"
	"log"
	"os"

	"github.com/joho/godotenv"
	twitter "github.com/g8rswimmer/go-twitter/v2"
)

func init() {
	if err := godotenv.Load(); err != nil {
		log.Fatal("Error loading .env file")
	}
}

func main() {
	// 从环境变量读取凭证
	apiKey := os.Getenv("CONSUMER_KEY")
	apiSecret := os.Getenv("CONSUMER_SECRET")
	accessToken := os.Getenv("ACCESS_TOKEN")
	accessTokenSecret := os.Getenv("ACCESS_TOKEN_SECRET")

	// 创建v2客户端,使用OAuth1.0a凭证(发布推文需要)
	client := twitter.NewClient(apiKey, apiSecret, accessToken, accessTokenSecret)

	// 构建推文请求
	req := twitter.CreateTweetRequest{
		Text: "Hello World from Twitter API v2",
	}

	// 调用v2接口发布推文
	resp, err := client.CreateTweet(context.Background(), req)
	if err != nil {
		log.Fatalf("发布推文失败: %v", err)
	}

	log.Printf("推文发布成功,ID: %s", resp.Data.ID)
}

3. 确认账号权限与凭证

  • 登录开发者平台,进入你的项目,确保已启用Tweet read和Tweet write权限
  • 权限修改后,重新生成并更新环境变量中的访问令牌(包括AccessToken、AccessTokenSecret)
  • 注意:v2接口发布推文需要使用OAuth1.0a凭证,Bearer Token仅用于只读操作

内容的提问来源于stack exchange,提问作者Linus Tan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 13:21:25