Advertisement
OverloadedOrama

Making a Discord Bot with Godot (Part One)

Jun 30th, 2019
542
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. extends HTTPRequest
  2.  
  3. var token := "yourtokenhere" #make sure to actually replace this with your token!
  4. var client : WebSocketClient
  5. var heartbeat_interval : float
  6. var last_sequence : float
  7.  
  8. func _ready() -> void:
  9. client = WebSocketClient.new()
  10. client.connect_to_url("wss://gateway.discord.gg/?v=6&encoding=json")
  11. client.connect("connection_established", self, "_connection_established")
  12. client.connect("data_received", self, "_data_received")
  13.  
  14. func _process(delta : float) -> void:
  15. #check if the client is not disconnected, there's no point to poll it if it is
  16. if client.get_connection_status() != NetworkedMultiplayerPeer.CONNECTION_DISCONNECTED:
  17. client.poll()
  18.  
  19. func _connection_established(protocol : String) -> void:
  20. print("We are connected!")
  21.  
  22. func _data_received() -> void:
  23. var packet := client.get_peer(1).get_packet()
  24. var data := packet.get_string_from_utf8()
  25. var json_parsed := JSON.parse(data)
  26. var dict : Dictionary = json_parsed.result
  27. var op = str(dict["op"]) #convert it to string for easier checking
  28.  
  29. match op:
  30. "0": #Opcode 0 (Events)
  31. print(dict["t"])
  32. last_sequence = dict["s"]
  33. "10": #Opcode 10 Hello
  34. #Set our timer
  35. heartbeat_interval = dict["d"]["heartbeat_interval"]
  36. $Timer.wait_time = heartbeat_interval / 1000
  37. $Timer.start()
  38. #Send Opcode 2 Identify to the Gateway
  39. var d = {
  40. "op" : 2,
  41. "d" : { "token": token, "properties": {} }
  42. }
  43. send_dictionary_as_packet(d)
  44. "11": #Opcode 11 Heartbeat ACK
  45. print("We've received a Heartbeat ACK from the gateway.")
  46.  
  47.  
  48. func _on_Timer_timeout() -> void: #Send Opcode 1 Heartbeat payloads every heartbeat_interval
  49. var d = {"op" : 1, "d" : last_sequence}
  50. send_dictionary_as_packet(d)
  51. print("We've send a Heartbeat to the gateway.")
  52.  
  53. func send_dictionary_as_packet(d : Dictionary) -> void:
  54. var query = to_json(d)
  55. client.get_peer(1).put_packet(query.to_utf8())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement