plugin.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // This file is subject to a 1-clause BSD license.
  2. // Its contents can be found in the enclosed LICENSE file.
  3. // Package action binds action commands. These are things like:
  4. //
  5. // <steve> !beer
  6. // * bot hands steve a cold beer.
  7. //
  8. package action
  9. import (
  10. "math/rand"
  11. "time"
  12. "notabug.org/mouz/bot/app/util"
  13. "notabug.org/mouz/bot/irc"
  14. "notabug.org/mouz/bot/irc/cmd"
  15. "notabug.org/mouz/bot/irc/proto"
  16. "notabug.org/mouz/bot/plugins"
  17. )
  18. func init() { plugins.Register(&plugin{}) }
  19. type plugin struct {
  20. cmd *cmd.Set
  21. rng *rand.Rand
  22. }
  23. // Load initializes the module and loads any internal resources
  24. // which may be required.
  25. func (p *plugin) Load(prof irc.Profile) error {
  26. p.cmd = cmd.New(prof.CommandPrefix(), nil)
  27. p.rng = rand.New(rand.NewSource(time.Now().UnixNano()))
  28. // action returns a command handler which presents a channel with
  29. // a random string from the given list.
  30. action := func(set []string) cmd.Handler {
  31. return func(w irc.ResponseWriter, r *irc.Request, params cmd.ParamList) {
  32. targ := r.SenderName
  33. if params.Len() > 0 {
  34. targ = params.String(0)
  35. }
  36. idx := p.rng.Intn(len(set))
  37. msg := util.Action(set[idx], targ)
  38. proto.PrivMsg(w, r.Target, msg)
  39. }
  40. }
  41. // Bind all known actions.
  42. for _, a := range TextActions {
  43. handler := action(a.Answers)
  44. for _, name := range a.Names {
  45. p.cmd.Bind(name, false, handler).
  46. Add(TextUserName, false, cmd.RegAny)
  47. }
  48. }
  49. return nil
  50. }
  51. // Unload cleans the module up and unloads any internal resources.
  52. func (p *plugin) Unload(prof irc.Profile) error {
  53. return nil
  54. }
  55. // Dispatch sends the given, incoming IRC message to the plugin for
  56. // processing as it sees fit.
  57. func (p *plugin) Dispatch(w irc.ResponseWriter, r *irc.Request) {
  58. p.cmd.Dispatch(w, r)
  59. }