rstudio / httpuv

HTTP and WebSocket server package for R
Other
224 stars 84 forks source link

Heartbeat in discord #381

Closed Camilo-Mora closed 3 months ago

Camilo-Mora commented 10 months ago

I am currently using your package to interface between R and Discord. Unfortunately, to keep the webhook alive, Discord requires to send a message at certain time intervals set by what they call a Heartbeat_interval. Does such a functionality exits in your package?

I worked around this problem by creating an infinite loop checking the time and sending the message at the required time interval ...while it works I wonder if you have a more efficient way to do this? I have read that several other applications require such a constant confirmation

library(websocket)
library(jsonlite)

  ws <- WebSocket$new("wss://gateway.discord.gg/?v=9&encording=json")

    Rpayload = list(
        op= 2,
        d= list(
          token= "Discord_Bot_Token",
          intents= 513,
          properties=list(
            os= "windows",
            browser= "firefox",
            device= "firefox")
        )
      ) #This is the message to establish verification. If successful Discord sends a message "OP=0"

      KeepAlive = list(op= 1,  d= 251 ) # this is the messages one needs to deliver to discord to tell it we want the connection  to be left open.

      Jsonpayload   = toJSON(Rpayload, auto_unbox = TRUE, pretty = TRUE) #Convert messages to JSON to be read by Discord.
      JsonKeepAlive = toJSON(KeepAlive, auto_unbox = TRUE, pretty = TRUE)

      ws$onOpen(function(event) {  ws$send(Jsonpayload)  }) #Stablish conformation upon opending the ws.

      ws$onMessage(function(event) { print(event$data) })

#This is the loop to send messages at  the time intervals set by the heartbite, which is about every 40 seconds.

    LastTime=Sys.time()
    Send=1
    while (Send==1){
      TimeLapse=as.numeric(Sys.time()-LastTime)

      if(TimeLapse>=40){
        ws$send(JsonKeepAlive)
        LastTime=Sys.time()
        Sys.sleep(2)
      } 
    }
jcheng5 commented 3 months ago

As of 1.6.10 you shouldn’t need to do this for WebSockets on httpuv as we send PING frames every 20(?) seconds for this reason. If you’re still seeing this can you please let us know? Thanks.