首页 > 解决方案 > go-twitter API 提取视频 URL

问题描述

这里的最终目标是:

  1. 用户在一些推文的回复中提到了我的应用在推特上的句柄
  2. 我的脚本获取原始推文的 ID
  3. 接收其 json 响应并从中提取实际的视频 URL。

我的问题:

我能够达到可以打印 tweet.Text 的程度,但除此之外的任何内容都会引发与内存地址相关的错误。我是 Go 新手,以前没有真正使用过指针,所以我猜问题出在某个地方。

我的代码(忽略其中的注释,我按原样粘贴,以便您可以轻松参考错误)->

// ExtendedEntity is a []MediEntity, now we need to figure out how to access the details in it
package main

import (
    "fmt"

    "github.com/dghubble/go-twitter/twitter"
    "github.com/dghubble/oauth1"
)

func main() {
    config := oauth1.NewConfig("asd", "asd")
    token := oauth1.NewToken("asd-V65ynQCN5vxWi72MGqfwF7WqYqdUZh", "asd")
    httpClient := config.Client(oauth1.NoContext, token)
    client := twitter.NewClient(httpClient)

    params := &twitter.StreamFilterParams{
        Track: []string{"@bulundindia1337"},
        // StallWarnings: twitter.Bool(true),
    }

    stream, _ := client.Streams.Filter(params)
    // fmt.Printf("%T", stream)
    // v := <-stream.Messages
    // fmt.Println(v)

    demux := twitter.NewSwitchDemux()
    demux.Tweet = func(tweet *twitter.Tweet) {
        fmt.Println("text > ", tweet.Text)
        fmt.Println("tweet ID > ", tweet.ID)
        parentTweetID := tweet.InReplyToStatusID
        fmt.Println("Parent tweet id > ", parentTweetID)
        a := parseURL(parentTweetID, client)
        fmt.Println(a)
        // fmt.Println(parentTweet.ExtendedTweet.ExtendedEntities)
        //fmt.Println(parentTweet.Text)
        //fmt.Println(parentTweet.ExtendedEntities)
    }

    for message := range stream.Messages {
        demux.Handle(message)
    }
}

func parseURL(tweetID int64, c *twitter.Client) twitter.MediaEntity {
    status, _, err := c.Statuses.Show(tweetID, nil)
    if err != nil {
        fmt.Println(err)
    }
    return status.ExtendedEntities.Media[0]
}

我运行流时的输出->

nish@b0x:~/Documents/go/twitube$ go run main.go 
text >  @thevirdas @netflix_in @TheWeirdass @EmmayEntertain @ApplauseSocial @Nikgonsalves @nikkhiladvani @nairsameer… t.co/LZ5iKKU8Ku
tweet ID >  1247376867046424578
Parent tweet id >  1246007863895449600
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x8 pc=0x669a8a]

goroutine 1 [running]:
main.parseURL(0x114ab58cf2d4e000, 0xc0000ef700, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, ...)
        /home/nish/Documents/go/twitube/main.go:50 +0xda
main.main.func1(0xc00009e000)
        /home/nish/Documents/go/twitube/main.go:33 +0x243
github.com/dghubble/go-twitter/twitter.SwitchDemux.Handle(0x7119e8, 0xc00005af00, 0x7119f8, 0x711a00, 0x711a08, 0x711a10, 0x711a18, 0x711a20, 0x711a28, 0x7119c8, ...)
        /home/nish/Documents/go/src/github.com/dghubble/go-twitter/twitter/demux.go:55 +0x22e
main.main()
        /home/nish/Documents/go/twitube/main.go:41 +0x265
exit status 2

go-twitter 包 URL -> https://godoc.org/github.com/dghubble/go-twitter/twitter#ExtendedEntity

如果您能指出我正确的方向,我将不胜感激!

标签: gotwitter

解决方案


推荐阅读