Сохранение чата twitch.tv

  1. use "std"
  2. use "math"
  3. use "date"
  4. use "http"
  5. use "json"
  6. use "types"
  7. use "files"
  8. use "functional"
  9.  
  10. DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'"
  11.  
  12. vod = ""
  13. if (length(vod) == 0) {
  14.   use "canvas"
  15.   vod = prompt("Twitch VOD id")
  16. }
  17. messages = []
  18. chunks = []
  19.  
  20. thread(::http, "https://api.twitch.tv/kraken/videos/v" + vod,
  21.     combine(::jsondecode, ::processVodInfo))
  22.  
  23. def processVodInfo(vodInfo) {
  24.   if (arrayKeyExists("error", vodInfo)) {
  25.     println "Error: " + vodInfo.message
  26.     return 0
  27.   }
  28.  
  29.   recordDate = newDate(DATE_PATTERN, vodInfo.recorded_at)
  30.   startTime = toTimestamp(recordDate) / 1000
  31.   startTime += (3 * 60 * 60)
  32.   endTime = long(startTime + ceil(vodInfo.length / 30.0) * 30)
  33.   maxIterations = (endTime - startTime) / 30
  34.  
  35.   for i = 0, i < maxIterations, i++ {
  36.     println sprintf("%d / %d", i + 1, maxIterations)
  37.  
  38.     timestamp = startTime + i * 30
  39.     url = "http://rechat.twitch.tv/rechat-messages?start=" + timestamp + "&video_id=v" + vod
  40.     chunksString = sync(def(ret) = http(url, ret))
  41.     chunksObject = jsondecode(chunksString)
  42.  
  43.     foreach(chunksObject.data, ::processChatChunk)
  44.   }
  45.  
  46.   saveResults(vodInfo)
  47. }
  48.  
  49. def processChatChunk(chunk) {
  50.   attr = chunk.attributes
  51.   formattedDate = formatDate(newDate(attr.timestamp))
  52.  
  53.   chunks = chunks :: chunk
  54.   messages ::= sprintf("%s (%s)\n%s",
  55.     attr.tags["display-name"], formattedDate, attr.message)
  56. }
  57.  
  58. def saveResults(vodInfo) {
  59.   result = vodInfo.channel.display_name + ": " + vodInfo.title + "\n";
  60.   result += formatDate(newDate(DATE_PATTERN, vodInfo.recorded_at)) + "\n"
  61.   result += vodInfo.url + "\n\n";
  62.   result += join(messages, "\n\n=====\n\n")
  63.   saveFile(vod + "_chat.txt", result)
  64.   saveFile(vod + "_chat.json", jsonencode(chunks))
  65. }
  66.  
  67. def saveFile(filename, content) {
  68.   f = fopen(filename, "w")
  69.   writeText(f, content)
  70.   flush(f)
  71.   fclose(f)
  72. }
Вводим vod id (восьмизначное число, например 67509345) и получаем чат твича в текстовом файле и в json
Онлайн версия

Реклама

Мы в соцсетях

tw tg yt gt