From 8301e1dfaa80830bb2aabab325001368ed1ad5e4 Mon Sep 17 00:00:00 2001 From: KLIPFEL Arthur Date: Tue, 24 Jul 2018 14:04:08 +0200 Subject: [PATCH 1/3] des trucs pas termine qui fonctionne plus ou moins --- alfred.go | 4 ++ plugin/test.go | 22 +++++++ plugin/test2.go | 22 +++++++ plugin_manager/context.go | 9 +++ plugin_manager/manager.go | 117 ++++++++++++++++++++++++++++++++++++++ plugin_manager/tools.go | 57 +++++++++++++++++++ settings.json | 4 +- 7 files changed, 233 insertions(+), 2 deletions(-) create mode 100644 plugin/test.go create mode 100644 plugin/test2.go create mode 100644 plugin_manager/context.go create mode 100644 plugin_manager/manager.go create mode 100644 plugin_manager/tools.go diff --git a/alfred.go b/alfred.go index 1933c92..cad1f1c 100644 --- a/alfred.go +++ b/alfred.go @@ -8,6 +8,7 @@ package main import ( + "./plugin_manager" "./settings" "./shared" tb "gopkg.in/tucnak/telebot.v2" @@ -63,6 +64,9 @@ func main() { b.Send(m.Chat, "Venez participer à mon développement en posant vos idées ici : https://mensuel.framapad.org/p/ALFRED2LERETOUR.") }) + plugin_manager.Init("plugin", b) + b.Handle(tb.OnText, plugin_manager.HandleMessage) + plugin_manager.StartPlugins() log.Println("Starting bot") b.Start() } diff --git a/plugin/test.go b/plugin/test.go new file mode 100644 index 0000000..7e84ec2 --- /dev/null +++ b/plugin/test.go @@ -0,0 +1,22 @@ +package main + +import ( + tb "gopkg.in/tucnak/telebot.v2" + "log" +) + +type plugin string + +func (g plugin) Load() { + log.Println("plugin test loaded!") +} + +func (g plugin) HandleMessage(bot *tb.Bot, msg string) { + log.Println("test message: " + msg) +} + +func (g plugin) Unload() { + log.Println("plugin test unloaded!") +} + +var Plugin plugin diff --git a/plugin/test2.go b/plugin/test2.go new file mode 100644 index 0000000..9883f11 --- /dev/null +++ b/plugin/test2.go @@ -0,0 +1,22 @@ +package main + +import ( + tb "gopkg.in/tucnak/telebot.v2" + "log" +) + +type plugin string + +func (g plugin) Load() { + log.Println("plugin test2 loaded!") +} + +func (g plugin) HandleMessage(bot *tb.Bot, msg string) { + log.Println("test2 message: " + msg) +} + +func (g plugin) Unload() { + log.Println("plugin test2 unloaded!") +} + +var Plugin plugin diff --git a/plugin_manager/context.go b/plugin_manager/context.go new file mode 100644 index 0000000..fa34617 --- /dev/null +++ b/plugin_manager/context.go @@ -0,0 +1,9 @@ +package plugin_manager + +import ( + tb "gopkg.in/tucnak/telebot.v2" +) + +type Context struct { + bot *tb.Bot +} diff --git a/plugin_manager/manager.go b/plugin_manager/manager.go new file mode 100644 index 0000000..186da86 --- /dev/null +++ b/plugin_manager/manager.go @@ -0,0 +1,117 @@ +/** + * @Author: KLIPFEL Arthur + * @Date: 2018-08-24 12:17:17 + */ +package plugin_manager + +import ( + tb "gopkg.in/tucnak/telebot.v2" + "log" + "sync" +) + +type PluginCtrl struct { + plugin Plugin + mux sync.Mutex + running bool + enable bool +} + +var pluginDir string +var pluginsRunning bool +var plugins map[string]PluginCtrl +var context Context + +func Init(_pluginDir string, bot *tb.Bot) { + pluginDir = _pluginDir + pluginsRunning = false + plugins = make(map[string]PluginCtrl) + context.bot = bot + for _, fileName := range GetSoFiles(pluginDir) { + var p PluginCtrl + p.plugin = LoadSoFile(pluginDir + "/" + fileName) + if p.plugin != nil { + p.running = false + p.enable = true + plugins[fileName[:len(fileName)-3]] = p + } + } +} + +func EnablePlugin(name string, enable bool) { + if p, ok := plugins[name]; ok { + if enable != p.enable { + p.enable = enable + plugins[name] = p + if pluginsRunning { + if enable { + if !p.running { + startPlugin(name) + } + } else { + if p.running { + stopPlugin(name) + } + } + } + } + } else { + log.Fatal("error: plugin " + name + " not founded") + } +} + +func StopPlugins() { + for k, _ := range plugins { + stopPlugin(k) + } + pluginsRunning = false +} + +func HandleMessage(msg *tb.Message) { + for _, val := range plugins { + if val.enable { + val.plugin.HandleMessage(context.bot, msg.Text) + } + } +} + +func StartPlugins() { + for k, val := range plugins { + if val.enable { + startPlugin(k) + } + } + pluginsRunning = true +} + +func startPlugin(name string) { + if p, ok := plugins[name]; ok { + //p.mux.Lock() + if !p.running && p.enable { + p.running = true + plugins[name] = p + p.plugin.Load() + } + //p.mux.Unlock() + } +} + +func stopPlugin(name string) { + if p, ok := plugins[name]; ok { + //p.mux.Lock() + if p.running { + p.running = false + plugins[name] = p + p.plugin.Unload() + } + //p.mux.Unlock() + } +} + +func Exit() { + for _, p := range plugins { + if p.running { + p.plugin.Unload() + } + } +} diff --git a/plugin_manager/tools.go b/plugin_manager/tools.go new file mode 100644 index 0000000..436eb06 --- /dev/null +++ b/plugin_manager/tools.go @@ -0,0 +1,57 @@ +/** + * @Author: KLIPFEL Arthur + * @Date: 2018-08-24 12:17:17 + */ +package plugin_manager + +import ( + tb "gopkg.in/tucnak/telebot.v2" + "io/ioutil" + "log" + "plugin" + "strings" +) + +type Plugin interface { + Load() + HandleMessage(bot *tb.Bot, msg string) + Unload() +} + +func GetSoFiles(dir string) []string { + var slice []string + + files, err := ioutil.ReadDir(dir) + if err != nil { + log.Fatal(err) + } else { + for _, f := range files { + if strings.HasSuffix(f.Name(), ".so") { + slice = append(slice, f.Name()) + } + } + } + return slice +} + +func LoadSoFile(file string) Plugin { + plug, err := plugin.Open(file) + if err != nil { + log.Fatal(err) + return nil + } + + symPlugin, err := plug.Lookup("Plugin") + if err != nil { + log.Fatal(err) + return nil + } + + var plugin Plugin + plugin, ok := symPlugin.(Plugin) + if !ok { + log.Fatal(file + ": unexpected type from module symbol") + return nil + } + return plugin +} diff --git a/settings.json b/settings.json index f6f81c4..e3860c6 100644 --- a/settings.json +++ b/settings.json @@ -1,4 +1,4 @@ { - "token": "INSERT TOKEN HERE", + "token": "646721001:AAHuCB0uqW1u94GD_BGTUrz-ECaGwGJRm2E", "history size": 10 -} \ No newline at end of file +} From 54c3bc8f59ec8289595fd8d373488a17fbb63d63 Mon Sep 17 00:00:00 2001 From: KLIPFEL Arthur Date: Wed, 25 Jul 2018 11:23:11 +0200 Subject: [PATCH 2/3] plugin manager qui fonctionne --- plugin.go | 68 ++++++++++++++++++++++++++++++++ plugin/test.go | 22 ----------- plugin_manager/manager.go | 56 +++++++++++++++++++++++--- plugin_manager/tools.go | 78 +++++++++++++++++++++++++++++++++++-- test.go | 40 +++++++++++++++++++ plugin/test2.go => test2.go | 0 6 files changed, 232 insertions(+), 32 deletions(-) create mode 100644 plugin.go delete mode 100644 plugin/test.go create mode 100644 test.go rename plugin/test2.go => test2.go (100%) diff --git a/plugin.go b/plugin.go new file mode 100644 index 0000000..0408dac --- /dev/null +++ b/plugin.go @@ -0,0 +1,68 @@ +package main + +import ( + "./plugin_manager" + tb "gopkg.in/tucnak/telebot.v2" +) + +type plugin string + +func (g plugin) GetCommands() []string { + return []string{"plugin"} +} + +func (g plugin) HandleCommand(bot *tb.Bot, msg *tb.Message, cmd string, args []string) { + if cmd == "plugin" { + ok := false + if len(args) >= 1 { + if args[0] == "list" { + lst := "" + for _, pName := range plugin_manager.GetPluginList() { + lst = lst + "-" + pName + " (status: " + if plugin_manager.IsPluginEnable(pName) { + lst += "enable, " + } else { + lst += "disable, " + } + if plugin_manager.IsPluginRunning(pName) { + lst += "running" + } else { + lst += "stopped" + } + lst += ")\n" + } + bot.Send(msg.Chat, "liste des plugins disponible:\n"+lst) + ok = true + } + if args[0] == "enable" && len(args) >= 2 { + for _, name := range args[1:] { + if plugin_manager.ExistPlugin(name) { + plugin_manager.EnablePlugin(name, true) + bot.Send(msg.Chat, "enable plugin "+name) + } + } + ok = true + } + if args[0] == "disable" && len(args) >= 2 { + for _, name := range args[1:] { + if plugin_manager.ExistPlugin(name) { + plugin_manager.EnablePlugin(name, false) + bot.Send(msg.Chat, "disable plugin "+name) + } + } + ok = true + } + } + if !ok { + bot.Send(msg.Chat, "command inconnue\n"+ + "liste de plugin:\n"+ + "/plugin list\n"+ + "activer un/des plugins\n"+ + "/plugin enable nom_plugin\n"+ + "désactiver un/des plugins\n"+ + "/plugin disable nom_plugin") + } + } +} + +var Plugin plugin diff --git a/plugin/test.go b/plugin/test.go deleted file mode 100644 index 7e84ec2..0000000 --- a/plugin/test.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - tb "gopkg.in/tucnak/telebot.v2" - "log" -) - -type plugin string - -func (g plugin) Load() { - log.Println("plugin test loaded!") -} - -func (g plugin) HandleMessage(bot *tb.Bot, msg string) { - log.Println("test message: " + msg) -} - -func (g plugin) Unload() { - log.Println("plugin test unloaded!") -} - -var Plugin plugin diff --git a/plugin_manager/manager.go b/plugin_manager/manager.go index 186da86..919a7ae 100644 --- a/plugin_manager/manager.go +++ b/plugin_manager/manager.go @@ -7,6 +7,7 @@ package plugin_manager import ( tb "gopkg.in/tucnak/telebot.v2" "log" + "strings" "sync" ) @@ -38,6 +39,42 @@ func Init(_pluginDir string, bot *tb.Bot) { } } +func GetPluginList() []string { + var lst []string + for name, _ := range plugins { + lst = append(lst, name) + } + return lst +} + +func IsPluginRunning(name string) bool { + if p, ok := plugins[name]; ok { + return p.running + } + return false +} + +func ExistPlugin(name string) bool { + if _, ok := plugins[name]; ok { + return true + } + return false +} + +func GetPlugin(name string) Plugin { + if p, ok := plugins[name]; ok { + return p + } + return nil +} + +func IsPluginEnable(name string) bool { + if p, ok := plugins[name]; ok { + return p.enable + } + return false +} + func EnablePlugin(name string, enable bool) { if p, ok := plugins[name]; ok { if enable != p.enable { @@ -69,8 +106,16 @@ func StopPlugins() { func HandleMessage(msg *tb.Message) { for _, val := range plugins { - if val.enable { - val.plugin.HandleMessage(context.bot, msg.Text) + if val.enable && val.running { + if strings.HasPrefix(msg.Text, "/") { + split := strings.Split(msg.Text, " ") + split[0] = split[0][1:] + if Contains(split[0], ExecGetCommands(val.plugin)) { + ExecHandleCommand(val.plugin, context.bot, msg, split[0], split[1:]) + } + } else { + ExecHandleMessage(val.plugin, context.bot, msg) + } } } } @@ -88,9 +133,8 @@ func startPlugin(name string) { if p, ok := plugins[name]; ok { //p.mux.Lock() if !p.running && p.enable { - p.running = true + p.running = ExecLoad(p.plugin) plugins[name] = p - p.plugin.Load() } //p.mux.Unlock() } @@ -102,7 +146,7 @@ func stopPlugin(name string) { if p.running { p.running = false plugins[name] = p - p.plugin.Unload() + ExecUnload(p.plugin) } //p.mux.Unlock() } @@ -111,7 +155,7 @@ func stopPlugin(name string) { func Exit() { for _, p := range plugins { if p.running { - p.plugin.Unload() + ExecUnload(p.plugin) } } } diff --git a/plugin_manager/tools.go b/plugin_manager/tools.go index 436eb06..3e15f72 100644 --- a/plugin_manager/tools.go +++ b/plugin_manager/tools.go @@ -12,10 +12,32 @@ import ( "strings" ) -type Plugin interface { - Load() - HandleMessage(bot *tb.Bot, msg string) - Unload() +type TestGetCommands interface { + GetCommands() []string +} + +type TestLoad interface { + Load() bool +} + +type TestHandleMessage interface { + HandleMessage(bot *tb.Bot, msg *tb.Message) +} + +type TestHandleCommand interface { + HandleCommand(bot *tb.Bot, msg *tb.Message, cmd string, args []string) +} + +type TestUnload interface { + Unload() bool +} + +type Plugin interface { /* + GetCommandes() []string + Load() bool + HandleMessage(bot *tb.Bot, msg *tb.Message) + HandleCommand(bot *tb.Bot, msg *tb.Message, cmd string, args []string) + Unload() bool*/ } func GetSoFiles(dir string) []string { @@ -48,6 +70,7 @@ func LoadSoFile(file string) Plugin { } var plugin Plugin + //plugin, _ = symPlugin.(Plugin) plugin, ok := symPlugin.(Plugin) if !ok { log.Fatal(file + ": unexpected type from module symbol") @@ -55,3 +78,50 @@ func LoadSoFile(file string) Plugin { } return plugin } + +func ExecGetCommands(plugin Plugin) []string { + p, ok := plugin.(TestGetCommands) + if ok { + return p.GetCommands() + } + return []string{} +} + +func ExecLoad(plugin Plugin) bool { + p, ok := plugin.(TestLoad) + if ok { + return p.Load() + } + return true +} + +func ExecHandleMessage(plugin Plugin, bot *tb.Bot, msg *tb.Message) { + p, ok := plugin.(TestHandleMessage) + if ok { + p.HandleMessage(bot, msg) + } +} + +func ExecHandleCommand(plugin Plugin, bot *tb.Bot, msg *tb.Message, cmd string, args []string) { + p, ok := plugin.(TestHandleCommand) + if ok { + p.HandleCommand(bot, msg, cmd, args) + } +} + +func ExecUnload(plugin Plugin) bool { + p, ok := plugin.(TestUnload) + if ok { + return p.Unload() + } + return true +} + +func Contains(e string, s []string) bool { + for _, a := range s { + if a == e { + return true + } + } + return false +} diff --git a/test.go b/test.go new file mode 100644 index 0000000..6fc0446 --- /dev/null +++ b/test.go @@ -0,0 +1,40 @@ +package main + +import ( + tb "gopkg.in/tucnak/telebot.v2" + "log" +) + +type plugin string + +func (g plugin) GetCommands() []string { + return []string{"ping", "test"} +} + +func (g plugin) Load() bool { + log.Println("plugin test loaded!") + return true +} + +func (g plugin) HandleMessage(bot *tb.Bot, msg *tb.Message) { + log.Println("plugin test message: " + msg.Text) +} + +func (g plugin) HandleCommand(bot *tb.Bot, msg *tb.Message, cmd string, args []string) { + if cmd == "ping" { + bot.Send(msg.Chat, "pong!") + } + argsS := "" + for _, arg := range args { + argsS = argsS + " " + arg + } + log.Print("plugin test cmd: " + cmd + " (args:" + argsS + ")") + +} + +func (g plugin) Unload() bool { + log.Println("plugin test unloaded!") + return true +} + +var Plugin plugin diff --git a/plugin/test2.go b/test2.go similarity index 100% rename from plugin/test2.go rename to test2.go From d5a79227792757222303161a526f5a15aa6ecfae Mon Sep 17 00:00:00 2001 From: KLIPFEL Arthur Date: Wed, 25 Jul 2018 11:57:15 +0200 Subject: [PATCH 3/3] merge --- .gitignore | 4 ++- alfred.go | 52 ++++++++++++---------------- commands/dice.go | 30 ++++++++++++++++ commands/framapad.go | 17 +++++++++ commands/gender.go | 68 ++++++++++++++++++++++++++++++++++++ commands/git.go | 17 +++++++++ commands/hello.go | 17 +++++++++ commands/on_text.go | 17 +++++++++ commands/sponge.go | 27 +++++++++++++++ settings.json | 7 ++-- shared/bot.go | 14 ++++++++ shared/history.go | 45 ++++++++++++++++++++++-- shared/users.go | 82 ++++++++++++++++++++++++++++++++++++++++++++ 13 files changed, 360 insertions(+), 37 deletions(-) create mode 100644 commands/dice.go create mode 100644 commands/framapad.go create mode 100644 commands/gender.go create mode 100644 commands/git.go create mode 100644 commands/hello.go create mode 100644 commands/on_text.go create mode 100644 commands/sponge.go create mode 100644 shared/bot.go create mode 100644 shared/users.go diff --git a/.gitignore b/.gitignore index b23330f..ee19125 100644 --- a/.gitignore +++ b/.gitignore @@ -14,4 +14,6 @@ # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 .glide/ -settings_custom.json \ No newline at end of file +settings_custom.json +history.json +users.json \ No newline at end of file diff --git a/alfred.go b/alfred.go index cad1f1c..cef024c 100644 --- a/alfred.go +++ b/alfred.go @@ -2,28 +2,42 @@ * @Author: Bartuccio Antoine * @Date: 2018-07-23 15:24:22 * @Last Modified by: klmp200 -* @Last Modified time: 2018-07-24 03:05:51 +* @Last Modified time: 2018-07-24 20:55:53 */ package main import ( + "./commands" "./plugin_manager" "./settings" "./shared" tb "gopkg.in/tucnak/telebot.v2" "log" - "strings" "time" ) func main() { + registered_commands := map[string]func(*tb.Message){ + tb.OnText: commands.OnText, + "/hello": commands.Hello, + "/sponge": commands.Sponge, + "/git": commands.Git, + "/framapad": commands.Framapad, + "/setgender": commands.SetGender, + "/gender": commands.Gender, + "/roll": commands.Dice, + } + if err := settings.LoadSettings("settings.json", "settings_custom.json"); err != nil { log.Fatal(err) } log.Println("Initialize history") - shared.InitHistory(int(settings.Settings["history size"].(float64))) + shared.InitHistory(int(settings.Settings["history size"].(float64)), + settings.Settings["history file"].(string)) + log.Println("Initialize users infos") + shared.InitUsers(settings.Settings["users file"].(string)) log.Println("Bot initialisation") b, err := tb.NewBot(tb.Settings{ @@ -34,35 +48,11 @@ func main() { log.Fatal(err) return } + shared.Bot = b - b.Handle("/hello", func(m *tb.Message) { - b.Send(m.Chat, "Bonjour "+m.Sender.Username) - }) - - b.Handle(tb.OnText, func(m *tb.Message) { - shared.History.AddMessage(m.Chat.ID, m.Text) - }) - - b.Handle("/sponge", func(m *tb.Message) { - message := "" - for i, char := range shared.History.LastMessage(m.Chat.ID) { - if i%2 == 0 { - message += strings.ToLower(string(char)) - } else { - message += strings.ToUpper(string(char)) - } - } - b.Send(m.Chat, message) - - }) - - b.Handle("/git", func(m *tb.Message) { - b.Send(m.Chat, "Mon code est accessible librement à l'adresse https://git.klmp200.net/ALFRED/ALFRED. Venez contribuer :)") - }) - - b.Handle("/framapad", func(m *tb.Message) { - b.Send(m.Chat, "Venez participer à mon développement en posant vos idées ici : https://mensuel.framapad.org/p/ALFRED2LERETOUR.") - }) + for key, value := range registered_commands { + b.Handle(key, value) + } plugin_manager.Init("plugin", b) b.Handle(tb.OnText, plugin_manager.HandleMessage) diff --git a/commands/dice.go b/commands/dice.go new file mode 100644 index 0000000..5a30a68 --- /dev/null +++ b/commands/dice.go @@ -0,0 +1,30 @@ +/* +* @Author: Bartuccio Antoine +* @Date: 2018-07-24 20:50:04 +* @Last Modified by: klmp200 +* @Last Modified time: 2018-07-24 21:00:59 + */ + +package commands + +import ( + "../shared" + tb "gopkg.in/tucnak/telebot.v2" + "math/rand" + "strconv" + "strings" +) + +func Dice(m *tb.Message) { + split := strings.Split(m.Text, " ") + if len(split) < 2 { + shared.Bot.Send(m.Chat, "Pour lancer un dé, il faut préciser combien de faces il a.") + return + } + up, err := strconv.Atoi(split[1]) + if err != nil || up <= 0 { + shared.Bot.Send(m.Chat, split[1]+" n'est pas un nombre valide.") + return + } + shared.Bot.Send(m.Chat, strconv.Itoa(rand.Intn(up+1))) +} diff --git a/commands/framapad.go b/commands/framapad.go new file mode 100644 index 0000000..31fc4c2 --- /dev/null +++ b/commands/framapad.go @@ -0,0 +1,17 @@ +/* +* @Author: Bartuccio Antoine +* @Date: 2018-07-24 12:11:26 +* @Last Modified by: klmp200 +* @Last Modified time: 2018-07-24 12:12:58 + */ + +package commands + +import ( + "../shared" + tb "gopkg.in/tucnak/telebot.v2" +) + +func Framapad(m *tb.Message) { + shared.Bot.Send(m.Chat, "Venez participer à mon développement en posant vos idées ici : https://mensuel.framapad.org/p/ALFRED2LERETOUR.") +} diff --git a/commands/gender.go b/commands/gender.go new file mode 100644 index 0000000..b126dbf --- /dev/null +++ b/commands/gender.go @@ -0,0 +1,68 @@ +/* +* @Author: Bartuccio Antoine +* @Date: 2018-07-24 14:55:33 +* @Last Modified by: klmp200 +* @Last Modified time: 2018-07-24 20:29:36 + */ + +package commands + +import ( + "../shared" + tb "gopkg.in/tucnak/telebot.v2" + "strings" +) + +func SetGender(m *tb.Message) { + if m.Sender.Username == "" { + shared.Bot.Send(m.Chat, "Il faut avoir enregistré un username pour pouvoir utiliser cette fonction") + return + } + split := cleanGender(strings.Split(m.Text, " ")[1:]) + if len(split) == 0 { + shared.Bot.Send(m.Chat, "Désolé, mais je n'ai pas compris.") + return + } + data := strings.Join(split, " ") + shared.Users.Set(m.Sender.Username, "gender", data) + shared.Bot.Send(m.Chat, "Votre genre est enregistré, je vous considère maintenant comme « "+data+" ».") +} + +func Gender(m *tb.Message) { + split := strings.Split(m.Text, " ") + if len(split) > 1 { + // Username asked + username := split[1] + username = strings.Replace(username, "@", "", 1) + data, exists := shared.Users.Get(username, "gender") + if !exists { + shared.Bot.Send(m.Chat, username+" n'est pas un utilisateur existant ou n'a pas renseigné son genre.") + return + } + shared.Bot.Send(m.Chat, "L'utilisateur "+username+" a pour genre « "+data+" ».") + } else { + data, exists := shared.Users.Get(m.Sender.Username, "gender") + if !exists { + shared.Bot.Send(m.Chat, "Vous n'avez pas enregistré votre genre, je ne voudrais pas l'assumer.") + } else { + shared.Bot.Send(m.Chat, data) + } + } +} + +func cleanGender(slice []string) []string { + for i := range slice { + clean := false + for !clean { + clean = true + if strings.HasPrefix(slice[i], "@") { + slice[i] = strings.Replace(slice[i], "@", "", 1) + clean = false + } else if strings.HasPrefix(slice[i], "/") { + slice[i] = strings.Replace(slice[i], "/", "", 1) + clean = false + } + } + } + return slice +} diff --git a/commands/git.go b/commands/git.go new file mode 100644 index 0000000..29a9c4a --- /dev/null +++ b/commands/git.go @@ -0,0 +1,17 @@ +/* +* @Author: Bartuccio Antoine +* @Date: 2018-07-24 12:07:34 +* @Last Modified by: klmp200 +* @Last Modified time: 2018-07-24 12:08:49 + */ + +package commands + +import ( + "../shared" + tb "gopkg.in/tucnak/telebot.v2" +) + +func Git(m *tb.Message) { + shared.Bot.Send(m.Chat, "Mon code source est accessible librement à l'adresse https://git.klmp200.net/ALFRED/ALFRED. Venez contribuer :)") +} diff --git a/commands/hello.go b/commands/hello.go new file mode 100644 index 0000000..bbb0f70 --- /dev/null +++ b/commands/hello.go @@ -0,0 +1,17 @@ +/* +* @Author: Bartuccio Antoine +* @Date: 2018-07-24 12:05:45 +* @Last Modified by: klmp200 +* @Last Modified time: 2018-07-24 12:06:39 + */ + +package commands + +import ( + "../shared" + tb "gopkg.in/tucnak/telebot.v2" +) + +func Hello(m *tb.Message) { + shared.Bot.Send(m.Chat, "Bonjour "+m.Sender.Username) +} diff --git a/commands/on_text.go b/commands/on_text.go new file mode 100644 index 0000000..c5db4a8 --- /dev/null +++ b/commands/on_text.go @@ -0,0 +1,17 @@ +/* +* @Author: Bartuccio Antoine +* @Date: 2018-07-24 12:09:37 +* @Last Modified by: klmp200 +* @Last Modified time: 2018-07-24 12:10:26 + */ + +package commands + +import ( + "../shared" + tb "gopkg.in/tucnak/telebot.v2" +) + +func OnText(m *tb.Message) { + shared.History.AddMessage(m.Chat.ID, m.Text) +} diff --git a/commands/sponge.go b/commands/sponge.go new file mode 100644 index 0000000..009ba5c --- /dev/null +++ b/commands/sponge.go @@ -0,0 +1,27 @@ +/* +* @Author: Bartuccio Antoine +* @Date: 2018-07-24 11:52:11 +* @Last Modified by: klmp200 +* @Last Modified time: 2018-07-24 11:58:42 + */ + +package commands + +import ( + "../shared" + tb "gopkg.in/tucnak/telebot.v2" + "strings" +) + +func Sponge(m *tb.Message) { + message := "" + for i, char := range shared.History.LastMessage(m.Chat.ID) { + if i%2 == 0 { + message += strings.ToLower(string(char)) + } else { + message += strings.ToUpper(string(char)) + } + } + shared.Bot.Send(m.Chat, message) + +} diff --git a/settings.json b/settings.json index e3860c6..b6f49e1 100644 --- a/settings.json +++ b/settings.json @@ -1,4 +1,7 @@ { - "token": "646721001:AAHuCB0uqW1u94GD_BGTUrz-ECaGwGJRm2E", - "history size": 10 + + "token": "INSERT TOKEN HERE", + "history size": 10, + "history file": "history.json", + "users file": "users.json" } diff --git a/shared/bot.go b/shared/bot.go new file mode 100644 index 0000000..9880987 --- /dev/null +++ b/shared/bot.go @@ -0,0 +1,14 @@ +/* +* @Author: Bartuccio Antoine +* @Date: 2018-07-24 11:56:47 +* @Last Modified by: klmp200 +* @Last Modified time: 2018-07-24 11:58:34 + */ + +package shared + +import ( + tb "gopkg.in/tucnak/telebot.v2" +) + +var Bot *tb.Bot diff --git a/shared/history.go b/shared/history.go index 0dc315e..406392b 100644 --- a/shared/history.go +++ b/shared/history.go @@ -2,12 +2,14 @@ * @Author: Bartuccio Antoine * @Date: 2018-07-24 01:27:11 * @Last Modified by: klmp200 -* @Last Modified time: 2018-07-24 02:09:53 +* @Last Modified time: 2018-07-24 12:54:21 */ package shared import ( + "encoding/json" + "io/ioutil" "sync" ) @@ -17,22 +19,34 @@ type history struct { data map[int64][]string } -var History history +type historyFile struct { + mutex sync.Mutex + path string +} -func InitHistory(size int) { +var History history +var hf historyFile + +// Init a chat history of a given size +func InitHistory(size int, history_file_path string) { + hf = historyFile{} + hf.path = history_file_path History = history{} History.mutex.Lock() defer History.mutex.Unlock() History.size = size History.data = make(map[int64][]string) + hf.read() } +// Get the number of messages saved in the history func (h history) Size() int { h.mutex.Lock() defer h.mutex.Unlock() return h.size } +// Get a selected message in a chat history func (h history) Message(chatID int64, n int) string { h.mutex.Lock() defer h.mutex.Unlock() @@ -43,6 +57,7 @@ func (h history) Message(chatID int64, n int) string { return "" } +// Append a message to a given chat func (h history) AddMessage(chatID int64, m string) { h.mutex.Lock() defer h.mutex.Unlock() @@ -52,6 +67,7 @@ func (h history) AddMessage(chatID int64, m string) { h.append(chatID, m) } +// Get the last message of a given chat func (h history) LastMessage(chatID int64) string { h.mutex.Lock() defer h.mutex.Unlock() @@ -61,6 +77,7 @@ func (h history) LastMessage(chatID int64) string { return "" } +// Get a copy of a given chat history func (h history) ChatHistory(chatID int64) []string { h.mutex.Lock() defer h.mutex.Unlock() @@ -73,6 +90,7 @@ func (h history) ChatHistory(chatID int64) []string { return nil } +// Add a message at the end of a chat and move everithyng up // Assert that the slice exists and mutex already locked func (h history) append(chatID int64, m string) { c := make([]string, h.size-1, h.size-1) @@ -82,4 +100,25 @@ func (h history) append(chatID int64, m string) { array[i] = val } array[h.size-1] = m + go hf.write() +} + +func (h historyFile) read() { + h.mutex.Lock() + defer h.mutex.Unlock() + data, err := ioutil.ReadFile(h.path) + if err != nil { + // File doesn't exist, skip import + return + } + json.Unmarshal(data, &History.data) +} + +func (h historyFile) write() { + h.mutex.Lock() + defer h.mutex.Unlock() + History.mutex.Lock() + defer History.mutex.Unlock() + data, _ := json.Marshal(History.data) + ioutil.WriteFile(h.path, data, 0770) } diff --git a/shared/users.go b/shared/users.go new file mode 100644 index 0000000..ebb78f8 --- /dev/null +++ b/shared/users.go @@ -0,0 +1,82 @@ +/* +* @Author: Bartuccio Antoine +* @Date: 2018-07-24 14:41:03 +* @Last Modified by: klmp200 +* @Last Modified time: 2018-07-24 17:49:51 + */ + +package shared + +import ( + "encoding/json" + "io/ioutil" + "sync" +) + +type users struct { + mutex sync.Mutex + data map[string]map[string]string +} + +type usersFile struct { + mutex sync.Mutex + path string +} + +var Users users +var uf usersFile + +func InitUsers(users_file_path string) { + uf = usersFile{} + uf.path = users_file_path + Users = users{} + Users.mutex.Lock() + defer Users.mutex.Unlock() + Users.data = make(map[string]map[string]string) + uf.read() +} + +// Get an info about a given user +func (u users) Get(username string, key string) (string, bool) { + u.mutex.Lock() + defer u.mutex.Unlock() + user, exists := u.data[username] + if !exists { + return "", false + } + if _, exists = user[key]; !exists { + return "", false + } + return user[key], true +} + +// Add an info about a given user +func (u users) Set(username string, key, data string) { + u.mutex.Lock() + defer u.mutex.Unlock() + if _, exists := u.data[username]; !exists { + u.data[username] = make(map[string]string) + } + u.data[username][key] = data + go uf.write() +} + +func (u usersFile) read() { + u.mutex.Lock() + defer u.mutex.Unlock() + data, err := ioutil.ReadFile(u.path) + if err != nil { + // File doesn't exist, skip import + return + } + json.Unmarshal(data, &Users.data) +} + +func (u usersFile) write() { + u.mutex.Lock() + defer u.mutex.Unlock() + Users.mutex.Lock() + defer Users.mutex.Unlock() + data, _ := json.Marshal(Users.data) + ioutil.WriteFile(u.path, data, 0770) +}