Skip to content

Commit 81469bb

Browse files
* 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
1 parent 7a3795e commit 81469bb

File tree

7 files changed

+127
-37
lines changed

7 files changed

+127
-37
lines changed

README.md

+9-2
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,9 @@ Watchlists allow you to specify a list of channels to watch. The watched values
272272
watchList = ["#securityfeeds"]
273273
watchFiles = ["/watchfiles/voidbox.list"]
274274
alertChannel = "#milla_alerts"
275+
eventTypes = ["PRIVMSG"]
276+
fgColor = 0
277+
bgColor = 28
275278
```
276279

277280
### Example Config File
@@ -706,6 +709,10 @@ milla.query_db(query)
706709
milla.register_cmd(script_path, cmd_name, function_name)
707710
```
708711

712+
```lua
713+
milla.url_encode(str)
714+
```
715+
709716
Using `register_cmd` we can register a command that will be available to run like the built-in and customs commands.<br/>
710717
Here's an example of how to use it:<br/>
711718

@@ -725,7 +732,7 @@ local http = require("http")
725732
-- should only return one string value
726733
function milla_get_ip(arg)
727734
local ip = arg
728-
local response, err = http.request("GET", "http://ip-api.com/json?" .. ip)
735+
local response, err = http.request("GET", "http://ip-api.com/json/" .. ip)
729736
if err ~= nil then print(err) end
730737
731738
local json_response, err = json.decode(response.body)
@@ -746,7 +753,7 @@ milla.register_cmd("/plugins/ip.lua", "ip", "milla_get_ip")
746753
This will allow us to do:<br/>
747754

748755
```
749-
/terra: /ip 1.1.1.1
756+
terra: /ip 1.1.1.1
750757
```
751758
752759
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/>

main.go

+43-10
Original file line numberDiff line numberDiff line change
@@ -554,7 +554,12 @@ func runCommand(
554554
break
555555
}
556556

557-
result := RunLuaFunc(args[0], args[1], client, appConfig)
557+
luaArgs := strings.TrimPrefix(event.Last(), appConfig.IrcNick+": ")
558+
luaArgs = strings.TrimSpace(luaArgs)
559+
luaArgs = strings.TrimPrefix(luaArgs, "/")
560+
luaArgs = strings.TrimPrefix(luaArgs, args[0])
561+
562+
result := RunLuaFunc(args[0], luaArgs, client, appConfig)
558563
client.Cmd.Reply(event, result)
559564
}
560565
}
@@ -640,11 +645,6 @@ func DoOllamaRequest(
640645
return "", err
641646
}
642647

643-
if err != nil {
644-
645-
return "", err
646-
}
647-
648648
defer response.Body.Close()
649649

650650
log.Println("response body:", response.Body)
@@ -1086,17 +1086,50 @@ func populateWatchListWords(appConfig *TomlConfig) {
10861086
}
10871087

