]> git.lizzy.rs Git - furrybot.git/commitdiff
Async HTTP fetching
authorElias Fleckenstein <eliasfleckenstein@web.de>
Wed, 10 Mar 2021 08:39:28 +0000 (09:39 +0100)
committerElias Fleckenstein <eliasfleckenstein@web.de>
Wed, 10 Mar 2021 08:39:28 +0000 (09:39 +0100)
bot.lua
init.lua

diff --git a/bot.lua b/bot.lua
index aa2e6d5b8d1559ceab5fda178b68acd400e3a628..c80c9e73ada08282c7b9a666260244ca0a11700f 100644 (file)
--- a/bot.lua
+++ b/bot.lua
@@ -1,7 +1,6 @@
 furrybot.commands = {}
 
 local C = minetest.get_color_escape_sequence
-local http = minetest.get_http_api()
 
 function furrybot.send(msg, color)
        minetest.send_chat_message("/me " .. C("#00FF3C") .. "[" .. C(color or "#FFFA00") .. msg .. C("#00FF3C") .. "]")
@@ -37,6 +36,10 @@ function furrybot.check_online(name, target)
        end
 end
 
+function furrybot.choose(list)
+       return list[math.random(#list)]
+end
+
 function furrybot.recieve(msg)
        msg = minetest.strip_colors(msg)
        if msg:find("<") == 1 then
@@ -123,13 +126,22 @@ function furrybot.commands.verse(name)
        local req = {
                url = "https://labs.bible.org/api/?type=json&passage=random",
        }
-       local res = http.fetch_sync(req)
-       if res.succeeded then
-               local data = minetest.parse_json(res.data)[1]
-               furrybot.send(data.text .. C("#00FFC3") .. "[" .. data.bookname .. " " .. data.chapter .. "," .. data.verse .. "]")
-       else
-               furrybot.ping_player_error(name, "Request failed with code", res.code)
-       end
+       local res = furrybot.http.fetch(req, function(res)
+               if res.succeeded then
+                       local data = minetest.parse_json(res.data)[1]
+                       furrybot.send(data.text .. C("#00FFC3") .. "[" .. data.bookname .. " " .. data.chapter .. "," .. data.verse .. "]")
+               else
+                       furrybot.ping_player_error(name, "Request failed with code", res.code)
+               end
+       end)
+end
+
+function furrybot.commands.rolldice(name)
+       furrybot.ping_player(name, "rolled a dice and got a " .. C("#AAFF43") .. math.random(6))
+end
+
+function furrybot.commands.coinflip(name)
+       furrybot.ping_player(name, "flipped a coin and got " .. C("#AAFF43") .. furrybot.choose({"Heads", "Tails"}))
 end
 
 if furrybot.loaded then
index 2b9c2a0e9b71c869a13b35036bddee938f143f8a..aefc9fd342309d576d3a7600867fe476097a6582 100644 (file)
--- a/init.lua
+++ b/init.lua
@@ -2,6 +2,7 @@ furrybot = {}
 
 dofile(minetest.get_modpath("furrybot") .. "/bot.lua")
 
+furrybot.http = minetest.request_http_api()
 local env = assert(minetest.request_insecure_environment())
 
 minetest.register_on_receiving_chat_message(function(msg)