aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorterminaldweller <devi@terminaldweller.com>2024-07-30 23:25:59 +0000
committerterminaldweller <devi@terminaldweller.com>2024-07-30 23:25:59 +0000
commit81469bbb1745a835676c3664e75a4a951223da9d (patch)
tree70a53b118c406d5958a8fb8c72e391fb6439f729
parentwe can now add new commands from lua plugins (diff)
downloadmilla-81469bbb1745a835676c3664e75a4a951223da9d.tar.gz
milla-81469bbb1745a835676c3664e75a4a951223da9d.zip
* fixed a crash when unloading a lua script
* added event types, foreground and background color for watchlists * added a url_encode function to lua to encode urls. Underneath, it just calls the standard library function from golang * updated the README * the urban plugin now can take in the number of entries to return * reverted a bug where setting the http proxy for the lua http module was not working * fixed the url for the ip script so it is actually working. the current provider does not support ipv6 though
-rw-r--r--README.md11
-rw-r--r--main.go53
-rw-r--r--plugins.go27
-rw-r--r--plugins/ip.lua17
-rw-r--r--plugins/rss.lua2
-rw-r--r--plugins/urban.lua46
-rw-r--r--types.go8
7 files changed, 127 insertions, 37 deletions
diff --git a/README.md b/README.md
index 467a5b7..58713b1 100644
--- a/README.md
+++ b/README.md
@@ -272,6 +272,9 @@ Watchlists allow you to specify a list of channels to watch. The watched values
watchList = ["#securityfeeds"]
watchFiles = ["/watchfiles/voidbox.list"]
alertChannel = "#milla_alerts"
+eventTypes = ["PRIVMSG"]
+fgColor = 0
+bgColor = 28
```
### Example Config File
@@ -706,6 +709,10 @@ milla.query_db(query)
milla.register_cmd(script_path, cmd_name, function_name)
```
+```lua
+milla.url_encode(str)
+```
+
Using `register_cmd` we can register a command that will be available to run like the built-in and customs commands.<br/>
Here's an example of how to use it:<br/>
@@ -725,7 +732,7 @@ local http = require("http")
-- should only return one string value
function milla_get_ip(arg)
local ip = arg
- local response, err = http.request("GET", "http://ip-api.com/json?" .. ip)
+ local response, err = http.request("GET", "http://ip-api.com/json/" .. ip)
if err ~= nil then print(err) end
local json_response, err = json.decode(response.body)
@@ -746,7 +753,7 @@ milla.register_cmd("/plugins/ip.lua", "ip", "milla_get_ip")
This will allow us to do:<br/>
```
-/terra: /ip 1.1.1.1
+terra: /ip 1.1.1.1
```
The example rss plugin, accepts a yaml file as input, reeds the provided rss feeds once, extracts the title, author name and link to the resource, sends the feed over to the `#rssfeed` irc channel and exits.<br/>
diff --git a/main.go b/main.go
index 619ea63..05133c0 100644
--- a/main.go
+++ b/main.go
@@ -554,7 +554,12 @@ func runCommand(
break
}
- result := RunLuaFunc(args[0], args[1], client, appConfig)
+ luaArgs := strings.TrimPrefix(event.Last(), appConfig.IrcNick+": ")
+ luaArgs = strings.TrimSpace(luaArgs)
+ luaArgs = strings.TrimPrefix(luaArgs, "/")
+ luaArgs = strings.TrimPrefix(luaArgs, args[0])
+
+ result := RunLuaFunc(args[0], luaArgs, client, appConfig)
client.Cmd.Reply(event, result)
}
}
@@ -640,11 +645,6 @@ func DoOllamaRequest(
return "", err
}
- if err != nil {
-
- return "", err
- }
-
defer response.Body.Close()
log.Println("response body:", response.Body)
@@ -1086,17 +1086,50 @@ func populateWatchListWords(appConfig *TomlConfig) {
}
func WatchListHandler(irc *girc.Client, appConfig TomlConfig) {
- irc.Handlers.AddBg(girc.PRIVMSG, func(_ *girc.Client, event girc.Event) {
+ irc.Handlers.AddBg(girc.ALL_EVENTS, func(_ *girc.Client, event girc.Event) {
+ var isRightEventType bool
+
sarray := suffixarray.New([]byte(event.Last()))
+ if len(event.Params) == 0 {
+ return
+ }
+
for watchname, watchlist := range appConfig.WatchLists {
for _, channel := range watchlist.WatchList {
+ isRightEventType = false
+
if channel == event.Params[0] {
+
+ for _, eventType := range watchlist.EventTypes {
+ if eventType == event.Command {
+ isRightEventType = true
+
+ break
+ }
+ }
+
+ if !isRightEventType {
+ continue
+ }
+
for _, word := range watchlist.Words {
- indexes := sarray.Lookup([]byte(word), -1)
+ indexes := sarray.Lookup([]byte(" "+word+" "), 1)
if len(indexes) > 0 {
- irc.Cmd.Message(watchlist.AlertChannel, fmt.Sprintf("%s: %s", watchname, event.Last()))
- log.Printf("%s: %s", watchname, event.Last())
+ nextWhitespaceIndex := strings.Index(event.Last()[indexes[0]+1:], " ")
+
+ rewrittenMessage :=
+ event.Last()[:indexes[0]+1] +
+ fmt.Sprintf("\x1b[48;5;%dm", watchlist.BGColor) +
+ fmt.Sprintf("\x1b[38;5;%dm", watchlist.FGColor) +
+ event.Last()[indexes[0]+1:indexes[0]+1+nextWhitespaceIndex] +
+ "\x1b[0m" + event.Last()[indexes[0]+1+nextWhitespaceIndex:]
+
+ irc.Cmd.Message(
+ watchlist.AlertChannel,
+ fmt.Sprintf("%s: %s", watchname, rewrittenMessage))
+
+ log.Printf("matched from watchlist -- %s: %s", watchname, event.Last())
break
}
diff --git a/plugins.go b/plugins.go
index c2775db..8e15976 100644
--- a/plugins.go
+++ b/plugins.go
@@ -197,7 +197,6 @@ func sendMessageClosure(luaState *lua.LState, client *girc.Client) func(*lua.LSt
return 0
}
}
-
func registerLuaCommand(luaState *lua.LState, appConfig *TomlConfig) func(*lua.LState) int {
return func(luaState *lua.LState) int {
path := luaState.CheckString(1)
@@ -317,6 +316,15 @@ func dbQueryClosure(luaState *lua.LState, appConfig *TomlConfig) func(*lua.LStat
}
}
+func urlEncode(luaState *lua.LState) func(*lua.LState) int {
+ return func(luaState *lua.LState) int {
+ URL := luaState.CheckString(1)
+ escapedURL := url.QueryEscape(URL)
+ luaState.Push(lua.LString(escapedURL))
+ return 1
+ }
+}
+
func millaModuleLoaderClosure(luaState *lua.LState, client *girc.Client, appConfig *TomlConfig) func(*lua.LState) int {
return func(luaState *lua.LState) int {
exports := map[string]lua.LGFunction{
@@ -328,6 +336,7 @@ func millaModuleLoaderClosure(luaState *lua.LState, client *girc.Client, appConf
"send_chatgpt_request": lua.LGFunction(chatGPTRequestClosure(luaState, appConfig)),
"query_db": lua.LGFunction(dbQueryClosure(luaState, appConfig)),
"register_cmd": lua.LGFunction(registerLuaCommand(luaState, appConfig)),
+ "url_encode": lua.LGFunction(urlEncode(luaState)),
}
millaModule := luaState.SetFuncs(luaState.NewTable(), exports)
@@ -425,20 +434,20 @@ func RunLuaFunc(
luaState.PreloadModule("json", gopherjson.Loader)
var proxyString string
- switch proxyString {
- case os.Getenv("ALL_PROXY"):
+ if os.Getenv("ALL_PROXY") != "" {
proxyString = os.Getenv("ALL_PROXY")
- case os.Getenv("HTTPS_PROXY"):
+ } else if os.Getenv("HTTPS_PROXY") != "" {
proxyString = os.Getenv("HTTPS_PROXY")
- case os.Getenv("HTTP_PROXY"):
+ } else if os.Getenv("HTTP_PROXY") != "" {
proxyString = os.Getenv("HTTP_PROXY")
- case os.Getenv("https_proxy"):
+ } else if os.Getenv("https_proxy") != "" {
proxyString = os.Getenv("https_proxy")
- case os.Getenv("http_proxy"):
+ } else if os.Getenv("http_proxy") != "" {
proxyString = os.Getenv("http_proxy")
- default:
}
+ log.Print("set proxy env to:", proxyString)
+
proxyTransport := &http.Transport{}
if proxyString != "" {
@@ -465,6 +474,8 @@ func RunLuaFunc(
Protect: true,
}
+ log.Print(cmd)
+ log.Print(args)
if err := luaState.CallByParam(funcLValue, lua.LString(args)); err != nil {
log.Print("failed running lua command ...")
log.Print(err)
diff --git a/plugins/ip.lua b/plugins/ip.lua
index 2e9afad..79ac6e2 100644
--- a/plugins/ip.lua
+++ b/plugins/ip.lua
@@ -2,18 +2,19 @@ local milla = require("milla")
local os = require("os")
local json = require("json")
--- setting the proxy value before loading the http module
--- this way, only this script will be using this proxy
-os.setenv("ALL_PROXY", "socks5://172.17.0.1:9057")
-
-local http = require("http")
-
-- this function should be global
-- one string arg that holds all args
-- should only return one string value
function milla_get_ip(arg)
- local ip = arg
- local response, err = http.request("GET", "http://ip-api.com/json?" .. ip)
+ -- setting the proxy value before loading the http module
+ -- this way, only this script will be using this proxy
+ os.setenv("http_proxy", "http://172.17.0.1:8120")
+
+ local http = require("http")
+
+ local url = "http://ip-api.com/json/" .. arg
+
+ local response, err = http.request("GET", url)
if err ~= nil then print(err) end
local json_response, err = json.decode(response.body)
diff --git a/plugins/rss.lua b/plugins/rss.lua
index 880a0fd..111baa2 100644
--- a/plugins/rss.lua
+++ b/plugins/rss.lua
@@ -47,7 +47,6 @@ local function get_rss_feed(config)
end
path, err = xmlpath.compile("//entry/author/name")
- -- local path, err = xmlpath.compile("//entry/title")
if err ~= nil then
milla.send_message(err, "")
goto continue
@@ -58,7 +57,6 @@ local function get_rss_feed(config)
end
path, err = xmlpath.compile("//entry/author/uri")
- -- local path, err = xmlpath.compile("//entry/title")
if err ~= nil then
milla.send_message(err, "")
goto continue
diff --git a/plugins/urban.lua b/plugins/urban.lua
index 08c610b..7b7e71c 100644
--- a/plugins/urban.lua
+++ b/plugins/urban.lua
@@ -2,15 +2,42 @@ local milla = require("milla")
local os = require("os")
local json = require("json")
-os.setenv("ALL_PROXY", "socks5://172.17.0.1:9057")
+os.setenv("ALL_PROXY", "socks5://172.17.0.1:9004")
local http = require("http")
-function milla_urban(arg)
+function milla_urban(cli_args)
+ local args = {}
+ for i in string.gmatch(cli_args, "%S+") do table.insert(args, i) end
+
+ for k, v in ipairs(args) do print(k, v) end
+
+ local count = 1
+ local term = ""
+
+ local skip = false
+
+ for i = 1, #args do
+ if skip then
+ skip = false
+ goto continue
+ end
+ if args[i] == "-n" then
+ count = tonumber(args[i + 1])
+ skip = true
+ else
+ term = term .. args[i] .. " "
+ end
+ ::continue::
+ end
+ print("Term: " .. term)
+ print("Count: " .. count)
+
local user_agent =
"Mozilla/5.0 (X11; U; Linux x86_64; pl-PL; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10"
- local term = arg
- local url = "http://api.urbandictionary.com/v0/define?term=" .. term
+
+ local escaped_term = milla.url_encode(term)
+ local url = "http://api.urbandictionary.com/v0/define?term=" .. escaped_term
local response, err = http.request("GET", url, {
timeout = "10s",
headers = {
@@ -30,10 +57,17 @@ function milla_urban(arg)
local json_response, err = json.decode(response.body)
if err ~= nil then print(err) end
+ if response.status_code ~= 200 then
+ return "Error: " .. response.status_code
+ end
+
local result = ""
- for k, v in ipairs(json_response["list"]) do
+ for _, v in ipairs(json_response["list"]) do
for kk, vv in pairs(v) do print(kk, vv) end
- if k == 1 then result = v["definition"] end
+ if count > 0 then
+ result = result .. tostring(count) .. v["definition"] .. "----"
+ end
+ count = count - 1
end
return result
diff --git a/types.go b/types.go
index d6f3236..85f820d 100644
--- a/types.go
+++ b/types.go
@@ -33,6 +33,9 @@ type WatchList struct {
WatchList []string `toml:"watchList"`
WatchFiles []string `toml:"watchFiles"`
Words []string `toml:"watchWords"`
+ EventTypes []string `toml:"eventTypes"`
+ FGColor int `toml:"fgColor"`
+ BGColor int `toml:"bgColor"`
}
type LuaCommand struct {
@@ -114,7 +117,10 @@ func (config *TomlConfig) deleteLstate(name string) {
if config.LuaStates == nil {
return
}
- config.LuaStates[name].Cancel()
+
+ if config.LuaStates[name].Cancel != nil {
+ config.LuaStates[name].Cancel()
+ }
delete(config.LuaStates, name)
}