【发布时间】:2016-11-24 09:28:33
【问题描述】:
我正在尝试使用 since_id 来获取使用 twitter 搜索 api 的推文。下面是我的代码,这里我正在创建一个查询对象的映射,并且因为 id.我将自 id 默认为 0,我的目标是每次运行查询时更新自 id。这样当我下次运行查询时,它不会得到相同的推文,应该从最后一条推文开始。
import java.io.{PrintWriter, StringWriter}
import java.util.Properties
import com.google.common.io.Resources
import twitter4j._
import scala.collection.JavaConversions._
// reference: http://bcomposes.com/2013/02/09/using-twitter4j-with-scala-to-access-streaming-tweets/
object Util {
val props = Resources.getResource("twitter4j.props").openStream()
val properties = new Properties()
properties.load(props)
val config = new twitter4j.conf.ConfigurationBuilder()
.setDebugEnabled(properties.getProperty("debug").toBoolean)
.setOAuthConsumerKey(properties.getProperty("consumerKey"))
.setOAuthConsumerSecret(properties.getProperty("consumerSecret"))
.setOAuthAccessToken(properties.getProperty("accessToken"))
.setOAuthAccessTokenSecret(properties.getProperty("accessTokenSecret"))
val tempKeys =List("Yahoo","Bloomberg","Messi", "JPM Chase","Facebook")
val sinceIDmap : scala.collection.mutable.Map[String, Long] = collection.mutable.Map(tempKeys map { ix => s"$ix" -> 0.toLong } : _*)
//val tweetsMap: scala.collection.mutable.Map[String, String]
val configBuild = (config.build())
val MAX_TWEET=100
getTweets()
def getTweets(): Unit ={
sinceIDmap.keys.foreach((TickerId) => getTweets(TickerId))
}
def getTweets(TickerId: String): scala.collection.mutable.Map[String, scala.collection.mutable.Buffer[String]] = {
println("Search key is:"+TickerId)
var tweets = scala.collection.mutable.Map[String, scala.collection.mutable.Buffer[String]]()
try {
val twitter: Twitter = new TwitterFactory(configBuild).getInstance
val query = new Query(TickerId)
query.setSinceId(sinceIDmap.get(TickerId).get)
query.setLang("en")
query.setCount(MAX_TWEET)
val result = twitter.search(query)
tweets += ( TickerId -> result.getTweets().map(_.getText))
//sinceIDmap(TickerId)=result.getSinceId
println("-----------Since id is :"+result.getSinceId )
//println(tweets)
}
catch {
case te: TwitterException =>
println("Failed to search tweets: " + te.getMessage)
}
tweets
}
}
object StatusStreamer {
def main(args: Array[String]) {
Util
}
}
输出:
Search key is:Yahoo
log4j:WARN No appenders could be found for logger (twitter4j.HttpClientImpl).
log4j:WARN Please initialize the log4j system properly.
-----------Since id is :0
Search key is:JPM Chase
-----------Since id is :0
Search key is:Facebook
-----------Since id is :0
Search key is:Bloomberg
-----------Since id is :0
Search key is:Messi
-----------Since id is :0
问题是当我在运行查询后尝试打印自 id 时,它给出的值与我最初设置的值相同。有人可以指出我在这里做错了什么吗?或者如果我的方法是错误的,如果有人知道可以在这里工作,可以分享任何其他方法。
谢谢
【问题讨论】: