Skip to content

Instantly share code, notes, and snippets.

@samuelmaddock
Created January 5, 2014 23:32
Show Gist options
  • Save samuelmaddock/8275581 to your computer and use it in GitHub Desktop.
Save samuelmaddock/8275581 to your computer and use it in GitHub Desktop.
Twitch.TV live hostname
if not SERVER then return end
local STREAM_API_URL = "https://api.twitch.tv/kraken/streams/%s"
local STREAM_HOSTNAME = "%s | twitch.tv/%s"
local CvarFlags = { FCVAR_ARCHIVE, FCVAR_DONTRECORD }
local TwitchPingDelay = CreateConVar( "twitch_pingdelay", 2 * 60, CvarFlags,
"Frequency in which the Twitch.TV stream will be pinged." )
local TwitchChannelCvar = CreateConVar( "twitch_channel", "", CvarFlags,
"Twitch.TV channel to append to the server hostname." )
local PingTwitchChannel
local OldHostname
local function SetTwitchHostname( channel )
if OldHostname then return end
local hostname = GetHostName()
RunConsoleCommand( "hostname", STREAM_HOSTNAME:format( hostname, channel ) )
OldHostname = hostname
end
local function ResetHostname()
if not OldHostname then return end
RunConsoleCommand( "hostname", OldHostname )
OldHostname = nil
end
local function DelayTwitchPing( delay )
timer.Simple( delay or TwitchPingDelay:GetInt(), PingTwitchChannel )
end
function PingTwitchChannel()
local channel = TwitchChannelCvar:GetString()
if not channel or channel == "" then return end
http.Fetch( STREAM_API_URL:format(channel),
function(body, length, headers, code)
local response = util.JSONToTable(body)
if not response then
ErrorNoHalt("Twitch.TV: Failed to parse API response\n")
debug.Trace()
return
end
-- Is the stream valid and running?
if ( response.status and response.status > 400 ) or
not response.stream then
ResetHostname()
else
-- Display Twitch.TV channel in hostname
SetTwitchHostname( channel )
end
DelayTwitchPing()
end,
function()
ResetHostname()
DelayTwitchPing()
end
)
end
DelayTwitchPing( 10 )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment