diff --git a/bot.go b/bot.go index d723551..1e56bee 100644 --- a/bot.go +++ b/bot.go @@ -18,6 +18,8 @@ type Bot struct { Debug bool `json:"debug"` // Handler 注册对各种事件的处理 Handler Handler + // handlers 方便调用的 handler + handlers map[string]GeneralHandleType } // Start clients without blocking diff --git a/client.go b/client.go index ae80db8..fad2c48 100644 --- a/client.go +++ b/client.go @@ -2,7 +2,9 @@ package rei import ( "log" + "reflect" "time" + "unsafe" tgba "github.com/go-telegram-bot-api/telegram-bot-api/v5" ) @@ -16,6 +18,19 @@ type TelegramClient struct { // NewTelegramClient ... func NewTelegramClient(c *Bot) (tc TelegramClient) { tc.b = *c + h := reflect.ValueOf(&tc.b.Handler).Elem() + t := h.Type() + tc.b.handlers = make(map[string]GeneralHandleType, 16) + for i := 0; i < h.NumField(); i++ { + f := h.Field(i) + if f.IsZero() { + continue + } + tp := t.Field(i).Name[2:] + log.Println("[INFO] register handler", tp) + handler := f.Interface() + tc.b.handlers[tp] = *(*GeneralHandleType)(unsafe.Add(unsafe.Pointer(&handler), unsafe.Sizeof(uintptr(0)))) + } return } diff --git a/event.go b/event.go index 5160e3f..04fd8e5 100644 --- a/event.go +++ b/event.go @@ -3,7 +3,6 @@ package rei import ( "log" "reflect" - "unsafe" tgba "github.com/go-telegram-bot-api/telegram-bot-api/v5" ) @@ -21,18 +20,17 @@ type Event struct { func (tc *TelegramClient) processEvent(update tgba.Update) { v := reflect.ValueOf(&update).Elem() t := reflect.ValueOf(&update).Elem().Type() - h := reflect.ValueOf(tc.b.Handler) for i := 1; i < v.NumField(); i++ { f := v.Field(i) if f.IsZero() { continue } - m := h.FieldByName("On" + t.Field(i).Name) - if m.IsZero() { + tp := t.Field(i).Name + h, ok := tc.b.handlers[tp] + if !ok { continue } - log.Println("[INFO] processEvent call", "On"+t.Field(i).Name) - handler := m.Interface() - go (*(*GeneralHandleType)(unsafe.Add(unsafe.Pointer(&handler), unsafe.Sizeof(uintptr(0)))))(update.UpdateID, tc, f.UnsafePointer()) + log.Println("[INFO] process", tp, "event") + go h(update.UpdateID, tc, f.UnsafePointer()) } }