Compare commits
No commits in common. "master" and "3.x" have entirely different histories.
3
.gitignore
vendored
3
.gitignore
vendored
@ -1,6 +1,3 @@
|
||||
# Example auth file
|
||||
auth.txt
|
||||
|
||||
# Godot 4+ specific ignores
|
||||
.godot/
|
||||
|
||||
|
5
Button.gd
Normal file
5
Button.gd
Normal file
@ -0,0 +1,5 @@
|
||||
extends Button
|
||||
|
||||
func _pressed():
|
||||
$"../../../Gift".chat($"../LineEdit".text)
|
||||
$"../LineEdit".text = ""
|
40
ChatContainer.gd
Normal file
40
ChatContainer.gd
Normal file
@ -0,0 +1,40 @@
|
||||
extends VBoxContainer
|
||||
|
||||
func put_chat(senderdata : SenderData, msg : String):
|
||||
var msgnode : Control = preload("res://ChatMessage.tscn").instance()
|
||||
var time = OS.get_time()
|
||||
var badges : String = ""
|
||||
if ($"../Gift".image_cache):
|
||||
for badge in senderdata.tags["badges"].split(",", false):
|
||||
badges += "[img=center]" + $"../Gift".image_cache.get_badge(badge, senderdata.tags["room-id"]).resource_path + "[/img] "
|
||||
var locations : Array = []
|
||||
for emote in senderdata.tags["emotes"].split("/", false):
|
||||
var data : Array = emote.split(":")
|
||||
for d in data[1].split(","):
|
||||
var start_end = d.split("-")
|
||||
locations.append(EmoteLocation.new(data[0], int(start_end[0]), int(start_end[1])))
|
||||
locations.sort_custom(EmoteLocation, "smaller")
|
||||
var offset = 0
|
||||
for loc in locations:
|
||||
var emote_string = "[img=center]" + $"../Gift".image_cache.get_emote(loc.id).resource_path +"[/img]"
|
||||
msg = msg.substr(0, loc.start + offset) + emote_string + msg.substr(loc.end + offset + 1)
|
||||
offset += emote_string.length() + loc.start - loc.end - 1
|
||||
var bottom : bool = $Chat/ScrollContainer.scroll_vertical == $Chat/ScrollContainer.get_v_scrollbar().max_value - $Chat/ScrollContainer.get_v_scrollbar().rect_size.y
|
||||
msgnode.set_msg(str(time["hour"]) + ":" + ("0" + str(time["minute"]) if time["minute"] < 10 else str(time["minute"])), senderdata, msg, badges)
|
||||
$Chat/ScrollContainer/ChatMessagesContainer.add_child(msgnode)
|
||||
yield(get_tree(), "idle_frame")
|
||||
if (bottom):
|
||||
$Chat/ScrollContainer.scroll_vertical = $Chat/ScrollContainer.get_v_scrollbar().max_value
|
||||
|
||||
class EmoteLocation extends Reference:
|
||||
var id : String
|
||||
var start : int
|
||||
var end : int
|
||||
|
||||
func _init(emote_id, start_idx, end_idx):
|
||||
self.id = emote_id
|
||||
self.start = start_idx
|
||||
self.end = end_idx
|
||||
|
||||
static func smaller(a : EmoteLocation, b : EmoteLocation):
|
||||
return a.start < b.start
|
4
ChatMessage.gd
Normal file
4
ChatMessage.gd
Normal file
@ -0,0 +1,4 @@
|
||||
extends HBoxContainer
|
||||
|
||||
func set_msg(stamp : String, data : SenderData, msg : String, badges : String) -> void:
|
||||
$RichTextLabel.bbcode_text = stamp + " " + badges + "[b][color="+ data.tags["color"] + "]" + data.tags["display-name"] +"[/color][/b]: " + msg
|
23
ChatMessage.tscn
Normal file
23
ChatMessage.tscn
Normal file
@ -0,0 +1,23 @@
|
||||
[gd_scene load_steps=2 format=2]
|
||||
|
||||
[ext_resource path="res://ChatMessage.gd" type="Script" id=1]
|
||||
|
||||
[node name="ChatMessage" type="HBoxContainer"]
|
||||
margin_right = 400.0
|
||||
margin_bottom = 24.0
|
||||
size_flags_horizontal = 3
|
||||
script = ExtResource( 1 )
|
||||
__meta__ = {
|
||||
"_edit_use_anchors_": false
|
||||
}
|
||||
|
||||
[node name="RichTextLabel" type="RichTextLabel" parent="."]
|
||||
margin_right = 400.0
|
||||
margin_bottom = 24.0
|
||||
focus_mode = 2
|
||||
size_flags_horizontal = 3
|
||||
size_flags_vertical = 3
|
||||
bbcode_enabled = true
|
||||
fit_content_height = true
|
||||
scroll_active = false
|
||||
selection_enabled = true
|
79
Gift.gd
Normal file
79
Gift.gd
Normal file
@ -0,0 +1,79 @@
|
||||
extends Gift
|
||||
|
||||
func _ready() -> void:
|
||||
# I use a file in the working directory to store auth data
|
||||
# so that I don't accidentally push it to the repository.
|
||||
# Replace this or create a auth file with 3 lines in your
|
||||
# project directory:
|
||||
# <bot username>
|
||||
# <oauth token>
|
||||
# <initial channel>
|
||||
var authfile := File.new()
|
||||
authfile.open("./auth", File.READ)
|
||||
var botname := authfile.get_line()
|
||||
var token := authfile.get_line()
|
||||
var initial_channel = authfile.get_line()
|
||||
|
||||
connect_to_twitch()
|
||||
yield(self, "twitch_connected")
|
||||
|
||||
# Login using your username and an oauth token.
|
||||
# You will have to either get a oauth token yourself or use
|
||||
# https://twitchapps.com/tokengen/
|
||||
# to generate a token with custom scopes.
|
||||
authenticate_oauth(botname, token)
|
||||
if(yield(self, "login_attempt") == false):
|
||||
print("Invalid username or token.")
|
||||
return
|
||||
join_channel(initial_channel)
|
||||
|
||||
connect("cmd_no_permission", get_parent(), "no_permission")
|
||||
connect("chat_message", get_parent(), "chat_message")
|
||||
|
||||
# Adds a command with a specified permission flag.
|
||||
# All implementations must take at least one arg for the command info.
|
||||
# Implementations that recieve args requrires two args,
|
||||
# the second arg will contain all params in a PoolStringArray
|
||||
# This command can only be executed by VIPS/MODS/SUBS/STREAMER
|
||||
add_command("test", get_parent(), "command_test", 0, 0, PermissionFlag.NON_REGULAR)
|
||||
|
||||
# These two commands can be executed by everyone
|
||||
add_command("helloworld", get_parent(), "hello_world")
|
||||
add_command("greetme", get_parent(), "greet_me")
|
||||
|
||||
# This command can only be executed by the streamer
|
||||
add_command("streamer_only", get_parent(), "streamer_only", 0, 0, PermissionFlag.STREAMER)
|
||||
|
||||
# Command that requires exactly 1 arg.
|
||||
add_command("greet", get_parent(), "greet", 1, 1)
|
||||
|
||||
# Command that prints every arg seperated by a comma (infinite args allowed), at least 2 required
|
||||
add_command("list", get_parent(), "list", -1, 2)
|
||||
|
||||
# Adds a command alias
|
||||
add_alias("test","test1")
|
||||
add_alias("test","test2")
|
||||
add_alias("test","test3")
|
||||
# Or do it in a single line
|
||||
# add_aliases("test", ["test1", "test2", "test3"])
|
||||
|
||||
# Remove a single command
|
||||
remove_command("test2")
|
||||
|
||||
# Now only knows commands "test", "test1" and "test3"
|
||||
remove_command("test")
|
||||
# Now only knows commands "test1" and "test3"
|
||||
|
||||
# Remove all commands that call the same function as the specified command
|
||||
purge_command("test1")
|
||||
# Now no "test" command is known
|
||||
|
||||
# Send a chat message to the only connected channel (<channel_name>)
|
||||
# Fails, if connected to more than one channel.
|
||||
# chat("TEST")
|
||||
|
||||
# Send a chat message to channel <channel_name>
|
||||
# chat("TEST", initial_channel)
|
||||
|
||||
# Send a whisper to target user
|
||||
# whisper("TEST", initial_channel)
|
2
LICENSE
2
LICENSE
@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2019-2023 Max Kross
|
||||
Copyright (c) 2019-2021 Max Kross
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
26
Node.gd
Normal file
26
Node.gd
Normal file
@ -0,0 +1,26 @@
|
||||
extends Control
|
||||
|
||||
func chat_message(data : SenderData, msg : String) -> void:
|
||||
$ChatContainer.put_chat(data, msg)
|
||||
|
||||
# Check the CommandInfo class for the available info of the cmd_info.
|
||||
func command_test(cmd_info : CommandInfo) -> void:
|
||||
print("A")
|
||||
|
||||
func hello_world(cmd_info : CommandInfo) -> void:
|
||||
$Gift.chat("HELLO WORLD!")
|
||||
|
||||
func streamer_only(cmd_info : CommandInfo) -> void:
|
||||
$Gift.chat("Streamer command executed")
|
||||
|
||||
func no_permission(cmd_info : CommandInfo) -> void:
|
||||
$Gift.chat("NO PERMISSION!")
|
||||
|
||||
func greet(cmd_info : CommandInfo, arg_ary : PoolStringArray) -> void:
|
||||
$Gift.chat("Greetings, " + arg_ary[0])
|
||||
|
||||
func greet_me(cmd_info : CommandInfo) -> void:
|
||||
$Gift.chat("Greetings, " + cmd_info.sender_data.tags["display-name"] + "!")
|
||||
|
||||
func list(cmd_info : CommandInfo, arg_ary : PoolStringArray) -> void:
|
||||
$Gift.chat(arg_ary.join(", "))
|
90
Node.tscn
Normal file
90
Node.tscn
Normal file
@ -0,0 +1,90 @@
|
||||
[gd_scene load_steps=6 format=2]
|
||||
|
||||
[ext_resource path="res://Gift.gd" type="Script" id=1]
|
||||
[ext_resource path="res://addons/gift/icon.png" type="Texture" id=2]
|
||||
[ext_resource path="res://Button.gd" type="Script" id=3]
|
||||
[ext_resource path="res://ChatContainer.gd" type="Script" id=5]
|
||||
[ext_resource path="res://Node.gd" type="Script" id=6]
|
||||
|
||||
[node name="Node" type="Control"]
|
||||
anchor_right = 1.0
|
||||
anchor_bottom = 1.0
|
||||
script = ExtResource( 6 )
|
||||
__meta__ = {
|
||||
"_edit_use_anchors_": false
|
||||
}
|
||||
|
||||
[node name="Gift" type="Node" parent="."]
|
||||
script = ExtResource( 1 )
|
||||
__meta__ = {
|
||||
"_editor_icon": ExtResource( 2 )
|
||||
}
|
||||
get_images = true
|
||||
|
||||
[node name="ChatContainer" type="VBoxContainer" parent="."]
|
||||
anchor_right = 1.0
|
||||
anchor_bottom = 1.0
|
||||
script = ExtResource( 5 )
|
||||
__meta__ = {
|
||||
"_edit_use_anchors_": false
|
||||
}
|
||||
|
||||
[node name="Chat" type="Panel" parent="ChatContainer"]
|
||||
show_behind_parent = true
|
||||
margin_right = 400.0
|
||||
margin_bottom = 572.0
|
||||
size_flags_horizontal = 3
|
||||
size_flags_vertical = 3
|
||||
__meta__ = {
|
||||
"_edit_use_anchors_": false
|
||||
}
|
||||
|
||||
[node name="ScrollContainer" type="ScrollContainer" parent="ChatContainer/Chat"]
|
||||
anchor_right = 1.0
|
||||
anchor_bottom = 1.0
|
||||
margin_left = 10.0
|
||||
margin_top = 10.0
|
||||
margin_right = -10.0
|
||||
margin_bottom = -10.0
|
||||
follow_focus = true
|
||||
scroll_horizontal_enabled = false
|
||||
__meta__ = {
|
||||
"_edit_use_anchors_": false
|
||||
}
|
||||
|
||||
[node name="ChatMessagesContainer" type="VBoxContainer" parent="ChatContainer/Chat/ScrollContainer"]
|
||||
margin_right = 380.0
|
||||
margin_bottom = 552.0
|
||||
size_flags_horizontal = 3
|
||||
size_flags_vertical = 3
|
||||
custom_constants/separation = 6
|
||||
__meta__ = {
|
||||
"_edit_use_anchors_": false
|
||||
}
|
||||
|
||||
[node name="HBoxContainer" type="HBoxContainer" parent="ChatContainer"]
|
||||
margin_top = 576.0
|
||||
margin_right = 400.0
|
||||
margin_bottom = 600.0
|
||||
|
||||
[node name="LineEdit" type="LineEdit" parent="ChatContainer/HBoxContainer"]
|
||||
margin_right = 296.0
|
||||
margin_bottom = 24.0
|
||||
size_flags_horizontal = 3
|
||||
size_flags_vertical = 3
|
||||
caret_blink = true
|
||||
caret_blink_speed = 0.5
|
||||
__meta__ = {
|
||||
"_edit_use_anchors_": false
|
||||
}
|
||||
|
||||
[node name="Button" type="Button" parent="ChatContainer/HBoxContainer"]
|
||||
margin_left = 300.0
|
||||
margin_right = 400.0
|
||||
margin_bottom = 24.0
|
||||
rect_min_size = Vector2( 100, 0 )
|
||||
text = "Send"
|
||||
script = ExtResource( 3 )
|
||||
__meta__ = {
|
||||
"_edit_use_anchors_": false
|
||||
}
|
155
README.md
155
README.md
@ -1,16 +1,159 @@
|
||||
# GIFT
|
||||
Godot IRC For Twitch addon
|
||||
|
||||
To use this plugin, you need to create a new application on dev.twitch.tv to get a client ID and possibly a client secret (depending on which authentication method you choose). The redirect URL of your App has to be http://localhost:18297 or the URL you specify in the RedirectingFlow constructor.
|
||||
- [Examples](https://github.com/MennoMax/gift#Examples)
|
||||
- [API](https://github.com/MennoMax/gift#API)
|
||||
- [Exported Variables](https://github.com/MennoMax/gift#Exported-Variables)
|
||||
- [Signals](https://github.com/MennoMax/gift#Signals)
|
||||
- [Functions](https://github.com/MennoMax/gift#Functions)
|
||||
- [Utility Classes](https://github.com/MennoMax/gift#Utility-Classes)
|
||||
|
||||
If you require help, feel free to join my >[Discord Server](https://discord.gg/28DQbuwMM2)< and ask your questions <3
|
||||
***
|
||||
|
||||
Below is a working example of this plugin, which is included in this project. A replication of the twitch chat. Most information about the Twitch API can be found in the [official documentation](https://dev.twitch.tv/docs/).
|
||||
|
||||
[Example.gd](https://github.com/issork/gift/blob/master/example/Example.gd)
|
||||
Below is a working example of this plugin, which is included in this project. A replication of the twitch chat.
|
||||
|
||||

|
||||
|
||||
### Examples
|
||||
|
||||
The following code is also [included](https://github.com/MennoMax/gift/blob/master/Gift.gd) in this repository.
|
||||
```gdscript
|
||||
extends Gift
|
||||
|
||||
func _ready() -> void:
|
||||
connect("cmd_no_permission", self, "no_permission")
|
||||
connect_to_twitch()
|
||||
yield(self, "twitch_connected")
|
||||
|
||||
# Login using your username and an oauth token.
|
||||
# You will have to either get a oauth token yourself or use
|
||||
# https://twitchapps.com/tokengen/
|
||||
# to generate a token with custom scopes.
|
||||
authenticate_oauth(<account_name>, <oauth_token>)
|
||||
if(yield(self, "login_attempt") == false):
|
||||
print("Invalid username or token.")
|
||||
return
|
||||
join_channel(<channel_name>)
|
||||
|
||||
# Adds a command with a specified permission flag.
|
||||
# All implementations must take at least one arg for the command info.
|
||||
# Implementations that recieve args requrires two args,
|
||||
# the second arg will contain all params in a PoolStringArray
|
||||
# This command can only be executed by VIPS/MODS/SUBS/STREAMER
|
||||
add_command("test", self, "command_test", 0, 0, PermissionFlag.NON_REGULAR)
|
||||
|
||||
# These two commands can be executed by everyone
|
||||
add_command("helloworld", self, "hello_world")
|
||||
add_command("greetme", self, "greet_me")
|
||||
|
||||
# This command can only be executed by the streamer
|
||||
add_command("streamer_only", self, "streamer_only", 0, 0, PermissionFlag.STREAMER)
|
||||
|
||||
# Command that requires exactly 1 arg.
|
||||
add_command("greet", self, "greet", 1, 1)
|
||||
|
||||
# Command that prints every arg seperated by a comma (infinite args allowed), at least 2 required
|
||||
add_command("list", self, "list", -1, 2)
|
||||
|
||||
# Adds a command alias
|
||||
add_alias("test","test1")
|
||||
add_alias("test","test2")
|
||||
add_alias("test","test3")
|
||||
# Or do it in a single line
|
||||
# add_aliases("test", ["test1", "test2", "test3"])
|
||||
|
||||
# Remove a single command
|
||||
remove_command("test2")
|
||||
|
||||
# Now only knows commands "test", "test1" and "test3"
|
||||
remove_command("test")
|
||||
# Now only knows commands "test1" and "test3"
|
||||
|
||||
# Remove all commands that call the same function as the specified command
|
||||
purge_command("test1")
|
||||
# Now no "test" command is known
|
||||
|
||||
# Send a chat message to the only connected channel (<channel_name>)
|
||||
# Fails, if connected to more than one channel.
|
||||
chat("TEST")
|
||||
|
||||
# Send a chat message to channel <channel_name>
|
||||
chat("TEST", <channel_name>)
|
||||
|
||||
# Send a whisper to target user
|
||||
whisper("TEST", <target_name>)
|
||||
|
||||
# Check the CommandInfo class for the available info of the cmd_info.
|
||||
func command_test(cmd_info : CommandInfo) -> void:
|
||||
print("A")
|
||||
|
||||
func hello_world(cmd_info : CommandInfo) -> void:
|
||||
chat("HELLO WORLD!")
|
||||
|
||||
func streamer_only(cmd_info : CommandInfo) -> void:
|
||||
chat("Streamer command executed")
|
||||
|
||||
func no_permission(cmd_info : CommandInfo) -> void:
|
||||
chat("NO PERMISSION!")
|
||||
|
||||
func greet(cmd_info : CommandInfo, arg_ary : PoolStringArray) -> void:
|
||||
chat("Greetings, " + arg_ary[0])
|
||||
|
||||
func greet_me(cmd_info : CommandInfo) -> void:
|
||||
chat("Greetings, " + cmd_info.sender_data.tags["display-name"] + "!")
|
||||
|
||||
func list(cmd_info : CommandInfo, arg_ary : PoolStringArray) -> void:
|
||||
chat(arg_ary.join(", "))
|
||||
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
## API
|
||||
|
||||
### Exported Variables
|
||||
- **command_prefix**: PoolStringArray - Prefixes for commands. Every message that starts with one of these will be interpreted as one.
|
||||
- **chat_timeout** : float - Time to wait before sending the next chat message. Values below ~0.31 will lead to a disconnect at 100 messages in the queue.
|
||||
- **get_badges** : bool - Wether or not badges should be downloaded and cached in RAM.
|
||||
- **get_emotes** : bool - Wether or not emotes should be downloaded and cached in RAM.
|
||||
- **disk_cache** : bool - If true, badges and emotes will be cached on the disk instead.
|
||||
- **disk_cache_path** : String - Path to the cache folder on the hard drive.
|
||||
|
||||
***
|
||||
|
||||
### Signals:
|
||||
|Signal|Params|Description|
|
||||
|-|-|-|
|
||||
|twitch_connected|-|The underlying websocket successfully connected to Twitch.|
|
||||
|twitch_disconnected|-|The connection has been closed. Not emitted if Twitch announced a reconnect.|
|
||||
|twitch_unavailbale|-|Could not establish a connection to Twitch.|
|
||||
|twitch_reconnect|-|Twitch requested the client to reconnect. (Will be unavailable until next connect)|
|
||||
|login_attempt|success(bool) - wether or not the login attempt was successful|The client tried to login.|
|
||||
|chat_message|sender_data(SenderData), message(String), channel(String)|User sent a message in chat.|
|
||||
|whisper_message|sender_data(SenderData), message(String), channel(String)|User sent a whisper message.|
|
||||
|unhandled message|message(String), tags(Dictionary)|Unhandled message from Twitch.|
|
||||
|cmd_invalid_argcount|cmd_name(String), sender_data(SenderData), cmd_data(CommandData), arg_ary(PoolStringArray)|A command has been called by a chatter with an invalid amount of args.|
|
||||
|cmd_no_permission|cmd_name(String), sender_data(SenderData), cmd_data(CommandData), arg_ary(PoolStringArray)|A command has been called by a chater without having the required permissions.|
|
||||
|pong|-|A ping from Twitch has been answered with a pong.|
|
||||
|
||||
***
|
||||
|
||||
### Functions:
|
||||
|Function|Params|Description|
|
||||
|-|-|-|
|
||||
|authenticate_oauth|nick(String) - the accoutns username, token(String) - your oauth token|Authenticate yourself to use the Twitch API. Check out https://twitchapps.com/tokengen/ to generate a token.|
|
||||
|send|text(string) - the UTF8-String that should be sent to Twitch|Sends a UTF8-String to Twitch over the websocket.|
|
||||
|chat|message(String), channel(String) - DEFAULT: Only connected channel|Sends a chat message to a channel.|
|
||||
|whisper|message(String), target(String)| Sends a whisper message to the specified user.|
|
||||
|add_command|cmd_name(String), instance(Object), instance_func(String), max_args(int), min_args(int), permission_level(int), where(int)| Registers a command with a function to call on a specified object. You can also set min/max args allowed and where (whisper or chat) the command execution should be allowed to be requested.|
|
||||
|remove_command|cmd_name(String)|Removes a single command or alias from the command registry.|
|
||||
|purge_command|cmd_name(String)| Removes all commands that call the same function on the same object as the specified command.|
|
||||
|add_alias|cmd_name(String), alias(String)|Registers a command alias.|
|
||||
|add_aliases|cmd_name(String), aliases(PoolStringArray)|Registers all command aliases in the array.|
|
||||
|join_channel|channel(String)|Joins a channel.|
|
||||
|leave_channel|channel(String)|Leaves a channel.|
|
||||
|
||||
***
|
||||
|
||||
### Utility Classes
|
||||
|
||||
@ -18,7 +161,7 @@ Below is a working example of this plugin, which is included in this project. A
|
||||
|
||||
#### CommandData
|
||||
##### Data required to store, execute and handle commands properly.
|
||||
- **func_ref** : Callable - Function that is called by the command.
|
||||
- **func_ref** : FuncRef - Function that is called by the command.
|
||||
- **permission_level** : int - Permission level required by the command.
|
||||
- **max_args** : int - Maximum number of arguments this command accepts. cmd_invalid_argcount is emitted if above this number.
|
||||
- **min_args** : int - Minimum number of arguments this command accepts. cmd_invalid_argcount is emitted if below this number.
|
||||
|
@ -1,134 +0,0 @@
|
||||
class_name TwitchAPIConnection
|
||||
extends RefCounted
|
||||
|
||||
signal received_response(response)
|
||||
|
||||
var id_conn : TwitchIDConnection
|
||||
|
||||
var client : HTTPClient = HTTPClient.new()
|
||||
var client_response : PackedByteArray = []
|
||||
|
||||
func _init(id_connection : TwitchIDConnection) -> void:
|
||||
client.blocking_mode_enabled = true
|
||||
id_conn = id_connection
|
||||
id_conn.polled.connect(poll)
|
||||
client.connect_to_host("https://api.twitch.tv", -1, TLSOptions.client())
|
||||
|
||||
func poll() -> void:
|
||||
client.poll()
|
||||
if (client.get_status() == HTTPClient.STATUS_BODY):
|
||||
client_response += client.read_response_body_chunk()
|
||||
elif (!client_response.is_empty()):
|
||||
received_response.emit(client_response.get_string_from_utf8())
|
||||
client_response.clear()
|
||||
|
||||
func request(method : int, url : String, headers : PackedStringArray, body : String = "") -> Dictionary:
|
||||
client.request(method, url, headers, body)
|
||||
var response = await(received_response)
|
||||
match (client.get_response_code()):
|
||||
401:
|
||||
id_conn.token_invalid.emit()
|
||||
return {}
|
||||
return JSON.parse_string(response)
|
||||
|
||||
func get_channel_chat_badges(broadcaster_id : String) -> Dictionary:
|
||||
var headers : PackedStringArray = [
|
||||
"Authorization: Bearer %s" % id_conn.last_token.token,
|
||||
"Client-Id: %s" % id_conn.last_token.last_client_id
|
||||
]
|
||||
return await(request(HTTPClient.METHOD_GET,"/helix/chat/badges?broadcaster_id=%s" % broadcaster_id, headers))
|
||||
|
||||
func get_global_chat_badges() -> Dictionary:
|
||||
var headers : PackedStringArray = [
|
||||
"Authorization: Bearer %s" % id_conn.last_token.token,
|
||||
"Client-Id: %s" % id_conn.last_token.last_client_id
|
||||
]
|
||||
return await(request(HTTPClient.METHOD_GET,"/helix/chat/badges/global", headers))
|
||||
|
||||
# Create a eventsub subscription. For the data required, refer to https://dev.twitch.tv/docs/eventsub/eventsub-subscription-types/
|
||||
func create_eventsub_subscription(subscription_data : Dictionary) -> Dictionary:
|
||||
var headers : PackedStringArray = [
|
||||
"Authorization: Bearer %s" % id_conn.last_token.token,
|
||||
"Client-Id: %s" % id_conn.last_token.last_client_id,
|
||||
"Content-Type: application/json"
|
||||
]
|
||||
var response = await(request(HTTPClient.METHOD_POST, "/helix/eventsub/subscriptions", headers, JSON.stringify(subscription_data)))
|
||||
match (client.get_response_code()):
|
||||
400:
|
||||
print("Bad Request! Check the data you specified.")
|
||||
return {}
|
||||
403:
|
||||
print("Forbidden! The access token is missing the required scopes.")
|
||||
return {}
|
||||
409:
|
||||
print("Conflict! A subscription already exists for the specified event type and condition combination.")
|
||||
return {}
|
||||
429:
|
||||
print("Too Many Requests! The request exceeds the number of subscriptions that you may create with the same combination of type and condition values.")
|
||||
return {}
|
||||
return response
|
||||
|
||||
func get_users_by_id(ids : Array[String]) -> Dictionary:
|
||||
return await(get_users([], ids))
|
||||
|
||||
func get_users_by_name(names : Array[String]) -> Dictionary:
|
||||
return await(get_users(names, []))
|
||||
|
||||
func get_users(names : Array[String], ids : Array[String]) -> Dictionary:
|
||||
var headers : PackedStringArray = [
|
||||
"Authorization: Bearer %s" % id_conn.last_token.token,
|
||||
"Client-Id: %s" % id_conn.last_token.last_client_id
|
||||
]
|
||||
if (names.is_empty() && ids.is_empty()):
|
||||
return {}
|
||||
var params = "?"
|
||||
if (names.size() > 0):
|
||||
params += "login=%s" % names.pop_back()
|
||||
while(names.size() > 0):
|
||||
params += "&login=%s" % names.pop_back()
|
||||
if (params.length() > 1):
|
||||
params += "&"
|
||||
if (ids.size() > 0):
|
||||
params += "id=%s" % ids.pop_back()
|
||||
while(ids.size() > 0):
|
||||
params += "&id=%s" % ids.pop_back()
|
||||
var response = await(request(HTTPClient.METHOD_GET,"/helix/users/%s" % params, headers))
|
||||
match (client.get_response_code()):
|
||||
400:
|
||||
id_conn.token_invalid.emit()
|
||||
return {}
|
||||
return response
|
||||
|
||||
# Send a whisper from user_id to target_id with the specified message.
|
||||
# Returns true on success or if the message was silently dropped, false on failure.
|
||||
func send_whisper(from_user_id : String, to_user_id : String, message : String) -> bool:
|
||||
var headers : PackedStringArray = [
|
||||
"Authorization: Bearer %s" % id_conn.last_token.token,
|
||||
"Client-Id: %s" % id_conn.last_token.last_client_id,
|
||||
"Content-Type: application/json"
|
||||
]
|
||||
var params: String = "?"
|
||||
params += "from_user_id=%s" % from_user_id
|
||||
params += "&to_user_id=%s" % to_user_id
|
||||
var response: Dictionary = await(
|
||||
request(
|
||||
HTTPClient.METHOD_POST,
|
||||
"/helix/whispers" + params,
|
||||
headers,
|
||||
JSON.stringify({"message": message})
|
||||
)
|
||||
)
|
||||
var response_code: int = client.get_response_code()
|
||||
match (response_code):
|
||||
# 200 is returned even if Twitch documentation says only 204
|
||||
200, 204:
|
||||
print("Success! The whisper was sent.")
|
||||
return true
|
||||
# Complete list of error codes according to Twitch documentation
|
||||
400, 401, 403, 404, 429:
|
||||
print("[Error (send_whisper)] %s - %s" % [response["status"], response["message"]])
|
||||
return false
|
||||
# Fallback for unknown response codes
|
||||
_:
|
||||
print("[Default (send_whisper)] %s " % response_code)
|
||||
return false
|
@ -1,26 +0,0 @@
|
||||
class_name TwitchOAuthFlow
|
||||
extends RefCounted
|
||||
|
||||
signal token_received(token_data)
|
||||
|
||||
var peer : StreamPeerTCP
|
||||
|
||||
func _create_peer() -> StreamPeerTCP:
|
||||
return null
|
||||
|
||||
func poll() -> void:
|
||||
if (!peer):
|
||||
peer = _create_peer()
|
||||
if (peer && peer.get_status() == StreamPeerTCP.STATUS_CONNECTED):
|
||||
_poll_peer()
|
||||
elif (peer.get_status() == StreamPeerTCP.STATUS_CONNECTED):
|
||||
_poll_peer()
|
||||
|
||||
func _poll_peer() -> void:
|
||||
peer.poll()
|
||||
if (peer.get_available_bytes() > 0):
|
||||
var response = peer.get_utf8_string(peer.get_available_bytes())
|
||||
_process_response(response)
|
||||
|
||||
func _process_response(response : String) -> void:
|
||||
pass
|
@ -1,45 +0,0 @@
|
||||
class_name AuthorizationCodeGrantFlow
|
||||
extends RedirectingFlow
|
||||
|
||||
signal auth_code_received(token)
|
||||
signal http_connected
|
||||
|
||||
var http_client : HTTPClient
|
||||
var chunks : PackedByteArray = PackedByteArray()
|
||||
|
||||
func get_authorization_code(client_id : String, scopes : PackedStringArray, force_verify : bool = false) -> String:
|
||||
start_tcp_server()
|
||||
OS.shell_open("https://id.twitch.tv/oauth2/authorize?response_type=code&client_id=%s&scope=%s&redirect_uri=%s&force_verify=%s" % [client_id, " ".join(scopes).uri_encode(), redirect_url, "true" if force_verify else "false"].map(func (a : String): return a.uri_encode()))
|
||||
print("Waiting for user to login.")
|
||||
var code : String = await(auth_code_received)
|
||||
server.stop()
|
||||
return code
|
||||
|
||||
func login(client_id : String, client_secret : String, auth_code : String = "", scopes : PackedStringArray = [], force_verify : bool = false) -> RefreshableUserAccessToken:
|
||||
if (auth_code == ""):
|
||||
auth_code = await(get_authorization_code(client_id, scopes, force_verify))
|
||||
if (http_client == null):
|
||||
http_client = HTTPClient.new()
|
||||
http_client.connect_to_host("https://id.twitch.tv", -1, TLSOptions.client())
|
||||
await(http_connected)
|
||||
http_client.request(HTTPClient.METHOD_POST, "/oauth2/token", ["Content-Type: application/x-www-form-urlencoded"], "client_id=%s&client_secret=%s&code=%s&grant_type=authorization_code&redirect_uri=%s" % [client_id, client_secret, auth_code, redirect_url])
|
||||
print("Using auth token to login.")
|
||||
var token : RefreshableUserAccessToken = RefreshableUserAccessToken.new(await(token_received), client_id, client_secret)
|
||||
token.fresh = true
|
||||
return token
|
||||
|
||||
func poll() -> void:
|
||||
if (server != null):
|
||||
super.poll()
|
||||
|
||||
func _handle_empty_response() -> void:
|
||||
super._handle_empty_response()
|
||||
auth_code_received.emit("")
|
||||
|
||||
func _handle_success(data : Dictionary) -> void:
|
||||
super._handle_success(data)
|
||||
auth_code_received.emit(data["code"])
|
||||
|
||||
func _handle_error(data : Dictionary) -> void:
|
||||
super._handle_error(data)
|
||||
auth_code_received.emit("")
|
@ -1,30 +0,0 @@
|
||||
class_name ClientCredentialsGrantFlow
|
||||
extends TwitchOAuthFlow
|
||||
|
||||
signal http_connected
|
||||
|
||||
var http_client : HTTPClient
|
||||
var chunks : PackedByteArray = PackedByteArray()
|
||||
|
||||
func poll() -> void:
|
||||
if (http_client != null):
|
||||
http_client.poll()
|
||||
if (http_client.get_status() == HTTPClient.STATUS_CONNECTED):
|
||||
http_connected.emit()
|
||||
if (!chunks.is_empty()):
|
||||
var response = chunks.get_string_from_utf8()
|
||||
token_received.emit(JSON.parse_string(response))
|
||||
chunks.clear()
|
||||
http_client = null
|
||||
elif (http_client.get_status() == HTTPClient.STATUS_BODY):
|
||||
chunks += http_client.read_response_body_chunk()
|
||||
|
||||
func login(client_id : String, client_secret : String) -> AppAccessToken:
|
||||
if (http_client == null):
|
||||
http_client = HTTPClient.new()
|
||||
http_client.connect_to_host("https://id.twitch.tv", -1, TLSOptions.client())
|
||||
await(http_connected)
|
||||
http_client.request(HTTPClient.METHOD_POST, "/oauth2/token", ["Content-Type: application/x-www-form-urlencoded"], "client_id=%s&client_secret=%s&grant_type=client_credentials" % [client_id, client_secret])
|
||||
var token : AppAccessToken = AppAccessToken.new(await(token_received), client_id)
|
||||
token.fresh = true
|
||||
return token
|
@ -1,34 +0,0 @@
|
||||
class_name ImplicitGrantFlow
|
||||
extends RedirectingFlow
|
||||
|
||||
# Get an OAuth token from Twitch. Returns null if authentication failed.
|
||||
func login(client_id : String, scopes : PackedStringArray, force_verify : bool = false) -> UserAccessToken:
|
||||
start_tcp_server()
|
||||
OS.shell_open("https://id.twitch.tv/oauth2/authorize?response_type=token&client_id=%s&force_verify=%s&redirect_uri=%s&scope=%s" % [client_id, "true" if force_verify else "false", redirect_url, " ".join(scopes)].map(func (a : String): return a.uri_encode()))
|
||||
print("Waiting for user to login.")
|
||||
var token_data : Dictionary = await(token_received)
|
||||
server.stop()
|
||||
if (!token_data.is_empty()):
|
||||
var token : UserAccessToken = UserAccessToken.new(token_data, client_id)
|
||||
token.fresh = true
|
||||
return token
|
||||
return null
|
||||
|
||||
func poll() -> void:
|
||||
if (!peer):
|
||||
peer = _create_peer()
|
||||
if (peer && peer.get_status() == StreamPeerTCP.STATUS_CONNECTED):
|
||||
_poll_peer()
|
||||
elif (peer.get_status() == StreamPeerTCP.STATUS_CONNECTED):
|
||||
_poll_peer()
|
||||
|
||||
func _handle_empty_response() -> void:
|
||||
send_response("200 OK", "<html><script>window.location = window.location.toString().replace('#','?');</script><head><title>Twitch Login</title></head></html>".to_utf8_buffer())
|
||||
|
||||
func _handle_success(data : Dictionary) -> void:
|
||||
super._handle_success(data)
|
||||
token_received.emit(data)
|
||||
|
||||
func _handle_error(data : Dictionary) -> void:
|
||||
super._handle_error(data)
|
||||
token_received.emit({})
|
@ -1,62 +0,0 @@
|
||||
class_name RedirectingFlow
|
||||
extends TwitchOAuthFlow
|
||||
|
||||
var server : TCPServer
|
||||
|
||||
var tcp_port : int
|
||||
var redirect_url : String
|
||||
|
||||
func _init(port : int = 18297, redirect : String = "http://localhost:%s" % port) -> void:
|
||||
tcp_port = port
|
||||
redirect_url = redirect
|
||||
|
||||
func _create_peer() -> StreamPeerTCP:
|
||||
return server.take_connection()
|
||||
|
||||
func start_tcp_server() -> void:
|
||||
if (server == null):
|
||||
server = TCPServer.new()
|
||||
if (server.listen(tcp_port) != OK):
|
||||
print("Could not listen to port %d" % tcp_port)
|
||||
|
||||
func send_response(response : String, body : PackedByteArray) -> void:
|
||||
peer.put_data(("HTTP/1.1 %s\r\n" % response).to_utf8_buffer())
|
||||
peer.put_data("Server: GIFT (Godot Engine)\r\n".to_utf8_buffer())
|
||||
peer.put_data(("Content-Length: %d\r\n"% body.size()).to_utf8_buffer())
|
||||
peer.put_data("Connection: close\r\n".to_utf8_buffer())
|
||||
peer.put_data("Content-Type: text/html; charset=UTF-8\r\n".to_utf8_buffer())
|
||||
peer.put_data("\r\n".to_utf8_buffer())
|
||||
peer.put_data(body)
|
||||
|
||||
func _process_response(response : String) -> void:
|
||||
if (response == ""):
|
||||
print("Empty response. Check if your redirect URL is set to %s." % redirect_url)
|
||||
return
|
||||
var start : int = response.substr(0, response.find("\n")).find("?")
|
||||
if (start == -1):
|
||||
_handle_empty_response()
|
||||
else:
|
||||
response = response.substr(start + 1, response.find(" ", start) - start)
|
||||
var data : Dictionary = {}
|
||||
for entry in response.split("&"):
|
||||
var pair = entry.split("=")
|
||||
data[pair[0]] = pair[1] if pair.size() > 0 else ""
|
||||
if (data.has("error")):
|
||||
_handle_error(data)
|
||||
else:
|
||||
_handle_success(data)
|
||||
peer.disconnect_from_host()
|
||||
peer = null
|
||||
|
||||
func _handle_empty_response() -> void:
|
||||
print ("Response from Twitch does not contain the required data.")
|
||||
|
||||
func _handle_success(data : Dictionary) -> void:
|
||||
data["scope"] = data["scope"].uri_decode().split(" ")
|
||||
print("Success.")
|
||||
send_response("200 OK", "<html><head><title>Twitch Login</title></head><body onload=\"javascript:close()\">Success!</body></html>".to_utf8_buffer())
|
||||
|
||||
func _handle_error(data : Dictionary) -> void:
|
||||
var msg = "Error %s: %s" % [data["error"], data["error_description"]]
|
||||
print(msg)
|
||||
send_response("400 BAD REQUEST", msg.to_utf8_buffer())
|
@ -1,5 +0,0 @@
|
||||
class_name AppAccessToken
|
||||
extends TwitchToken
|
||||
|
||||
func _init(data : Dictionary, client_id) -> void:
|
||||
super._init(data, client_id, data["expires_in"])
|
@ -1,10 +0,0 @@
|
||||
class_name RefreshableUserAccessToken
|
||||
extends UserAccessToken
|
||||
|
||||
var refresh_token : String
|
||||
var last_client_secret : String
|
||||
|
||||
func _init(data : Dictionary, client_id : String, client_secret : String) -> void:
|
||||
super._init(data, client_id)
|
||||
refresh_token = data["refresh_token"]
|
||||
last_client_secret = client_secret
|
@ -1,11 +0,0 @@
|
||||
class_name TwitchToken
|
||||
extends RefCounted
|
||||
|
||||
var last_client_id : String = ""
|
||||
var token : String
|
||||
var expires_in : int
|
||||
var fresh : bool = false
|
||||
|
||||
func _init(data : Dictionary, client_id : String, expires_in : int = 0) -> void:
|
||||
token = data["access_token"]
|
||||
last_client_id = client_id
|
@ -1,8 +0,0 @@
|
||||
class_name UserAccessToken
|
||||
extends TwitchToken
|
||||
|
||||
var scopes : PackedStringArray
|
||||
|
||||
func _init(data : Dictionary, client_id : String) -> void:
|
||||
super._init(data, client_id)
|
||||
scopes = data["scope"]
|
@ -1,107 +0,0 @@
|
||||
class_name GIFTCommandHandler
|
||||
extends RefCounted
|
||||
|
||||
signal cmd_invalid_argcount(command, sender_data, cmd_data, arg_ary)
|
||||
signal cmd_no_permission(command, sender_data, cmd_data, arg_ary)
|
||||
|
||||
# Required permission to execute the command
|
||||
enum PermissionFlag {
|
||||
EVERYONE = 0,
|
||||
VIP = 1,
|
||||
SUB = 2,
|
||||
MOD = 4,
|
||||
STREAMER = 8,
|
||||
MOD_STREAMER = 12, # Mods and the streamer
|
||||
NON_REGULAR = 15 # Everyone but regular viewers
|
||||
}
|
||||
|
||||
# Where the command should be accepted
|
||||
enum WhereFlag {
|
||||
CHAT = 1,
|
||||
WHISPER = 2,
|
||||
ANYWHERE = 3
|
||||
}
|
||||
|
||||
# Messages starting with one of these symbols are handled as commands. '/' will be ignored, reserved by Twitch.
|
||||
var command_prefixes : Array[String] = ["!"]
|
||||
# Dictionary of commands, contains <command key> -> <Callable> entries.
|
||||
var commands : Dictionary = {}
|
||||
|
||||
# Registers a command on an object with a func to call, similar to connect(signal, instance, func).
|
||||
func add_command(cmd_name : String, callable : Callable, max_args : int = 0, min_args : int = 0, permission_level : int = PermissionFlag.EVERYONE, where : int = WhereFlag.CHAT) -> void:
|
||||
commands[cmd_name] = CommandData.new(callable, permission_level, max_args, min_args, where)
|
||||
|
||||
# Removes a single command or alias.
|
||||
func remove_command(cmd_name : String) -> void:
|
||||
commands.erase(cmd_name)
|
||||
|
||||
# Removes a command and all associated aliases.
|
||||
func purge_command(cmd_name : String) -> void:
|
||||
var to_remove = commands.get(cmd_name)
|
||||
if(to_remove):
|
||||
var remove_queue = []
|
||||
for command in commands.keys():
|
||||
if(commands[command].func_ref == to_remove.func_ref):
|
||||
remove_queue.append(command)
|
||||
for queued in remove_queue:
|
||||
commands.erase(queued)
|
||||
|
||||
# Add a command alias. The command specified in 'cmd_name' can now also be executed with the
|
||||
# command specified in 'alias'.
|
||||
func add_alias(cmd_name : String, alias : String) -> void:
|
||||
if(commands.has(cmd_name)):
|
||||
commands[alias] = commands.get(cmd_name)
|
||||
|
||||
# Same as add_alias, but for multiple aliases at once.
|
||||
func add_aliases(cmd_name : String, aliases : PackedStringArray) -> void:
|
||||
for alias in aliases:
|
||||
add_alias(cmd_name, alias)
|
||||
|
||||
func handle_command(sender_data : SenderData, msg : String, whisper : bool = false) -> void:
|
||||
if(command_prefixes.has(msg.left(1))):
|
||||
msg = msg.right(-1)
|
||||
var split = msg.split(" ", true, 1)
|
||||
var command : String = split[0]
|
||||
var cmd_data : CommandData = commands.get(command)
|
||||
if(cmd_data):
|
||||
if(whisper == true && cmd_data.where & WhereFlag.WHISPER != WhereFlag.WHISPER):
|
||||
return
|
||||
elif(whisper == false && cmd_data.where & WhereFlag.CHAT != WhereFlag.CHAT):
|
||||
return
|
||||
var arg_ary : PackedStringArray = PackedStringArray()
|
||||
if (split.size() > 1):
|
||||
arg_ary = split[1].split(" ")
|
||||
if(arg_ary.size() > cmd_data.max_args && cmd_data.max_args != -1 || arg_ary.size() < cmd_data.min_args):
|
||||
cmd_invalid_argcount.emit(command, sender_data, cmd_data, arg_ary)
|
||||
return
|
||||
if(cmd_data.permission_level != 0):
|
||||
var user_perm_flags = get_perm_flag_from_tags(sender_data.tags)
|
||||
if(user_perm_flags & cmd_data.permission_level == 0):
|
||||
cmd_no_permission.emit(command, sender_data, cmd_data, arg_ary)
|
||||
return
|
||||
if(arg_ary.size() == 0):
|
||||
if (cmd_data.min_args > 0):
|
||||
cmd_invalid_argcount.emit(command, sender_data, cmd_data, arg_ary)
|
||||
return
|
||||
cmd_data.func_ref.call(CommandInfo.new(sender_data, command, whisper))
|
||||
else:
|
||||
cmd_data.func_ref.call(CommandInfo.new(sender_data, command, whisper), arg_ary)
|
||||
|
||||
func get_perm_flag_from_tags(tags : Dictionary) -> int:
|
||||
var flag = 0
|
||||
var entry = tags.get("badges")
|
||||
if(entry):
|
||||
for badge in entry.split(","):
|
||||
if(badge.begins_with("vip")):
|
||||
flag += PermissionFlag.VIP
|
||||
if(badge.begins_with("broadcaster")):
|
||||
flag += PermissionFlag.STREAMER
|
||||
entry = tags.get("mod")
|
||||
if(entry):
|
||||
if(entry == "1"):
|
||||
flag += PermissionFlag.MOD
|
||||
entry = tags.get("subscriber")
|
||||
if(entry):
|
||||
if(entry == "1"):
|
||||
flag += PermissionFlag.SUB
|
||||
return flag
|
@ -1,120 +0,0 @@
|
||||
class_name TwitchEventSubConnection
|
||||
extends RefCounted
|
||||
|
||||
const TEN_MINUTES_S : int = 600
|
||||
|
||||
# The id has been received from the welcome message.
|
||||
signal session_id_received(id)
|
||||
signal events_revoked(type, status)
|
||||
signal event(type, event_data)
|
||||
|
||||
enum ConnectionState {
|
||||
DISCONNECTED,
|
||||
CONNECTED,
|
||||
CONNECTION_FAILED,
|
||||
RECONNECTING
|
||||
}
|
||||
|
||||
var connection_state : ConnectionState = ConnectionState.DISCONNECTED
|
||||
|
||||
var eventsub_messages : Dictionary = {}
|
||||
var eventsub_reconnect_url : String = ""
|
||||
var session_id : String = ""
|
||||
var keepalive_timeout : int = 0
|
||||
var last_keepalive : int = 0
|
||||
|
||||
var last_cleanup : int = 0
|
||||
|
||||
var websocket : WebSocketPeer
|
||||
|
||||
var api : TwitchAPIConnection
|
||||
|
||||
func _init(twitch_api_connection : TwitchAPIConnection) -> void:
|
||||
api = twitch_api_connection
|
||||
api.id_conn.polled.connect(poll)
|
||||
|
||||
func connect_to_eventsub(url : String = "wss://eventsub.wss.twitch.tv/ws") -> void:
|
||||
if (websocket == null):
|
||||
websocket = WebSocketPeer.new()
|
||||
websocket.connect_to_url(url)
|
||||
print("Connecting to Twitch EventSub")
|
||||
await(session_id_received)
|
||||
|
||||
func poll() -> void:
|
||||
if (websocket != null):
|
||||
websocket.poll()
|
||||
var state := websocket.get_ready_state()
|
||||
match state:
|
||||
WebSocketPeer.STATE_OPEN:
|
||||
if (!connection_state == ConnectionState.CONNECTED):
|
||||
connection_state = ConnectionState.CONNECTED
|
||||
print("Connected to EventSub.")
|
||||
else:
|
||||
while (websocket.get_available_packet_count()):
|
||||
process_event(websocket.get_packet())
|
||||
WebSocketPeer.STATE_CLOSED:
|
||||
if(connection_state != ConnectionState.CONNECTED):
|
||||
print("Could not connect to EventSub.")
|
||||
websocket = null
|
||||
connection_state = ConnectionState.CONNECTION_FAILED
|
||||
elif(connection_state == ConnectionState.RECONNECTING):
|
||||
print("Reconnecting to EventSub")
|
||||
websocket.close()
|
||||
connect_to_eventsub(eventsub_reconnect_url)
|
||||
else:
|
||||
print("Disconnected from EventSub.")
|
||||
connection_state = ConnectionState.DISCONNECTED
|
||||
print("Connection closed! [%s]: %s"%[websocket.get_close_code(), websocket.get_close_reason()])
|
||||
websocket = null
|
||||
var t : int = Time.get_ticks_msec() / 1000 - TEN_MINUTES_S
|
||||
if (last_cleanup < t):
|
||||
last_cleanup = Time.get_ticks_msec() / 1000
|
||||
var to_remove : Array = []
|
||||
for msg in eventsub_messages:
|
||||
if (eventsub_messages[msg] < Time.get_unix_time_from_system() - TEN_MINUTES_S):
|
||||
to_remove.append(msg)
|
||||
for e in to_remove:
|
||||
eventsub_messages.erase(e)
|
||||
|
||||
func process_event(data : PackedByteArray) -> void:
|
||||
var msg : Dictionary = JSON.parse_string(data.get_string_from_utf8())
|
||||
if (eventsub_messages.has(msg["metadata"]["message_id"]) || Time.get_unix_time_from_datetime_string(msg["metadata"]["message_timestamp"]) < Time.get_unix_time_from_system() - TEN_MINUTES_S):
|
||||
return
|
||||
eventsub_messages[msg["metadata"]["message_id"]] = Time.get_unix_time_from_datetime_string(msg["metadata"]["message_timestamp"])
|
||||
var payload : Dictionary = msg["payload"]
|
||||
last_keepalive = Time.get_ticks_msec()
|
||||
match msg["metadata"]["message_type"]:
|
||||
"session_welcome":
|
||||
session_id = payload["session"]["id"]
|
||||
keepalive_timeout = payload["session"]["keepalive_timeout_seconds"]
|
||||
session_id_received.emit(session_id)
|
||||
"session_keepalive":
|
||||
if (payload.has("session")):
|
||||
keepalive_timeout = payload["session"]["keepalive_timeout_seconds"]
|
||||
"session_reconnect":
|
||||
connection_state = ConnectionState.RECONNECTING
|
||||
eventsub_reconnect_url = payload["session"]["reconnect_url"]
|
||||
"revocation":
|
||||
events_revoked.emit(payload["subscription"]["type"], payload["subscription"]["status"])
|
||||
"notification":
|
||||
var event_data : Dictionary = payload["event"]
|
||||
event.emit(payload["subscription"]["type"], event_data)
|
||||
|
||||
# Refer to https://dev.twitch.tv/docs/eventsub/eventsub-subscription-types/ for details on
|
||||
# which API versions are available and which conditions are required.
|
||||
func subscribe_event(event_name : String, version : String, conditions : Dictionary) -> void:
|
||||
var data : Dictionary = {}
|
||||
data["type"] = event_name
|
||||
data["version"] = version
|
||||
data["condition"] = conditions
|
||||
data["transport"] = {
|
||||
"method":"websocket",
|
||||
"session_id":session_id
|
||||
}
|
||||
var response = await(api.create_eventsub_subscription(data))
|
||||
if (response.has("error")):
|
||||
print("Subscription failed for event '%s'. Error %s (%s): %s" % [event_name, response["status"], response["error"], response["message"]])
|
||||
return
|
||||
elif (response.is_empty()):
|
||||
return
|
||||
print("Now listening to '%s' events." % event_name)
|
8
addons/gift/gift.gd
Executable file
8
addons/gift/gift.gd
Executable file
@ -0,0 +1,8 @@
|
||||
tool
|
||||
extends EditorPlugin
|
||||
|
||||
func _enter_tree() -> void:
|
||||
add_custom_type("Gift", "Node", preload("gift_node.gd"), preload("icon.png"))
|
||||
|
||||
func _exit_tree() -> void:
|
||||
remove_custom_type("Gift")
|
280
addons/gift/gift_node.gd
Normal file
280
addons/gift/gift_node.gd
Normal file
@ -0,0 +1,280 @@
|
||||
extends Node
|
||||
class_name Gift
|
||||
|
||||
# The underlying websocket sucessfully connected to twitch.
|
||||
signal twitch_connected
|
||||
# The connection has been closed. Not emitted if twitch announced a reconnect.
|
||||
signal twitch_disconnected
|
||||
# The connection to twitch failed.
|
||||
signal twitch_unavailable
|
||||
# Twitch requested the client to reconnect. (Will be unavailable until next connect)
|
||||
signal twitch_reconnect
|
||||
# The client tried to login. Returns true if successful, else false.
|
||||
signal login_attempt(success)
|
||||
# User sent a message in chat.
|
||||
signal chat_message(sender_data, message)
|
||||
# User sent a whisper message.
|
||||
signal whisper_message(sender_data, message)
|
||||
# Unhandled data passed through
|
||||
signal unhandled_message(message, tags)
|
||||
# A command has been called with invalid arg count
|
||||
signal cmd_invalid_argcount(cmd_name, sender_data, cmd_data, arg_ary)
|
||||
# A command has been called with insufficient permissions
|
||||
signal cmd_no_permission(cmd_name, sender_data, cmd_data, arg_ary)
|
||||
# Twitch's ping is about to be answered with a pong.
|
||||
signal pong
|
||||
# Emote has been downloaded
|
||||
signal emote_downloaded(emote_id)
|
||||
# Badge has been downloaded
|
||||
signal badge_downloaded(badge_name)
|
||||
|
||||
# Messages starting with one of these symbols are handled as commands. '/' will be ignored, reserved by Twitch.
|
||||
export(Array, String) var command_prefixes : Array = ["!"]
|
||||
# Time to wait in msec after each sent chat message. Values below ~310 might lead to a disconnect after 100 messages.
|
||||
export(int) var chat_timeout_ms = 320
|
||||
export(bool) var get_images : bool = false
|
||||
# If true, caches emotes/badges to disk, so that they don't have to be redownloaded on every restart.
|
||||
# This however means that they might not be updated if they change until you clear the cache.
|
||||
export(bool) var disk_cache : bool = false
|
||||
# Disk Cache has to be enbaled for this to work
|
||||
export(String, FILE) var disk_cache_path = "user://gift/cache"
|
||||
|
||||
var websocket := WebSocketClient.new()
|
||||
var user_regex := RegEx.new()
|
||||
var twitch_restarting
|
||||
# Twitch disconnects connected clients if too many chat messages are being sent. (At about 100 messages/30s)
|
||||
var chat_queue = []
|
||||
var last_msg = OS.get_ticks_msec()
|
||||
# Mapping of channels to their channel info, like available badges.
|
||||
var channels : Dictionary = {}
|
||||
var commands : Dictionary = {}
|
||||
var image_cache : ImageCache
|
||||
|
||||
# Required permission to execute the command
|
||||
enum PermissionFlag {
|
||||
EVERYONE = 0,
|
||||
VIP = 1,
|
||||
SUB = 2,
|
||||
MOD = 4,
|
||||
STREAMER = 8,
|
||||
# Mods and the streamer
|
||||
MOD_STREAMER = 12,
|
||||
# Everyone but regular viewers
|
||||
NON_REGULAR = 15
|
||||
}
|
||||
|
||||
# Where the command should be accepted
|
||||
enum WhereFlag {
|
||||
CHAT = 1,
|
||||
WHISPER = 2
|
||||
}
|
||||
|
||||
func _init():
|
||||
websocket.verify_ssl = true
|
||||
user_regex.compile("(?<=!)[\\w]*(?=@)")
|
||||
|
||||
func _ready() -> void:
|
||||
websocket.connect("data_received", self, "data_received")
|
||||
websocket.connect("connection_established", self, "connection_established")
|
||||
websocket.connect("connection_closed", self, "connection_closed")
|
||||
websocket.connect("server_close_request", self, "sever_close_request")
|
||||
websocket.connect("connection_error", self, "connection_error")
|
||||
if(get_images):
|
||||
image_cache = ImageCache.new(disk_cache, disk_cache_path)
|
||||
|
||||
func connect_to_twitch() -> void:
|
||||
if(websocket.connect_to_url("wss://irc-ws.chat.twitch.tv:443") != OK):
|
||||
print_debug("Could not connect to Twitch.")
|
||||
emit_signal("twitch_unavailable")
|
||||
|
||||
func _process(delta : float) -> void:
|
||||
if(websocket.get_connection_status() != NetworkedMultiplayerPeer.CONNECTION_DISCONNECTED):
|
||||
websocket.poll()
|
||||
if (!chat_queue.empty() && (last_msg + chat_timeout_ms) <= OS.get_ticks_msec()):
|
||||
send(chat_queue.pop_front())
|
||||
last_msg = OS.get_ticks_msec()
|
||||
|
||||
# Login using a oauth token.
|
||||
# You will have to either get a oauth token yourself or use
|
||||
# https://twitchapps.com/tokengen/
|
||||
# to generate a token with custom scopes.
|
||||
func authenticate_oauth(nick : String, token : String) -> void:
|
||||
websocket.get_peer(1).set_write_mode(WebSocketPeer.WRITE_MODE_TEXT)
|
||||
send("PASS " + ("" if token.begins_with("oauth:") else "oauth:") + token, true)
|
||||
send("NICK " + nick.to_lower())
|
||||
request_caps()
|
||||
|
||||
func request_caps(caps : String = "twitch.tv/commands twitch.tv/tags twitch.tv/membership") -> void:
|
||||
send("CAP REQ :" + caps)
|
||||
|
||||
# Sends a String to Twitch.
|
||||
func send(text : String, token : bool = false) -> void:
|
||||
websocket.get_peer(1).put_packet(text.to_utf8())
|
||||
if(OS.is_debug_build()):
|
||||
if(!token):
|
||||
print("< " + text.strip_edges(false))
|
||||
else:
|
||||
print("< PASS oauth:******************************")
|
||||
|
||||
# Sends a chat message to a channel. Defaults to the only connected channel.
|
||||
func chat(message : String, channel : String = ""):
|
||||
var keys : Array = channels.keys()
|
||||
if(channel != ""):
|
||||
chat_queue.append("PRIVMSG " + ("" if channel.begins_with("#") else "#") + channel + " :" + message + "\r\n")
|
||||
elif(keys.size() == 1):
|
||||
chat_queue.append("PRIVMSG #" + channels.keys()[0] + " :" + message + "\r\n")
|
||||
else:
|
||||
print_debug("No channel specified.")
|
||||
|
||||
func whisper(message : String, target : String) -> void:
|
||||
chat("/w " + target + " " + message)
|
||||
|
||||
func data_received() -> void:
|
||||
var messages : PoolStringArray = websocket.get_peer(1).get_packet().get_string_from_utf8().strip_edges(false).split("\r\n")
|
||||
var tags = {}
|
||||
for message in messages:
|
||||
if(message.begins_with("@")):
|
||||
var msg : PoolStringArray = message.split(" ", false, 1)
|
||||
message = msg[1]
|
||||
for tag in msg[0].split(";"):
|
||||
var pair = tag.split("=")
|
||||
tags[pair[0]] = pair[1]
|
||||
if(OS.is_debug_build()):
|
||||
print("> " + message)
|
||||
handle_message(message, tags)
|
||||
|
||||
# Registers a command on an object with a func to call, similar to connect(signal, instance, func).
|
||||
func add_command(cmd_name : String, instance : Object, instance_func : String, max_args : int = 0, min_args : int = 0, permission_level : int = PermissionFlag.EVERYONE, where : int = WhereFlag.CHAT) -> void:
|
||||
var func_ref = FuncRef.new()
|
||||
func_ref.set_instance(instance)
|
||||
func_ref.set_function(instance_func)
|
||||
commands[cmd_name] = CommandData.new(func_ref, permission_level, max_args, min_args, where)
|
||||
|
||||
# Removes a single command or alias.
|
||||
func remove_command(cmd_name : String) -> void:
|
||||
commands.erase(cmd_name)
|
||||
|
||||
# Removes a command and all associated aliases.
|
||||
func purge_command(cmd_name : String) -> void:
|
||||
var to_remove = commands.get(cmd_name)
|
||||
if(to_remove):
|
||||
var remove_queue = []
|
||||
for command in commands.keys():
|
||||
if(commands[command].func_ref == to_remove.func_ref):
|
||||
remove_queue.append(command)
|
||||
for queued in remove_queue:
|
||||
commands.erase(queued)
|
||||
|
||||
func add_alias(cmd_name : String, alias : String) -> void:
|
||||
if(commands.has(cmd_name)):
|
||||
commands[alias] = commands.get(cmd_name)
|
||||
|
||||
func add_aliases(cmd_name : String, aliases : PoolStringArray) -> void:
|
||||
for alias in aliases:
|
||||
add_alias(cmd_name, alias)
|
||||
|
||||
func handle_message(message : String, tags : Dictionary) -> void:
|
||||
if(message == ":tmi.twitch.tv NOTICE * :Login authentication failed"):
|
||||
print_debug("Authentication failed.")
|
||||
emit_signal("login_attempt", false)
|
||||
return
|
||||
if(message == "PING :tmi.twitch.tv"):
|
||||
send("PONG :tmi.twitch.tv")
|
||||
emit_signal("pong")
|
||||
return
|
||||
var msg : PoolStringArray = message.split(" ", true, 3)
|
||||
match msg[1]:
|
||||
"001":
|
||||
print_debug("Authentication successful.")
|
||||
emit_signal("login_attempt", true)
|
||||
"PRIVMSG":
|
||||
var sender_data : SenderData = SenderData.new(user_regex.search(msg[0]).get_string(), msg[2], tags)
|
||||
handle_command(sender_data, msg[3].split(" ", true, 1))
|
||||
emit_signal("chat_message", sender_data, msg[3].right(1))
|
||||
"WHISPER":
|
||||
var sender_data : SenderData = SenderData.new(user_regex.search(msg[0]).get_string(), msg[2], tags)
|
||||
handle_command(sender_data, msg[3].split(" ", true, 1), true)
|
||||
emit_signal("whisper_message", sender_data, msg[3].right(1))
|
||||
"RECONNECT":
|
||||
twitch_restarting = true
|
||||
_:
|
||||
emit_signal("unhandled_message", message, tags)
|
||||
|
||||
func handle_command(sender_data : SenderData, msg : PoolStringArray, whisper : bool = false) -> void:
|
||||
if(command_prefixes.has(msg[0].substr(1, 1))):
|
||||
var command : String = msg[0].right(2)
|
||||
var cmd_data : CommandData = commands.get(command)
|
||||
if(cmd_data):
|
||||
if(whisper == true && cmd_data.where & WhereFlag.WHISPER != WhereFlag.WHISPER):
|
||||
return
|
||||
elif(whisper == false && cmd_data.where & WhereFlag.CHAT != WhereFlag.CHAT):
|
||||
return
|
||||
var args = "" if msg.size() == 1 else msg[1]
|
||||
var arg_ary : PoolStringArray = PoolStringArray() if args == "" else args.split(" ")
|
||||
if(arg_ary.size() > cmd_data.max_args && cmd_data.max_args != -1 || arg_ary.size() < cmd_data.min_args):
|
||||
emit_signal("cmd_invalid_argcount", command, sender_data, cmd_data, arg_ary)
|
||||
print_debug("Invalid argcount!")
|
||||
return
|
||||
if(cmd_data.permission_level != 0):
|
||||
var user_perm_flags = get_perm_flag_from_tags(sender_data.tags)
|
||||
if(user_perm_flags & cmd_data.permission_level != cmd_data.permission_level):
|
||||
emit_signal("cmd_no_permission", command, sender_data, cmd_data, arg_ary)
|
||||
print_debug("No Permission for command!")
|
||||
return
|
||||
if(arg_ary.size() == 0):
|
||||
cmd_data.func_ref.call_func(CommandInfo.new(sender_data, command, whisper))
|
||||
else:
|
||||
cmd_data.func_ref.call_func(CommandInfo.new(sender_data, command, whisper), arg_ary)
|
||||
|
||||
func get_perm_flag_from_tags(tags : Dictionary) -> int:
|
||||
var flag = 0
|
||||
var entry = tags.get("badges")
|
||||
if(entry):
|
||||
for badge in entry.split(","):
|
||||
if(badge.begins_with("vip")):
|
||||
flag += PermissionFlag.VIP
|
||||
if(badge.begins_with("broadcaster")):
|
||||
flag += PermissionFlag.STREAMER
|
||||
entry = tags.get("mod")
|
||||
if(entry):
|
||||
if(entry == "1"):
|
||||
flag += PermissionFlag.MOD
|
||||
entry = tags.get("subscriber")
|
||||
if(entry):
|
||||
if(entry == "1"):
|
||||
flag += PermissionFlag.SUB
|
||||
return flag
|
||||
|
||||
func join_channel(channel : String) -> void:
|
||||
var lower_channel : String = channel.to_lower()
|
||||
send("JOIN #" + lower_channel)
|
||||
channels[lower_channel] = {}
|
||||
|
||||
func leave_channel(channel : String) -> void:
|
||||
var lower_channel : String = channel.to_lower()
|
||||
send("PART #" + lower_channel)
|
||||
channels.erase(lower_channel)
|
||||
|
||||
func connection_established(protocol : String) -> void:
|
||||
print_debug("Connected to Twitch.")
|
||||
emit_signal("twitch_connected")
|
||||
|
||||
func connection_closed(was_clean_close : bool) -> void:
|
||||
if(twitch_restarting):
|
||||
print_debug("Reconnecting to Twitch")
|
||||
emit_signal("twitch_reconnect")
|
||||
connect_to_twitch()
|
||||
yield(self, "twitch_connected")
|
||||
for channel in channels.keys():
|
||||
join_channel(channel)
|
||||
twitch_restarting = false
|
||||
else:
|
||||
print_debug("Disconnected from Twitch.")
|
||||
emit_signal("twitch_disconnected")
|
||||
|
||||
func connection_error() -> void:
|
||||
print_debug("Twitch is unavailable.")
|
||||
emit_signal("twitch_unavailable")
|
||||
|
||||
func server_close_request(code : int, reason : String) -> void:
|
||||
pass
|
BIN
addons/gift/icon.png
Executable file
BIN
addons/gift/icon.png
Executable file
Binary file not shown.
After Width: | Height: | Size: 188 B |
34
addons/gift/icon.png.import
Normal file
34
addons/gift/icon.png.import
Normal file
@ -0,0 +1,34 @@
|
||||
[remap]
|
||||
|
||||
importer="texture"
|
||||
type="StreamTexture"
|
||||
path="res://.import/icon.png-b5cf707f4ba91fefa5df60a746e02900.stex"
|
||||
metadata={
|
||||
"vram_texture": false
|
||||
}
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://addons/gift/icon.png"
|
||||
dest_files=[ "res://.import/icon.png-b5cf707f4ba91fefa5df60a746e02900.stex" ]
|
||||
|
||||
[params]
|
||||
|
||||
compress/mode=0
|
||||
compress/lossy_quality=0.7
|
||||
compress/hdr_mode=0
|
||||
compress/bptc_ldr=0
|
||||
compress/normal_map=0
|
||||
flags/repeat=0
|
||||
flags/filter=true
|
||||
flags/mipmaps=false
|
||||
flags/anisotropic=false
|
||||
flags/srgb=2
|
||||
process/fix_alpha_border=true
|
||||
process/premult_alpha=false
|
||||
process/HDR_as_SRGB=false
|
||||
process/invert_color=false
|
||||
stream=false
|
||||
size_limit=0
|
||||
detect_3d=true
|
||||
svg/scale=1.0
|
@ -1,86 +0,0 @@
|
||||
class_name TwitchIconDownloader
|
||||
extends RefCounted
|
||||
|
||||
signal fetched(texture)
|
||||
|
||||
var api : TwitchAPIConnection
|
||||
|
||||
const JTVNW_URL : String = "https://static-cdn.jtvnw.net"
|
||||
|
||||
var jtvnw_client : HTTPClient = HTTPClient.new()
|
||||
var jtvnw_response : PackedByteArray = []
|
||||
var jtvnw_queue : Array[String] = []
|
||||
|
||||
var cached_badges : Dictionary = {}
|
||||
|
||||
var disk_cache : bool
|
||||
|
||||
func _init(twitch_api : TwitchAPIConnection, disk_cache_enabled : bool = false) -> void:
|
||||
api = twitch_api
|
||||
api.id_conn.polled.connect(poll)
|
||||
disk_cache = disk_cache_enabled
|
||||
jtvnw_client.connect_to_host(JTVNW_URL)
|
||||
|
||||
func poll() -> void:
|
||||
jtvnw_client.poll()
|
||||
var conn_status : HTTPClient.Status = jtvnw_client.get_status()
|
||||
if (conn_status == HTTPClient.STATUS_BODY):
|
||||
jtvnw_response += jtvnw_client.read_response_body_chunk()
|
||||
elif (!jtvnw_response.is_empty()):
|
||||
var img := Image.new()
|
||||
img.load_png_from_buffer(jtvnw_response)
|
||||
jtvnw_response.clear()
|
||||
var path = jtvnw_queue.pop_front()
|
||||
var texture : ImageTexture = ImageTexture.new()
|
||||
texture.set_image(img)
|
||||
texture.take_over_path(path)
|
||||
fetched.emit(texture)
|
||||
elif (!jtvnw_queue.is_empty()):
|
||||
if (conn_status == HTTPClient.STATUS_CONNECTED):
|
||||
jtvnw_client.request(HTTPClient.METHOD_GET, jtvnw_queue.front(), ["Accept: image/png"])
|
||||
elif (conn_status == HTTPClient.STATUS_DISCONNECTED || conn_status == HTTPClient.STATUS_CONNECTION_ERROR):
|
||||
jtvnw_client.connect_to_host(JTVNW_URL)
|
||||
|
||||
func get_badge(badge_id : String, channel_id : String = "_global", scale : String = "1x") -> Texture2D:
|
||||
var badge_data : PackedStringArray = badge_id.split("/", true, 1)
|
||||
if (!cached_badges.has(channel_id)):
|
||||
if (channel_id == "_global"):
|
||||
cache_badges(await(api.get_global_chat_badges()), channel_id)
|
||||
else:
|
||||
cache_badges(await(api.get_channel_chat_badges(channel_id)), channel_id)
|
||||
if (channel_id != "_global" && !cached_badges[channel_id].has(badge_data[0])):
|
||||
return await(get_badge(badge_id, "_global", scale))
|
||||
var path : String = cached_badges[channel_id][badge_data[0]]["versions"][badge_data[1]]["image_url_%s" % scale].substr(JTVNW_URL.length())
|
||||
if ResourceLoader.has_cached(path):
|
||||
return load(path)
|
||||
else:
|
||||
jtvnw_queue.append(path)
|
||||
var filepath : String = "user://badges/%s/%s_%s_%s.png" % [channel_id, badge_data[0], badge_data[1], scale]
|
||||
return await(wait_for_fetched(path, filepath))
|
||||
|
||||
func get_emote(emote_id : String, dark : bool = true, scale : String = "1.0") -> Texture2D:
|
||||
var path : String = "/emoticons/v2/%s/static/%s/%s" % [emote_id, "dark" if dark else "light", scale]
|
||||
if ResourceLoader.has_cached(path):
|
||||
return load(path)
|
||||
else:
|
||||
var filepath : String = "user://emotes/%s.png" % emote_id
|
||||
jtvnw_queue.append(path)
|
||||
return await(wait_for_fetched(path, filepath))
|
||||
|
||||
func cache_badges(result, channel_id) -> void:
|
||||
cached_badges[channel_id] = result
|
||||
var mappings : Dictionary = {}
|
||||
var badges : Array = cached_badges[channel_id]["data"]
|
||||
for entry in badges:
|
||||
if (!mappings.has(entry["set_id"])):
|
||||
mappings[entry["set_id"]] = {"versions" : {}}
|
||||
for version in entry["versions"]:
|
||||
mappings[entry["set_id"]]["versions"][version["id"]] = version
|
||||
cached_badges[channel_id] = mappings
|
||||
|
||||
func wait_for_fetched(path : String, filepath : String) -> ImageTexture:
|
||||
var last_fetched : ImageTexture = null
|
||||
while (last_fetched == null || last_fetched.resource_path != path):
|
||||
last_fetched = await(fetched)
|
||||
last_fetched.take_over_path(path)
|
||||
return load(path)
|
@ -1,66 +0,0 @@
|
||||
class_name TwitchIDConnection
|
||||
extends RefCounted
|
||||
|
||||
|
||||
signal polled
|
||||
signal token_invalid
|
||||
signal token_refreshed(success)
|
||||
|
||||
const ONE_HOUR_MS = 3600000
|
||||
|
||||
var last_token : TwitchToken
|
||||
|
||||
var id_client : HTTPClient = HTTPClient.new()
|
||||
var id_client_response : PackedByteArray = []
|
||||
|
||||
var next_check : int = 0
|
||||
|
||||
func _init(token : TwitchToken) -> void:
|
||||
last_token = token
|
||||
if (last_token.fresh):
|
||||
next_check += ONE_HOUR_MS
|
||||
id_client.connect_to_host("https://id.twitch.tv", -1, TLSOptions.client())
|
||||
|
||||
func poll() -> void:
|
||||
if (id_client != null):
|
||||
id_client.poll()
|
||||
if (id_client.get_status() == HTTPClient.STATUS_CONNECTED):
|
||||
if (!id_client_response.is_empty()):
|
||||
var response = JSON.parse_string(id_client_response.get_string_from_utf8())
|
||||
if (response.has("status") && (response["status"] == 401 || response["status"] == 400)):
|
||||
print("Token is invalid. Aborting.")
|
||||
token_invalid.emit()
|
||||
token_refreshed.emit(false)
|
||||
else:
|
||||
last_token.token = response.get("access_token", last_token.token)
|
||||
last_token.expires_in = response.get("expires_in", last_token.expires_in)
|
||||
if last_token is RefreshableUserAccessToken:
|
||||
last_token.refresh_token = response.get("refresh_token", last_token.refresh_token)
|
||||
token_refreshed.emit(true)
|
||||
if last_token is AppAccessToken:
|
||||
token_refreshed.emit(true)
|
||||
id_client_response.clear()
|
||||
if (next_check <= Time.get_ticks_msec()):
|
||||
check_token()
|
||||
next_check += ONE_HOUR_MS
|
||||
elif (id_client.get_status() == HTTPClient.STATUS_BODY):
|
||||
id_client_response += id_client.read_response_body_chunk()
|
||||
polled.emit()
|
||||
|
||||
func check_token() -> void:
|
||||
id_client.request(HTTPClient.METHOD_GET, "/oauth2/validate", ["Authorization: OAuth %s" % last_token.token])
|
||||
print("Validating token...")
|
||||
|
||||
func refresh_token() -> void:
|
||||
if (last_token is RefreshableUserAccessToken):
|
||||
id_client.request(HTTPClient.METHOD_GET, "/oauth2/token", ["Content-Type: application/x-www-form-urlencoded"], "grant_type=refresh_token&refresh_token=%s&client_id=%s&client_secret=%s" % [last_token.refresh_token, last_token.last_client_id, last_token.last_client_secret])
|
||||
elif (last_token is UserAccessToken):
|
||||
var auth : ImplicitGrantFlow = ImplicitGrantFlow.new()
|
||||
polled.connect(auth.poll)
|
||||
var last_token = await(auth.login(last_token.last_client_id, last_token.scopes))
|
||||
token_refreshed.emit(true)
|
||||
else:
|
||||
id_client.request(HTTPClient.METHOD_POST, "/oauth2/token", ["Content-Type: application/x-www-form-urlencoded"], "client_id=%s&client_secret=%s&grant_type=client_credentials" % [last_token.client_id, last_token.client_secret])
|
||||
if (last_token == null):
|
||||
print("Please check if you have all required scopes.")
|
||||
token_refreshed.emit(false)
|
@ -1,192 +0,0 @@
|
||||
class_name TwitchIRCConnection
|
||||
extends RefCounted
|
||||
|
||||
signal connection_state_changed(state)
|
||||
signal chat_message(sender_data, message)
|
||||
signal whisper_message(sender_data, message)
|
||||
signal channel_data_received(room)
|
||||
signal login_attempt(success)
|
||||
|
||||
signal unhandled_message(message, tags)
|
||||
|
||||
enum ConnectionState {
|
||||
DISCONNECTED,
|
||||
CONNECTED,
|
||||
CONNECTION_FAILED,
|
||||
RECONNECTING
|
||||
}
|
||||
|
||||
var connection_state : ConnectionState = ConnectionState.DISCONNECTED:
|
||||
set(new_state):
|
||||
connection_state = new_state
|
||||
connection_state_changed.emit(new_state)
|
||||
|
||||
var websocket : WebSocketPeer
|
||||
# Timestamp of the last message sent.
|
||||
var last_msg : int = Time.get_ticks_msec()
|
||||
# Time to wait in msec after each sent chat message. Values below ~310 might lead to a disconnect after 100 messages.
|
||||
var chat_timeout_ms : int = 320
|
||||
# Twitch disconnects connected clients if too many chat messages are being sent. (At about 100 messages/30s).
|
||||
# This queue makes sure messages aren't sent too quickly.
|
||||
var chat_queue : Array[String] = []
|
||||
# Mapping of channels to their channel info, like available badges.
|
||||
var channels : Dictionary = {}
|
||||
# Last Userstate of the bot for channels. Contains <channel_name> -> <userstate_dictionary> entries.
|
||||
var last_state : Dictionary = {}
|
||||
var user_regex : RegEx = RegEx.create_from_string("(?<=!)[\\w]*(?=@)")
|
||||
|
||||
var id : TwitchIDConnection
|
||||
|
||||
var last_username : String
|
||||
var last_token : UserAccessToken
|
||||
var last_caps : PackedStringArray
|
||||
|
||||
func _init(twitch_id_connection : TwitchIDConnection) -> void:
|
||||
id = twitch_id_connection
|
||||
id.polled.connect(poll)
|
||||
|
||||
# Connect to Twitch IRC. Returns true on success, false if connection fails.
|
||||
func connect_to_irc(username : String) -> bool:
|
||||
last_username = username
|
||||
websocket = WebSocketPeer.new()
|
||||
websocket.connect_to_url("wss://irc-ws.chat.twitch.tv:443")
|
||||
print("Connecting to Twitch IRC.")
|
||||
if (await(connection_state_changed) != ConnectionState.CONNECTED):
|
||||
return false
|
||||
send("PASS oauth:%s" % id.last_token.token, true)
|
||||
send("NICK " + username.to_lower())
|
||||
if (await(login_attempt)):
|
||||
print("Connected.")
|
||||
return true
|
||||
return false
|
||||
|
||||
func poll() -> void:
|
||||
if (websocket != null && connection_state != ConnectionState.CONNECTION_FAILED && connection_state != ConnectionState.RECONNECTING):
|
||||
websocket.poll()
|
||||
var state := websocket.get_ready_state()
|
||||
match state:
|
||||
WebSocketPeer.STATE_OPEN:
|
||||
if (connection_state == ConnectionState.DISCONNECTED):
|
||||
connection_state = ConnectionState.CONNECTED
|
||||
print("Connected to Twitch.")
|
||||
else:
|
||||
while (websocket.get_available_packet_count()):
|
||||
data_received(websocket.get_packet())
|
||||
if (!chat_queue.is_empty() && (last_msg + chat_timeout_ms) <= Time.get_ticks_msec()):
|
||||
send(chat_queue.pop_front())
|
||||
last_msg = Time.get_ticks_msec()
|
||||
WebSocketPeer.STATE_CLOSED:
|
||||
if (connection_state == ConnectionState.DISCONNECTED):
|
||||
print("Could not connect to Twitch.")
|
||||
connection_state = ConnectionState.CONNECTION_FAILED
|
||||
elif(connection_state == ConnectionState.RECONNECTING):
|
||||
print("Reconnecting to Twitch...")
|
||||
await(reconnect())
|
||||
else:
|
||||
connection_state = ConnectionState.DISCONNECTED
|
||||
print("Disconnected from Twitch. [%s]: %s"%[websocket.get_close_code(), websocket.get_close_reason()])
|
||||
|
||||
func data_received(data : PackedByteArray) -> void:
|
||||
var messages : PackedStringArray = data.get_string_from_utf8().strip_edges(false).split("\r\n")
|
||||
var tags = {}
|
||||
for message in messages:
|
||||
if(message.begins_with("@")):
|
||||
var msg : PackedStringArray = message.split(" ", false, 1)
|
||||
message = msg[1]
|
||||
for tag in msg[0].split(";"):
|
||||
var pair = tag.split("=")
|
||||
tags[pair[0]] = pair[1]
|
||||
if (OS.is_debug_build()):
|
||||
print("> " + message)
|
||||
handle_message(message, tags)
|
||||
|
||||
# Sends a String to Twitch.
|
||||
func send(text : String, token : bool = false) -> void:
|
||||
websocket.send_text(text)
|
||||
if(OS.is_debug_build()):
|
||||
if(!token):
|
||||
print("< " + text.strip_edges(false))
|
||||
else:
|
||||
print("< PASS oauth:******************************")
|
||||
|
||||
# Request capabilities from twitch.
|
||||
func request_capabilities(caps : PackedStringArray = ["twitch.tv/commands", "twitch.tv/tags"]) -> void:
|
||||
last_caps = caps
|
||||
send("CAP REQ :" + " ".join(caps))
|
||||
|
||||
# Sends a chat message to a channel. Defaults to the only connected channel.
|
||||
func chat(message : String, channel : String = ""):
|
||||
var keys : Array = channels.keys()
|
||||
if(channel != ""):
|
||||
if (channel.begins_with("#")):
|
||||
channel = channel.right(-1)
|
||||
chat_queue.append("PRIVMSG #" + channel + " :" + message + "\r\n")
|
||||
if (last_state.has(channel)):
|
||||
chat_message.emit(SenderData.new(last_state[channel]["display-name"], channel, last_state[channels.keys()[0]]), message)
|
||||
elif(keys.size() == 1):
|
||||
chat_queue.append("PRIVMSG #" + channels.keys()[0] + " :" + message + "\r\n")
|
||||
if (last_state.has(channels.keys()[0])):
|
||||
chat_message.emit(SenderData.new(last_state[channels.keys()[0]]["display-name"], channels.keys()[0], last_state[channels.keys()[0]]), message)
|
||||
else:
|
||||
print("No channel specified.")
|
||||
|
||||
func handle_message(message : String, tags : Dictionary) -> void:
|
||||
if(message == "PING :tmi.twitch.tv"):
|
||||
send("PONG :tmi.twitch.tv")
|
||||
return
|
||||
var msg : PackedStringArray = message.split(" ", true, 3)
|
||||
match msg[1]:
|
||||
"NOTICE":
|
||||
var info : String = msg[3].right(-1)
|
||||
if (info == "Login authentication failed" || info == "Login unsuccessful"):
|
||||
print("Authentication failed.")
|
||||
login_attempt.emit(false)
|
||||
elif (info == "You don't have permission to perform that action"):
|
||||
print("No permission. Attempting to obtain new token.")
|
||||
id.refresh_token()
|
||||
var success : bool = await(id.token_refreshed)
|
||||
if (!success):
|
||||
print("Please check if you have all required scopes.")
|
||||
websocket.close(1000, "Token became invalid.")
|
||||
return
|
||||
connection_state = ConnectionState.RECONNECTING
|
||||
else:
|
||||
unhandled_message.emit(message, tags)
|
||||
"001":
|
||||
print("Authentication successful.")
|
||||
login_attempt.emit(true)
|
||||
"PRIVMSG":
|
||||
var sender_data : SenderData = SenderData.new(user_regex.search(msg[0]).get_string(), msg[2], tags)
|
||||
chat_message.emit(sender_data, msg[3].right(-1))
|
||||
"WHISPER":
|
||||
var sender_data : SenderData = SenderData.new(user_regex.search(msg[0]).get_string(), msg[2], tags)
|
||||
whisper_message.emit(sender_data, msg[3].right(-1))
|
||||
"RECONNECT":
|
||||
connection_state = ConnectionState.RECONNECTING
|
||||
"USERSTATE", "ROOMSTATE":
|
||||
var room = msg[2].right(-1)
|
||||
if (!last_state.has(room)):
|
||||
last_state[room] = tags
|
||||
channel_data_received.emit(room)
|
||||
else:
|
||||
for key in tags:
|
||||
last_state[room][key] = tags[key]
|
||||
_:
|
||||
unhandled_message.emit(message, tags)
|
||||
|
||||
func join_channel(channel : String) -> void:
|
||||
var lower_channel : String = channel.to_lower()
|
||||
channels[lower_channel] = {}
|
||||
send("JOIN #" + lower_channel)
|
||||
|
||||
func leave_channel(channel : String) -> void:
|
||||
var lower_channel : String = channel.to_lower()
|
||||
send("PART #" + lower_channel)
|
||||
channels.erase(lower_channel)
|
||||
|
||||
func reconnect() -> void:
|
||||
if(await(connect_to_irc(last_username))):
|
||||
request_capabilities(last_caps)
|
||||
for channel in channels.keys():
|
||||
join_channel(channel)
|
||||
connection_state = ConnectionState.CONNECTED
|
BIN
addons/gift/placeholder.png
Normal file
BIN
addons/gift/placeholder.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 90 B |
13
addons/gift/placeholder.png.import
Normal file
13
addons/gift/placeholder.png.import
Normal file
@ -0,0 +1,13 @@
|
||||
[remap]
|
||||
|
||||
importer="image"
|
||||
type="Image"
|
||||
path="res://.import/placeholder.png-7d8d01cafa2d5188ea51e03e3fda7124.image"
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://addons/gift/placeholder.png"
|
||||
dest_files=[ "res://.import/placeholder.png-7d8d01cafa2d5188ea51e03e3fda7124.image" ]
|
||||
|
||||
[params]
|
||||
|
7
addons/gift/plugin.cfg
Executable file
7
addons/gift/plugin.cfg
Executable file
@ -0,0 +1,7 @@
|
||||
[plugin]
|
||||
|
||||
name="Godot IRC For Twitch"
|
||||
description="Godot websocket implementation for Twitch IRC."
|
||||
author="MennoMax"
|
||||
version="1.0.1"
|
||||
script="gift.gd"
|
@ -1,15 +1,16 @@
|
||||
extends Reference
|
||||
class_name CommandData
|
||||
extends RefCounted
|
||||
|
||||
var func_ref : Callable
|
||||
var func_ref : FuncRef
|
||||
var permission_level : int
|
||||
var max_args : int
|
||||
var min_args : int
|
||||
var where : int
|
||||
|
||||
func _init(f_ref : Callable, perm_lvl : int, mx_args : int, mn_args : int, whr : int):
|
||||
func _init(f_ref : FuncRef, perm_lvl : int, mx_args : int, mn_args : int, whr : int):
|
||||
func_ref = f_ref
|
||||
permission_level = perm_lvl
|
||||
max_args = mx_args
|
||||
min_args = mn_args
|
||||
where = whr
|
||||
|
||||
|
@ -1,11 +1,12 @@
|
||||
extends Reference
|
||||
class_name CommandInfo
|
||||
extends RefCounted
|
||||
|
||||
var sender_data : SenderData
|
||||
var command : String
|
||||
var whisper : bool
|
||||
|
||||
func _init(sndr_dt : SenderData, cmd : String, whspr : bool):
|
||||
func _init(sndr_dt, cmd, whspr):
|
||||
sender_data = sndr_dt
|
||||
command = cmd
|
||||
whisper = whspr
|
||||
|
||||
|
195
addons/gift/util/image_cache.gd
Normal file
195
addons/gift/util/image_cache.gd
Normal file
@ -0,0 +1,195 @@
|
||||
extends Resource
|
||||
class_name ImageCache
|
||||
|
||||
enum RequestType {
|
||||
EMOTE,
|
||||
BADGE,
|
||||
BADGE_MAPPING
|
||||
}
|
||||
|
||||
var caches := {
|
||||
RequestType.EMOTE: {},
|
||||
RequestType.BADGE: {},
|
||||
RequestType.BADGE_MAPPING: {}
|
||||
}
|
||||
|
||||
var queue := []
|
||||
var thread := Thread.new()
|
||||
var mutex := Mutex.new()
|
||||
var active = true
|
||||
var http_client := HTTPClient.new()
|
||||
var host : String
|
||||
|
||||
var file : File = File.new()
|
||||
var dir : Directory = Directory.new()
|
||||
var cache_path : String
|
||||
var disk_cache : bool
|
||||
|
||||
const HEADERS : PoolStringArray = PoolStringArray([
|
||||
"User-Agent: GIFT/1.0 (Godot Engine)",
|
||||
"Accept: */*"
|
||||
])
|
||||
|
||||
func _init(do_disk_cache : bool, cache_path : String) -> void:
|
||||
self.disk_cache = do_disk_cache
|
||||
self.cache_path = cache_path
|
||||
thread.start(self, "start")
|
||||
|
||||
func start(params) -> void:
|
||||
var f : File = File.new()
|
||||
var d : Directory = Directory.new()
|
||||
if (disk_cache):
|
||||
for type in caches.keys():
|
||||
var cache_dir = RequestType.keys()[type]
|
||||
caches[cache_dir] = {}
|
||||
var error := d.make_dir_recursive(cache_path + "/" + cache_dir)
|
||||
while active:
|
||||
if (!queue.empty()):
|
||||
mutex.lock()
|
||||
var entry : Entry = queue.pop_front()
|
||||
mutex.unlock()
|
||||
var buffer : PoolByteArray = http_request(entry.path, entry.type)
|
||||
if (disk_cache):
|
||||
if !d.dir_exists(entry.filename.get_base_dir()):
|
||||
d.make_dir(entry.filename.get_base_dir())
|
||||
f.open(entry.filename, File.WRITE)
|
||||
f.store_buffer(buffer)
|
||||
f.close()
|
||||
var texture = ImageTexture.new()
|
||||
var img : Image = Image.new()
|
||||
img.load_png_from_buffer(buffer)
|
||||
if entry.type == RequestType.BADGE:
|
||||
caches[RequestType.BADGE][entry.data[0]][entry.data[1]].create_from_image(img, 0)
|
||||
elif entry.type == RequestType.EMOTE:
|
||||
caches[RequestType.EMOTE][entry.data[0]].create_from_image(img, 0)
|
||||
yield(Engine.get_main_loop(), "idle_frame")
|
||||
|
||||
# Gets badge mappings for the specified channel. Default: _global (global mappings)
|
||||
func get_badge_mapping(channel_id : String = "_global") -> Dictionary:
|
||||
if !caches[RequestType.BADGE_MAPPING].has(channel_id):
|
||||
var filename : String = cache_path + "/" + RequestType.keys()[RequestType.BADGE_MAPPING] + "/" + channel_id + ".json"
|
||||
if !disk_cache && file.file_exists(filename):
|
||||
file.open(filename, File.READ)
|
||||
caches[RequestType.BADGE_MAPPING][channel_id] = parse_json(file.get_as_text())["badge_sets"]
|
||||
file.close()
|
||||
var buffer : PoolByteArray = http_request(channel_id, RequestType.BADGE_MAPPING)
|
||||
if !buffer.empty():
|
||||
caches[RequestType.BADGE_MAPPING][channel_id] = parse_json(buffer.get_string_from_utf8())["badge_sets"]
|
||||
if (disk_cache):
|
||||
file.open(filename, File.WRITE)
|
||||
file.store_buffer(buffer)
|
||||
file.close()
|
||||
else:
|
||||
return {}
|
||||
return caches[RequestType.BADGE_MAPPING][channel_id]
|
||||
|
||||
func get_badge(badge_name : String, channel_id : String = "_global", scale : String = "1") -> ImageTexture:
|
||||
var badge_data : PoolStringArray = badge_name.split("/", true, 1)
|
||||
var texture : ImageTexture = ImageTexture.new()
|
||||
var cachename = badge_data[0] + "_" + badge_data[1] + "_" + scale
|
||||
var filename : String = cache_path + "/" + RequestType.keys()[RequestType.BADGE] + "/" + channel_id + "/" + cachename + ".png"
|
||||
if !caches[RequestType.BADGE].has(channel_id):
|
||||
caches[RequestType.BADGE][channel_id] = {}
|
||||
if !caches[RequestType.BADGE][channel_id].has(cachename):
|
||||
if !disk_cache && file.file_exists(filename):
|
||||
file.open(filename, File.READ)
|
||||
var img : Image = Image.new()
|
||||
img.load_png_from_buffer(file.get_buffer(file.get_len()))
|
||||
texture.create_from_image(img)
|
||||
file.close()
|
||||
else:
|
||||
var map : Dictionary = caches[RequestType.BADGE_MAPPING].get(channel_id, get_badge_mapping(channel_id))
|
||||
if !map.empty():
|
||||
if map.has(badge_data[0]):
|
||||
mutex.lock()
|
||||
queue.append(Entry.new(map[badge_data[0]]["versions"][badge_data[1]]["image_url_" + scale + "x"].substr("https://static-cdn.jtvnw.net/badges/v1/".length()), RequestType.BADGE, filename, [channel_id, cachename]))
|
||||
mutex.unlock()
|
||||
var img = preload("res://addons/gift/placeholder.png")
|
||||
texture.create_from_image(img)
|
||||
elif channel_id != "_global":
|
||||
return get_badge(badge_name, "_global", scale)
|
||||
elif channel_id != "_global":
|
||||
return get_badge(badge_name, "_global", scale)
|
||||
texture.take_over_path(filename)
|
||||
caches[RequestType.BADGE][channel_id][cachename] = texture
|
||||
return caches[RequestType.BADGE][channel_id][cachename]
|
||||
|
||||
func get_emote(emote_id : String, scale = "1.0") -> ImageTexture:
|
||||
var texture : ImageTexture = ImageTexture.new()
|
||||
var cachename : String = emote_id + "_" + scale
|
||||
var filename : String = cache_path + "/" + RequestType.keys()[RequestType.EMOTE] + "/" + cachename + ".png"
|
||||
if !caches[RequestType.EMOTE].has(cachename):
|
||||
if !disk_cache && file.file_exists(filename):
|
||||
file.open(filename, File.READ)
|
||||
var img : Image = Image.new()
|
||||
img.load_png_from_buffer(file.get_buffer(file.get_len()))
|
||||
texture.create_from_image(img)
|
||||
file.close()
|
||||
else:
|
||||
mutex.lock()
|
||||
queue.append(Entry.new(emote_id + "/" + scale, RequestType.EMOTE, filename, [cachename]))
|
||||
mutex.unlock()
|
||||
var img = preload("res://addons/gift/placeholder.png")
|
||||
texture.create_from_image(img)
|
||||
texture.take_over_path(filename)
|
||||
caches[RequestType.EMOTE][cachename] = texture
|
||||
return caches[RequestType.EMOTE][cachename]
|
||||
|
||||
func http_request(path : String, type : int) -> PoolByteArray:
|
||||
var error := 0
|
||||
var buffer = PoolByteArray()
|
||||
var new_host : String
|
||||
match type:
|
||||
RequestType.BADGE_MAPPING:
|
||||
new_host = "badges.twitch.tv"
|
||||
path = "/v1/badges/" + ("global" if path == "_global" else "channels/" + path) + "/display"
|
||||
RequestType.BADGE, RequestType.EMOTE:
|
||||
new_host = "static-cdn.jtvnw.net"
|
||||
if type == RequestType.BADGE:
|
||||
path = "/badges/v1/" + path
|
||||
else:
|
||||
path = "/emoticons/v1/" + path
|
||||
if (host != new_host):
|
||||
error = http_client.connect_to_host(new_host, 443, true)
|
||||
while http_client.get_status() == HTTPClient.STATUS_CONNECTING or http_client.get_status() == HTTPClient.STATUS_RESOLVING:
|
||||
http_client.poll()
|
||||
delay(100)
|
||||
if (error != OK):
|
||||
print("Could not connect to " + new_host + ". Images disabled.")
|
||||
active = false
|
||||
return buffer
|
||||
host = new_host
|
||||
http_client.request(HTTPClient.METHOD_GET, path, HEADERS)
|
||||
while (http_client.get_status() == HTTPClient.STATUS_REQUESTING):
|
||||
http_client.poll()
|
||||
delay(50)
|
||||
if !(http_client.get_status() == HTTPClient.STATUS_BODY or http_client.get_status() == HTTPClient.STATUS_CONNECTED):
|
||||
print("Request failed. Skipped " + path + " (" + RequestType.keys()[type] + ")")
|
||||
return buffer
|
||||
while (http_client.get_status() == HTTPClient.STATUS_BODY):
|
||||
http_client.poll()
|
||||
delay(1)
|
||||
var chunk = http_client.read_response_body_chunk()
|
||||
if (chunk.size() == 0):
|
||||
delay(1)
|
||||
else:
|
||||
buffer += chunk
|
||||
return buffer
|
||||
|
||||
func delay(delay : int):
|
||||
if (OS.has_feature("web")):
|
||||
yield(Engine.get_main_loop(), "idle_frame")
|
||||
else:
|
||||
OS.delay_msec(delay)
|
||||
|
||||
class Entry extends Reference:
|
||||
var path : String
|
||||
var type : int
|
||||
var filename : String
|
||||
var data : Array
|
||||
|
||||
func _init(path : String, type : int, filename : String, data : Array):
|
||||
self.path = path
|
||||
self.type = type
|
||||
self.filename = filename
|
||||
self.data = data
|
@ -1,5 +1,5 @@
|
||||
extends Reference
|
||||
class_name SenderData
|
||||
extends RefCounted
|
||||
|
||||
var user : String
|
||||
var channel : String
|
||||
|
7
default_env.tres
Normal file
7
default_env.tres
Normal file
@ -0,0 +1,7 @@
|
||||
[gd_resource type="Environment" load_steps=2 format=2]
|
||||
|
||||
[sub_resource type="ProceduralSky" id=1]
|
||||
|
||||
[resource]
|
||||
background_mode = 2
|
||||
background_sky = SubResource( 1 )
|
@ -1,156 +0,0 @@
|
||||
extends Control
|
||||
|
||||
# Your client id. You can share this publicly. Default is my own client_id.
|
||||
# Please do not ship your project with my client_id, but feel free to test with it.
|
||||
# Visit https://dev.twitch.tv/console/apps/create to create a new application.
|
||||
# You can then find your client id at the bottom of the application console.
|
||||
# DO NOT SHARE THE CLIENT SECRET. If you do, regenerate it.
|
||||
@export var client_id : String = "9x951o0nd03na7moohwetpjjtds0or"
|
||||
# The name of the channel we want to connect to.
|
||||
@export var channel : String
|
||||
# The username of the bot account.
|
||||
@export var username : String
|
||||
|
||||
var id : TwitchIDConnection
|
||||
var api : TwitchAPIConnection
|
||||
var irc : TwitchIRCConnection
|
||||
var eventsub : TwitchEventSubConnection
|
||||
|
||||
var cmd_handler : GIFTCommandHandler = GIFTCommandHandler.new()
|
||||
|
||||
var iconloader : TwitchIconDownloader
|
||||
|
||||
func _ready() -> void:
|
||||
# We will login using the Implicit Grant Flow, which only requires a client_id.
|
||||
# Alternatively, you can use the Authorization Code Grant Flow or the Client Credentials Grant Flow.
|
||||
# Note that the Client Credentials Grant Flow will only return an AppAccessToken, which can not be used
|
||||
# for the majority of the Twitch API or to join a chat room.
|
||||
var auth : ImplicitGrantFlow = ImplicitGrantFlow.new()
|
||||
# For the auth to work, we need to poll it regularly.
|
||||
get_tree().process_frame.connect(auth.poll) # You can also use a timer if you don't want to poll on every frame.
|
||||
|
||||
# Next, we actually get our token to authenticate. We want to be able to read and write messages,
|
||||
# so we request the required scopes. See https://dev.twitch.tv/docs/authentication/scopes/#twitch-access-token-scopes
|
||||
var token : UserAccessToken = await(auth.login(client_id, ["chat:read", "chat:edit"]))
|
||||
if (token == null):
|
||||
# Authentication failed. Abort.
|
||||
return
|
||||
|
||||
# Store the token in the ID connection, create all other connections.
|
||||
id = TwitchIDConnection.new(token)
|
||||
irc = TwitchIRCConnection.new(id)
|
||||
api = TwitchAPIConnection.new(id)
|
||||
iconloader = TwitchIconDownloader.new(api)
|
||||
# For everything to work, the id connection has to be polled regularly.
|
||||
get_tree().process_frame.connect(id.poll)
|
||||
|
||||
# Connect to the Twitch chat.
|
||||
if(!await(irc.connect_to_irc(username))):
|
||||
# Authentication failed. Abort.
|
||||
return
|
||||
# Request the capabilities. By default only twitch.tv/commands and twitch.tv/tags are used.
|
||||
# Refer to https://dev.twitch.tv/docs/irc/capabilities/ for all available capapbilities.
|
||||
irc.request_capabilities()
|
||||
# Join the channel specified in the exported 'channel' variable.
|
||||
irc.join_channel(channel)
|
||||
|
||||
# Add a helloworld command.
|
||||
cmd_handler.add_command("helloworld", hello)
|
||||
# The helloworld command can now also be executed with "hello"!
|
||||
cmd_handler.add_alias("helloworld", "hello")
|
||||
# Add a list command that accepts between 1 and infinite args.
|
||||
cmd_handler.add_command("list", list, -1, 1)
|
||||
|
||||
# For the chat example to work, we forward the messages received to the put_chat function.
|
||||
irc.chat_message.connect(put_chat)
|
||||
|
||||
# We also have to forward the messages to the command handler to handle them.
|
||||
irc.chat_message.connect(cmd_handler.handle_command)
|
||||
# If you also want to accept whispers, connect the signal and bind true as the last arg.
|
||||
irc.whisper_message.connect(cmd_handler.handle_command.bind(true))
|
||||
|
||||
# When we press enter on the chat bar or press the send button, we want to execute the send_message
|
||||
# function.
|
||||
%LineEdit.text_submitted.connect(send_message.unbind(1))
|
||||
%Button.pressed.connect(send_message)
|
||||
|
||||
# This part of the example only works if GIFT is logged in to your broadcaster account.
|
||||
# If you are, you can uncomment this to also try receiving follow events.
|
||||
# Don't forget to also add the 'moderator:read:followers' scope to your token.
|
||||
# eventsub = TwitchEventSubConnection.new(api)
|
||||
# await(eventsub.connect_to_eventsub())
|
||||
# eventsub.event.connect(on_event)
|
||||
# var user_ids : Dictionary = await(api.get_users_by_name([username]))
|
||||
# if (user_ids.has("data") && user_ids["data"].size() > 0):
|
||||
# var user_id : String = user_ids["data"][0]["id"]
|
||||
# eventsub.subscribe_event("channel.follow", "2", {"broadcaster_user_id": user_id, "moderator_user_id": user_id})
|
||||
|
||||
func hello(cmd_info : CommandInfo) -> void:
|
||||
irc.chat("Hello World!")
|
||||
|
||||
func list(cmd_info : CommandInfo, arg_ary : PackedStringArray) -> void:
|
||||
irc.chat(", ".join(arg_ary))
|
||||
|
||||
func on_event(type : String, data : Dictionary) -> void:
|
||||
match(type):
|
||||
"channel.follow":
|
||||
print("%s followed your channel!" % data["user_name"])
|
||||
|
||||
func send_message() -> void:
|
||||
irc.chat(%LineEdit.text)
|
||||
%LineEdit.text = ""
|
||||
|
||||
func put_chat(senderdata : SenderData, msg : String):
|
||||
var bottom : bool = %ChatScrollContainer.scroll_vertical == %ChatScrollContainer.get_v_scroll_bar().max_value - %ChatScrollContainer.get_v_scroll_bar().get_rect().size.y
|
||||
var label : RichTextLabel = RichTextLabel.new()
|
||||
var time = Time.get_time_dict_from_system()
|
||||
label.fit_content = true
|
||||
label.selection_enabled = true
|
||||
label.push_font_size(12)
|
||||
label.push_color(Color.WEB_GRAY)
|
||||
label.add_text("%02d:%02d " % [time["hour"], time["minute"]])
|
||||
label.pop()
|
||||
label.push_font_size(14)
|
||||
var badges : Array[Texture2D]
|
||||
for badge in senderdata.tags["badges"].split(",", false):
|
||||
label.add_image(await(iconloader.get_badge(badge, senderdata.tags["room-id"])), 0, 0, Color.WHITE, INLINE_ALIGNMENT_CENTER)
|
||||
label.push_bold()
|
||||
if (senderdata.tags["color"] != ""):
|
||||
label.push_color(Color(senderdata.tags["color"]))
|
||||
label.add_text(" %s" % senderdata.tags["display-name"])
|
||||
label.push_color(Color.WHITE)
|
||||
label.push_normal()
|
||||
label.add_text(": ")
|
||||
var locations : Array[EmoteLocation] = []
|
||||
if (senderdata.tags.has("emotes")):
|
||||
for emote in senderdata.tags["emotes"].split("/", false):
|
||||
var data : PackedStringArray = emote.split(":")
|
||||
for d in data[1].split(","):
|
||||
var start_end = d.split("-")
|
||||
locations.append(EmoteLocation.new(data[0], int(start_end[0]), int(start_end[1])))
|
||||
locations.sort_custom(Callable(EmoteLocation, "smaller"))
|
||||
if (locations.is_empty()):
|
||||
label.add_text(msg)
|
||||
else:
|
||||
var offset = 0
|
||||
for loc in locations:
|
||||
label.add_text(msg.substr(offset, loc.start - offset))
|
||||
label.add_image(await(iconloader.get_emote(loc.id)), 0, 0, Color.WHITE, INLINE_ALIGNMENT_CENTER)
|
||||
offset = loc.end + 1
|
||||
%Messages.add_child(label)
|
||||
await(get_tree().process_frame)
|
||||
if (bottom):
|
||||
%ChatScrollContainer.scroll_vertical = %ChatScrollContainer.get_v_scroll_bar().max_value
|
||||
|
||||
class EmoteLocation extends RefCounted:
|
||||
var id : String
|
||||
var start : int
|
||||
var end : int
|
||||
|
||||
func _init(emote_id, start_idx, end_idx):
|
||||
self.id = emote_id
|
||||
self.start = start_idx
|
||||
self.end = end_idx
|
||||
|
||||
static func smaller(a : EmoteLocation, b : EmoteLocation):
|
||||
return a.start < b.start
|
@ -1,51 +0,0 @@
|
||||
[gd_scene load_steps=2 format=3 uid="uid://bculs28gstcxk"]
|
||||
|
||||
[ext_resource type="Script" path="res://example/Example.gd" id="1_8267x"]
|
||||
|
||||
[node name="Example" type="Control"]
|
||||
layout_mode = 3
|
||||
anchors_preset = 15
|
||||
anchor_right = 1.0
|
||||
anchor_bottom = 1.0
|
||||
grow_horizontal = 2
|
||||
grow_vertical = 2
|
||||
script = ExtResource("1_8267x")
|
||||
|
||||
[node name="ChatContainer" type="VBoxContainer" parent="."]
|
||||
layout_mode = 0
|
||||
anchor_right = 1.0
|
||||
anchor_bottom = 1.0
|
||||
|
||||
[node name="Chat" type="Panel" parent="ChatContainer"]
|
||||
show_behind_parent = true
|
||||
layout_mode = 2
|
||||
size_flags_horizontal = 3
|
||||
size_flags_vertical = 3
|
||||
|
||||
[node name="ChatScrollContainer" type="ScrollContainer" parent="ChatContainer/Chat"]
|
||||
unique_name_in_owner = true
|
||||
layout_mode = 0
|
||||
anchor_right = 1.0
|
||||
anchor_bottom = 1.0
|
||||
follow_focus = true
|
||||
|
||||
[node name="Messages" type="VBoxContainer" parent="ChatContainer/Chat/ChatScrollContainer"]
|
||||
unique_name_in_owner = true
|
||||
layout_mode = 2
|
||||
size_flags_horizontal = 3
|
||||
size_flags_vertical = 3
|
||||
|
||||
[node name="HBoxContainer" type="HBoxContainer" parent="ChatContainer"]
|
||||
layout_mode = 2
|
||||
|
||||
[node name="LineEdit" type="LineEdit" parent="ChatContainer/HBoxContainer"]
|
||||
unique_name_in_owner = true
|
||||
layout_mode = 2
|
||||
size_flags_horizontal = 3
|
||||
size_flags_vertical = 3
|
||||
caret_blink = true
|
||||
|
||||
[node name="Button" type="Button" parent="ChatContainer/HBoxContainer"]
|
||||
unique_name_in_owner = true
|
||||
layout_mode = 2
|
||||
text = "Send"
|
24
export_presets.cfg
Normal file
24
export_presets.cfg
Normal file
@ -0,0 +1,24 @@
|
||||
[preset.0]
|
||||
|
||||
name="Linux/X11"
|
||||
platform="Linux/X11"
|
||||
runnable=true
|
||||
custom_features=""
|
||||
export_filter="all_resources"
|
||||
include_filter=""
|
||||
exclude_filter=""
|
||||
export_path="/home/mennomax/Documents/godot/GIFT.x86_64"
|
||||
patch_list=PoolStringArray( )
|
||||
script_export_mode=1
|
||||
script_encryption_key=""
|
||||
|
||||
[preset.0.options]
|
||||
|
||||
texture_format/bptc=false
|
||||
texture_format/s3tc=true
|
||||
texture_format/etc=false
|
||||
texture_format/etc2=false
|
||||
texture_format/no_bptc_fallbacks=true
|
||||
binary_format/64_bits=true
|
||||
custom_template/release=""
|
||||
custom_template/debug=""
|
BIN
icon.png
Executable file → Normal file
BIN
icon.png
Executable file → Normal file
Binary file not shown.
Before Width: | Height: | Size: 188 B After Width: | Height: | Size: 271 B |
@ -1,9 +1,8 @@
|
||||
[remap]
|
||||
|
||||
importer="texture"
|
||||
type="CompressedTexture2D"
|
||||
uid="uid://rkm6ge1nohu1"
|
||||
path="res://.godot/imported/icon.png-487276ed1e3a0c39cad0279d744ee560.ctex"
|
||||
type="StreamTexture"
|
||||
path="res://.import/icon.png-487276ed1e3a0c39cad0279d744ee560.stex"
|
||||
metadata={
|
||||
"vram_texture": false
|
||||
}
|
||||
@ -11,24 +10,25 @@ metadata={
|
||||
[deps]
|
||||
|
||||
source_file="res://icon.png"
|
||||
dest_files=["res://.godot/imported/icon.png-487276ed1e3a0c39cad0279d744ee560.ctex"]
|
||||
dest_files=[ "res://.import/icon.png-487276ed1e3a0c39cad0279d744ee560.stex" ]
|
||||
|
||||
[params]
|
||||
|
||||
compress/mode=0
|
||||
compress/high_quality=false
|
||||
compress/lossy_quality=0.7
|
||||
compress/hdr_compression=1
|
||||
compress/hdr_mode=0
|
||||
compress/bptc_ldr=0
|
||||
compress/normal_map=0
|
||||
compress/channel_pack=0
|
||||
mipmaps/generate=false
|
||||
mipmaps/limit=-1
|
||||
roughness/mode=0
|
||||
roughness/src_normal=""
|
||||
flags/repeat=0
|
||||
flags/filter=true
|
||||
flags/mipmaps=false
|
||||
flags/anisotropic=false
|
||||
flags/srgb=2
|
||||
process/fix_alpha_border=true
|
||||
process/premult_alpha=false
|
||||
process/normal_map_invert_y=false
|
||||
process/hdr_as_srgb=false
|
||||
process/hdr_clamp_exposure=false
|
||||
process/size_limit=0
|
||||
detect_3d/compress_to=1
|
||||
process/HDR_as_SRGB=false
|
||||
process/invert_color=false
|
||||
stream=false
|
||||
size_limit=0
|
||||
detect_3d=true
|
||||
svg/scale=1.0
|
||||
|
@ -6,18 +6,52 @@
|
||||
; [section] ; section goes between []
|
||||
; param=value ; assign values to parameters
|
||||
|
||||
config_version=5
|
||||
config_version=4
|
||||
|
||||
_global_script_classes=[ {
|
||||
"base": "Reference",
|
||||
"class": "CommandData",
|
||||
"language": "GDScript",
|
||||
"path": "res://addons/gift/util/cmd_data.gd"
|
||||
}, {
|
||||
"base": "Reference",
|
||||
"class": "CommandInfo",
|
||||
"language": "GDScript",
|
||||
"path": "res://addons/gift/util/cmd_info.gd"
|
||||
}, {
|
||||
"base": "Node",
|
||||
"class": "Gift",
|
||||
"language": "GDScript",
|
||||
"path": "res://addons/gift/gift_node.gd"
|
||||
}, {
|
||||
"base": "Resource",
|
||||
"class": "ImageCache",
|
||||
"language": "GDScript",
|
||||
"path": "res://addons/gift/util/image_cache.gd"
|
||||
}, {
|
||||
"base": "Reference",
|
||||
"class": "SenderData",
|
||||
"language": "GDScript",
|
||||
"path": "res://addons/gift/util/sender_data.gd"
|
||||
} ]
|
||||
_global_script_class_icons={
|
||||
"CommandData": "",
|
||||
"CommandInfo": "",
|
||||
"Gift": "",
|
||||
"ImageCache": "",
|
||||
"SenderData": ""
|
||||
}
|
||||
|
||||
[application]
|
||||
|
||||
config/name="GIFT"
|
||||
run/main_scene="res://example/Example.tscn"
|
||||
config/features=PackedStringArray("4.2")
|
||||
run/main_scene="res://Node.tscn"
|
||||
config/icon="res://icon.png"
|
||||
|
||||
[debug]
|
||||
|
||||
gdscript/warnings/return_value_discarded=false
|
||||
gdscript/warnings/unused_argument=false
|
||||
gdscript/warnings/return_value_discarded=false
|
||||
|
||||
[display]
|
||||
|
||||
@ -25,7 +59,7 @@ window/size/width=400
|
||||
|
||||
[editor_plugins]
|
||||
|
||||
enabled=PackedStringArray("res://addons/gift/plugin.cfg")
|
||||
enabled=PoolStringArray( "gift" )
|
||||
|
||||
[rendering]
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user