· 6 years ago · Nov 03, 2019, 05:22 AM
1--@name
2--@author
3--@server
4
5API_KEY = "Get an API key from grammarbot.io"
6REQUEST_TIME = 10
7API_URL = "http://api.grammarbot.io/v2/check?"
8REQ_PREFIX = API_URL.."api_key="..API_KEY.."&language=en-US&text="
9
10
11lastRequest = timer.systime() + REQUEST_TIME
12
13singleSayings = {
14 "You mean \""..API_KEY.."\", right?",
15 "I think you meant \""..API_KEY.."\", right?",
16 "You mean \""..API_KEY.."\"?",
17 "Do you mean \""..API_KEY.."\"?",
18 "You meant to say \""..API_KEY.."\" right?",
19 API_KEY.."*"
20}
21
22function httpUrlEncode(data)
23 local ndata = string.gsub( data, "[^%w _~%.%-]", function( str )
24 local nstr = string.format( "%X", string.byte( str ) )
25
26 return "%" .. ( ( string.len( nstr ) == 1 ) and "0" or "" ) .. nstr
27 end )
28
29 return string.gsub( ndata, " ", "+" )
30end
31
32function request(text)
33 local url = REQ_PREFIX..httpUrlEncode(text)
34 http.get(url, receive, getFail)
35end
36
37function receive(body, length, header, code)
38 response = json.decode(body)
39 local correction = {}
40 for _, match in pairs(response.matches) do
41 if match != nil and table.hasValue(table.getKeys(match), "replacements") then
42 --correction = correction..match.replacements[1].value.."* "
43 pcall(function()
44 if string.len(match.replacements[1].value) > 0 then
45 table.insert(correction, match.replacements[1].value)
46 end
47 end)
48 end
49 end
50
51 if table.count(correction) == 1 then
52 concmd("say "..string.replace(table.random(singleSayings),API_KEY,correction[1]))
53 elseif table.count(correction) > 1 then
54 concmd("say "..table.concat(correction, "* ").."*")
55 end
56end
57
58function getFail(err)
59end
60
61function onChat( ply, text, teamChat )
62 local elapsed = timer.systime() - lastRequest
63 if ply != owner() and http.canRequest() and elapsed > REQUEST_TIME and string.len(text) > 3 then
64 lastRequest = timer.systime()
65 request(text)
66 else
67 print(""..math.truncate(elapsed,2).." seconds since last request")
68 end
69end
70
71hook.add("PlayerSay", "OnChat", onChat)