func addChannelHistory(s *slack.Slack, db *sql.DB, channel, oldest string) (string, error) { params := slack.NewHistoryParameters() params.Oldest = oldest params.Count = 1000 history, err := s.GetChannelHistory(channel, params) if err != nil { return "", err } for _, msg := range history.Messages { if msg.SubType != "" { continue } fmt.Printf("%s: %s\n", msg.User, msg.Text) ts := timestampToTime(msg.Timestamp) _, err := db.Exec( `INSERT INTO messages(channel_id, user_id, text, timestamp, created_at, updated_at) VALUES(?, ?, ?, ?, NOW(), NOW()) `, channel, msg.User, msg.Text, ts.Format("2006-01-02 15:04:05")) if err != nil { return "", err } } if len(history.Messages) > 0 { return history.Messages[0].Timestamp, nil } return "", nil }
func lastMessageTimestamp(api *slack.Slack, channel slack.Channel) (int64, error) { var latest string for { historyParams := slack.HistoryParameters{Count: 5} if latest != "" { historyParams.Latest = latest } history, err := api.GetChannelHistory(channel.Id, historyParams) if err != nil { return -1, err } if len(history.Messages) == 0 { return -1, nil } for _, msg := range history.Messages { latest = msg.Msg.Timestamp if msg.SubType != "channel_join" && msg.SubType != "channel_leave" { msgStamp := strings.Split(msg.Msg.Timestamp, ".") if timestamp, err := strconv.ParseInt(msgStamp[0], 10, 32); err == nil { return timestamp, nil } } } } }
func fetchChannelHistory(api *slack.Slack, ID string) []slack.Message { historyParams := slack.NewHistoryParameters() historyParams.Count = 1000 // Fetch History history, err := api.GetChannelHistory(ID, historyParams) check(err) messages := history.Messages latest := messages[len(messages)-1].Timestamp for { if history.HasMore != true { break } historyParams.Latest = latest history, err = api.GetChannelHistory(ID, historyParams) check(err) length := len(history.Messages) if length > 0 { latest = history.Messages[length-1].Timestamp messages = append(messages, history.Messages...) } } return messages }