10881088
func WatchListHandler(irc *girc.Client, appConfig TomlConfig) {
1089-
irc.Handlers.AddBg(girc.PRIVMSG, func(_ *girc.Client, event girc.Event) {
1089+
irc.Handlers.AddBg(girc.ALL_EVENTS, func(_ *girc.Client, event girc.Event) {
1090+
var isRightEventType bool
1091+
10901092
sarray := suffixarray.New([]byte(event.Last()))
10911093

1094+
if len(event.Params) == 0 {
1095+
return
1096+
}
1097+
10921098
for watchname, watchlist := range appConfig.WatchLists {
10931099
for _, channel := range watchlist.WatchList {
1100+
isRightEventType = false
1101+
10941102
if channel == event.Params[0] {
1103+
1104+
for _, eventType := range watchlist.EventTypes {
1105+
if eventType == event.Command {
1106+
isRightEventType = true
1107+
1108+
break
1109+
}
1110+
}
1111+
1112+
if !isRightEventType {
1113+
continue
1114+
}
1115+
10951116
for _, word := range watchlist.Words {
1096-
indexes := sarray.Lookup([]byte(word), -1)
1117+
indexes := sarray.Lookup([]byte(" "+word+" "), 1)
10971118
if len(indexes) > 0 {
1098-
irc.Cmd.Message(watchlist.AlertChannel, fmt.Sprintf("%s: %s", watchname, event.Last()))
1099-
log.Printf("%s: %s", watchname, event.Last())
1119+
nextWhitespaceIndex := strings.Index(event.Last()[indexes[0]+1:], " ")
1120+
1121+
rewrittenMessage :=
1122+
event.Last()[:indexes[0]+1] +
1123+
fmt.Sprintf("\x1b[48;5;%dm", watchlist.BGColor) +
1124+
fmt.Sprintf("\x1b[38;5;%dm", watchlist.FGColor) +
1125+
event.Last()[indexes[0]+1:indexes[0]+1+nextWhitespaceIndex] +
1126+
"\x1b[0m" + event.Last()[indexes[0]+1+nextWhitespaceIndex:]
1127+
1128+
irc.Cmd.Message(
1129+
watchlist.AlertChannel,
1130+
fmt.Sprintf("%s: %s", watchname, rewrittenMessage))
1131+
1132+
log.Printf("matched from watchlist -- %s: %s", watchname, event.Last())
11001133

11011134
break
11021135
}

plugins.go

+19-8
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,6 @@ func sendMessageClosure(luaState *lua.LState, client *girc.Client) func(*lua.LSt
197197
return 0
198198
}
199199
}
200-
201200
func registerLuaCommand(luaState *lua.LState, appConfig *TomlConfig) func(*lua.LState) int {
202201
return func(luaState *lua.LState) int {
203202
path := luaState.CheckString(1)
@@ -317,6 +316,15 @@ func dbQueryClosure(luaState *lua.LState, appConfig *TomlConfig) func(*lua.LStat
317316
}
318317
}
319318

319+
func urlEncode(luaState *lua.LState) func(*lua.LState) int {
320+
return func(luaState *lua.LState) int {
321+
URL := luaState.CheckString(1)
322+
escapedURL := url.QueryEscape(URL)
323+
luaState.Push(lua.LString(escapedURL))
324+
return 1
325+
}
326+
}
327+
320328
func millaModuleLoaderClosure(luaState *lua.LState, client *girc.Client, appConfig *TomlConfig) func(*lua.LState) int {
321329
return func(luaState *lua.LState) int {
322330
exports := map[string]lua.LGFunction{
@@ -328,6 +336,7 @@ func millaModuleLoaderClosure(luaState *lua.LState, client *girc.Client, appConf
328336
"send_chatgpt_request": lua.LGFunction(chatGPTRequestClosure(luaState, appConfig)),
329337
"query_db": lua.LGFunction(dbQueryClosure(luaState, appConfig)),
330338
"register_cmd": lua.LGFunction(registerLuaCommand(luaState, appConfig)),
339+
"url_encode": lua.LGFunction(urlEncode(luaState)),
331340
}
332341
millaModule := luaState.SetFuncs(luaState.NewTable(), exports)
333342

@@ -425,20 +434,20 @@ func RunLuaFunc(
425434
luaState.PreloadModule("json", gopherjson.Loader)
426435

427436
var proxyString string
428-
switch proxyString {
429-
case os.Getenv("ALL_PROXY"):
437+
if os.Getenv("ALL_PROXY") != "" {
430438
proxyString = os.Getenv("ALL_PROXY")
431-
case os.Getenv("HTTPS_PROXY"):
439+
} else if os.Getenv("HTTPS_PROXY") != "" {
432440
proxyString = os.Getenv("HTTPS_PROXY")
433-
case os.Getenv("HTTP_PROXY"):
441+
} else if os.Getenv("HTTP_PROXY") != "" {
434442
proxyString = os.Getenv("HTTP_PROXY")
435-
case os.Getenv("https_proxy"):
443+
} else if os.Getenv("https_proxy") != "" {
436444
proxyString = os.Getenv("https_proxy")
437-
case os.Getenv("http_proxy"):
445+
} else if os.Getenv("http_proxy") != "" {
438446
proxyString = os.Getenv("http_proxy")
439-
default:
440447
}
441448

449+
log.Print("set proxy env to:", proxyString)
450+
442451
proxyTransport := &http.Transport{}
443452

444453
if proxyString != "" {
@@ -465,6 +474,8 @@ func RunLuaFunc(
465474
Protect: true,
466475
}
467476

477+
log.Print(cmd)
478+
log.Print(args)
468479
if err := luaState.CallByParam(funcLValue, lua.LString(args)); err != nil {
469480
log.Print("failed running lua command ...")
470481
log.Print(err)

plugins/ip.lua

+9-8
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,19 @@ local milla = require("milla")
22
local os = require("os")
33
local json = require("json")
44

5-
-- setting the proxy value before loading the http module
6-
-- this way, only this script will be using this proxy
7-
os.setenv("ALL_PROXY", "socks5://172.17.0.1:9057")
8-
9-
local http = require("http")
10-
115
-- this function should be global
126
-- one string arg that holds all args
137
-- should only return one string value
148
function milla_get_ip(arg)
15-
local ip = arg
16-
local response, err = http.request("GET", "http://ip-api.com/json?" .. ip)
9+
-- setting the proxy value before loading the http module
10+
-- this way, only this script will be using this proxy
11+
os.setenv("http_proxy", "http://172.17.0.1:8120")
12+
13+
local http = require("http")
14+
15+
local url = "http://ip-api.com/json/" .. arg
16+
17+
local response, err = http.request("GET", url)
1718
if err ~= nil then print(err) end
1819

1920
local json_response, err = json.decode(response.body)

plugins/rss.lua

-2
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,6 @@ local function get_rss_feed(config)
4747
end
4848

4949
path, err = xmlpath.compile("//entry/author/name")
50-
-- local path, err = xmlpath.compile("//entry/title")
5150
if err ~= nil then
5251
milla.send_message(err, "")
5352
goto continue
@@ -58,7 +57,6 @@ local function get_rss_feed(config)
5857
end
5958

6059
path, err = xmlpath.compile("//entry/author/uri")
61-
-- local path, err = xmlpath.compile("//entry/title")
6260
if err ~= nil then
6361
milla.send_message(err, "")
6462
goto continue

plugins/urban.lua

+40-6
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,42 @@ local milla = require("milla")
22
local os = require("os")
33
local json = require("json")
44

5-
os.setenv("ALL_PROXY", "socks5://172.17.0.1:9057")
5+
os.setenv("ALL_PROXY", "socks5://172.17.0.1:9004")
66

77
local http = require("http")
88

9-
function milla_urban(arg)
9+
function milla_urban(cli_args)
10+
local args = {}
11+
for i in string.gmatch(cli_args, "%S+") do table.insert(args, i) end
12+
13+
for k, v in ipairs(args) do print(k, v) end
14+
15+
local count = 1
16+
local term = ""
17+
18+
local skip = false
19+
20+
for i = 1, #args do
21+
if skip then
22+
skip = false
23+
goto continue
24+
end
25+
if args[i] == "-n" then
26+
count = tonumber(args[i + 1])
27+
skip = true
28+
else
29+
term = term .. args[i] .. " "
30+
end
31+
::continue::
32+
end
33+
print("Term: " .. term)
34+
print("Count: " .. count)
35+
1036
local user_agent =
1137
"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"
12-
local term = arg
13-
local url = "http://api.urbandictionary.com/v0/define?term=" .. term
38+
39+
local escaped_term = milla.url_encode(term)
40+
local url = "http://api.urbandictionary.com/v0/define?term=" .. escaped_term
1441
local response, err = http.request("GET", url, {
1542
timeout = "10s",
1643
headers = {
@@ -30,10 +57,17 @@ function milla_urban(arg)
3057
local json_response, err = json.decode(response.body)
3158
if err ~= nil then print(err) end
3259

60+
if response.status_code ~= 200 then
61+
return "Error: " .. response.status_code
62+
end
63+
3364
local result = ""
34-
for k, v in ipairs(json_response["list"]) do
65+
for _, v in ipairs(json_response["list"]) do
3566
for kk, vv in pairs(v) do print(kk, vv) end
36-
if k == 1 then result = v["definition"] end
67+
if count > 0 then
68+
result = result .. tostring(count) .. v["definition"] .. "----"
69+
end
70+
count = count - 1
3771
end
3872

3973
return result

types.go

+7-1
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,9 @@ type WatchList struct {
3333
WatchList []string `toml:"watchList"`
3434
WatchFiles []string `toml:"watchFiles"`
3535
Words []string `toml:"watchWords"`
36+
EventTypes []string `toml:"eventTypes"`
37+
FGColor int `toml:"fgColor"`
38+
BGColor int `toml:"bgColor"`
3639
}
3740

3841
type LuaCommand struct {
@@ -114,7 +117,10 @@ func (config *TomlConfig) deleteLstate(name string) {
114117
if config.LuaStates == nil {
115118
return
116119
}
117-
config.LuaStates[name].Cancel()
120+
121+
if config.LuaStates[name].Cancel != nil {
122+
config.LuaStates[name].Cancel()
123+
}
118124
delete(config.LuaStates, name)
119125
}
120126

0 commit comments

Comments
 (0)