I'm using the twitch api to pull information about a channel. When I put in a valid channel it works, but after I put in a non-valid channel, it stops working. Any ideas why and how to fix it?
function handle(err) errortext = 'ERROR: ' .. err:gsub("(.-:)","") return errortext end function pcallgetasync(person) getasync = game:GetService('HttpService'):GetAsync('https://api.twitch.tv/kraken/channels/' .. person, true) return getasync end game.Players.PlayerAdded:connect(function(player) player.PlayerGui:WaitForChild('ScreenGui').Frame.SearchBox.Search.Changed:connect(function() person = player.PlayerGui.ScreenGui.Frame.SearchBox.Text if player.PlayerGui:WaitForChild('ScreenGui').Frame.SearchBox.Search.Value == true then local httpservice = game:GetService('HttpService') player.PlayerGui.ScreenGui.Frame.SearchBox.Changed:connect(function() person = player.PlayerGui.ScreenGui.Frame.SearchBox.Text end) if pcall (function() pcallgetasync(person) end) then afollowers = string.find(getasync, '"followers":') endthing = string.find(getasync, ',"_links"') followers = string.sub(getasync, afollowers + 12, endthing - 1) player.PlayerGui.ScreenGui.Frame.Followers.Text = 'Followers: ' .. followers player.PlayerGui.ScreenGui.Frame.SearchBox.Search.Value = false else print(xpcall(pcallgetasync, handle)) --errortext = tostring(xpcall(pcallgetasync, handle)) a = require(game.Workspace.ErrorScript) a(player.Name, errortext) end end end) end)
(I have not tested this so I cannot guarantee that this is the only issue)
Line 21 checks that you are able to get a response. However, it does not guarantee that your response is in the form you expected.
You search for '"followers":'
and ',"_links"'
; however, if the string does not contain those, then that search will result in nil
.
In the following line, you operate on (adding / substring, and using as arguments to string.sub
) afollowers
and endthing
even though they could be nil
, which will cause an error.
You should check that they have values:
if afollowers and endthing then
and only then proceed.