小ネタ
HttpClient
このへんはあまり関係ないのでよしなに
val client = HttpClient(CIO) { defaultRequest { url { protocol = URLProtocol.HTTPS host = "api.twitter.com" } header("Authorization", "Bearer $token") } Json { serializer = KotlinxSerializer(json) } }
Add rules
取得する Tweets の rules を POST する
返り値は String でも HttpResponse でも任意に定義した Response でも何でもいいですが、
kotlinx.serialization でそのまま decode する場合は、errors など key がない場合があるので ignoreUnknownKeys = true を指定しておくと良いです
val response = client.post<String> { url { encodedPath = "2/tweets/search/stream/rules" } body = StreamRulesRequest(rules) }
Get tweets
Tweets を real-time に取得する
Ktor Client の doc に書いてある通り、HttpStatement を使用します。
client.get<HttpStatement> { url { encodedPath = "2/tweets/search/stream" } }.execute { response -> val channel = response.receive<ByteReadChannel>() do { val tweet = channel.readUTF8Line() ?: break } while (tweet.isNotBlank()) }
Flow とかで emit すれば扱いやすくなると思います。
もう少し詳しく見たければこちらを
info-provision-bot/TwitterClient.kt at main · CORDEA/info-provision-bot · GitHub