Skip to content

Commit

Permalink
Merge pull request #12 from mattermost/revert-11
Browse files Browse the repository at this point in the history
Revert #11
  • Loading branch information
cpoile authored Jun 3, 2019
2 parents 8c8df72 + b6d777f commit 3cbf576
Show file tree
Hide file tree
Showing 9 changed files with 405 additions and 401 deletions.
22 changes: 20 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,24 @@ module github.com/mattermost/mattermost-plugin-welcomebot/server
go 1.12

require (
github.com/mattermost/mattermost-server v0.0.0-20190508185452-66cb36f5dc35
github.com/pkg/errors v0.8.1
github.com/BurntSushi/toml v0.3.1 // indirect
github.com/google/uuid v1.0.0 // indirect
github.com/gorilla/websocket v0.0.0-20181030144553-483fb8d7c32f // indirect
github.com/hashicorp/go-hclog v0.0.0-20180402200405-69ff559dc25f // indirect
github.com/hashicorp/go-plugin v0.0.0-20180331002553-e8d22c780116 // indirect
github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d // indirect
github.com/mattermost/mattermost-server v5.4.0+incompatible
github.com/mattermost/viper v1.0.4 // indirect
github.com/mitchellh/go-testing-interface v1.0.0 // indirect
github.com/nicksnyder/go-i18n v1.10.0 // indirect
github.com/oklog/run v1.0.0 // indirect
github.com/pborman/uuid v0.0.0-20180906182336-adf5a7427709 // indirect
github.com/pkg/errors v0.8.0
go.uber.org/atomic v1.3.2 // indirect
go.uber.org/multierr v1.1.0 // indirect
go.uber.org/zap v1.9.1 // indirect
golang.org/x/net v0.0.0-20181102091132-c10e9556a7bc // indirect
google.golang.org/genproto v0.0.0-20181101192439-c830210a61df // indirect
google.golang.org/grpc v1.16.0 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.0.0-20170531160350-a96e63847dc3 // indirect
)
368 changes: 18 additions & 350 deletions go.sum

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion plugin.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
"name": "Welcome Bot",
"description": "This plugin adds a WelcomeBot that helps add new users to channels.",
"version": "0.0.1",
"min_server_version": "5.12.0",
"server": {
"executables": {
"linux-amd64": "server/dist/plugin-linux-amd64",
Expand Down
61 changes: 61 additions & 0 deletions server/command_hooks.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package main

import (
"fmt"
"strings"

"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/plugin"
)

// RegisterCommand to registers welcomebot commands
func (p *Plugin) RegisterCommand(teamID string) error {
if err := p.API.RegisterCommand(&model.Command{
TeamId: teamID,
Trigger: welcomeBotUsername,
AutoComplete: true,
AutoCompleteHint: "[team_name]",
AutoCompleteDesc: "Re-runs the welcomebot for the supplied team",
DisplayName: "WelcomeBot Command",
Description: "Re-runs the welcomebot with the supplied team",
}); err != nil {
p.API.LogError(
"failed to register command",
"error", err.Error(),
)
}

return nil
}

// ExecuteCommand executes a command that has been previously registered via the RegisterCommand
// API.
func (p *Plugin) ExecuteCommand(c *plugin.Context, args *model.CommandArgs) (*model.CommandResponse, *model.AppError) {
if !strings.HasPrefix(args.Command, "/"+welcomeBotUsername) {
return &model.CommandResponse{
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
Text: fmt.Sprintf("Unknown command: " + args.Command),
}, nil
}

team, _ := p.API.GetTeamByName(args.Command)
if team == nil {
return &model.CommandResponse{
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
Text: fmt.Sprintf("Unknown team name: " + args.Command),
}, nil
}

teamMember, _ := p.API.GetTeamMember(team.Id, args.UserId)
if teamMember == nil {
return &model.CommandResponse{
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
Text: fmt.Sprintf("You do not appear to be part of the team: " + args.Command),
}, nil
}

return &model.CommandResponse{
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
Text: fmt.Sprintf("TODO re-run the WelcomeBot"),
}, nil
}
50 changes: 47 additions & 3 deletions server/configuration.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
package main

const (
actionTypeAutomatic = "automatic"
actionTypeButton = "button"
import (
"crypto/rand"
"encoding/base64"
"fmt"

"github.com/mattermost/mattermost-server/model"
)

const welcomeBotUsername = "welcomebot"
const actionTypeAutomatic = "automatic"
const actionTypeButton = "button"

// ConfigMessageAction are actions that can be taken from the welcome message
type ConfigMessageAction struct {
// The action type of button or automatic
Expand Down Expand Up @@ -62,5 +69,42 @@ func (p *Plugin) OnConfigurationChange() error {

p.welcomeMessages.Store(c.WelcomeMessages)

if err := p.ensureWelcomeBotUser(); err != nil {
p.API.LogError(err.Error())
return err
}

return nil
}

func (p *Plugin) ensureWelcomeBotUser() *model.AppError {
var err *model.AppError

user, _ := p.API.GetUserByUsername(welcomeBotUsername)

// Ensure the configured user exists.
if user == nil {
randBytes := make([]byte, 15)
rand.Read(randBytes)
password := base64.StdEncoding.EncodeToString(randBytes)
fmt.Println(password)

user, err = p.API.CreateUser(&model.User{
Username: welcomeBotUsername,
Password: password,
Email: fmt.Sprintf("%[email protected]", welcomeBotUsername),
Nickname: "Welcome Bot",
FirstName: "Welcome",
LastName: "Bot",
Position: "Bot",
})

if err != nil {
return err
}
}

p.welcomeBotUserID = user.Id

return nil
}
123 changes: 108 additions & 15 deletions server/http_hooks.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package main

import (
"bytes"
"encoding/json"
"html/template"
"net/http"

"github.com/mattermost/mattermost-server/model"
Expand All @@ -12,8 +14,10 @@ import (
// /plugins/{id} path will be routed to the plugin.
func (p *Plugin) ServeHTTP(c *plugin.Context, w http.ResponseWriter, r *http.Request) {
var action *Action
if err := json.NewDecoder(r.Body).Decode(&action); err != nil || action == nil {
p.encodeEphermalMessage(w, "WelcomeBot Error: We could not decode the action")
json.NewDecoder(r.Body).Decode(&action)

if action == nil {
encodeEphermalMessage(w, "WelcomeBot Error: We could not decode the action")
return
}

Expand All @@ -22,19 +26,19 @@ func (p *Plugin) ServeHTTP(c *plugin.Context, w http.ResponseWriter, r *http.Req

if data.User, err = p.API.GetUser(action.Context.UserID); err != nil {
p.API.LogError("failed to query user", "user_id", action.Context.UserID)
p.encodeEphermalMessage(w, "WelcomeBot Error: We could not find the supplied user")
encodeEphermalMessage(w, "WelcomeBot Error: We could not find the supplied user")
return
}

if data.Team, err = p.API.GetTeam(action.Context.TeamID); err != nil {
p.API.LogError("failed to query team", "team_id", action.Context.TeamID)
p.encodeEphermalMessage(w, "WelcomeBot Error: We could not find the supplied team")
encodeEphermalMessage(w, "WelcomeBot Error: We could not find the supplied team")
return
}

if data.DirectMessage, err = p.API.GetDirectChannel(action.Context.UserID, p.botUserID); err != nil {
if data.DirectMessage, err = p.API.GetDirectChannel(action.Context.UserID, p.welcomeBotUserID); err != nil {
p.API.LogError("failed to query direct message channel", "user_id", action.Context.UserID)
p.encodeEphermalMessage(w, "WelcomeBot Error: We could not find the welcome bot direct message channel")
encodeEphermalMessage(w, "WelcomeBot Error: We could not find the welcome bot direct message channel")
return
}

Expand All @@ -43,38 +47,127 @@ func (p *Plugin) ServeHTTP(c *plugin.Context, w http.ResponseWriter, r *http.Req
// Check to make sure you're still in the team
if teamMember, err := p.API.GetTeamMember(action.Context.TeamID, action.Context.UserID); err != nil || teamMember == nil || teamMember.DeleteAt > 0 {
p.API.LogError("Didn't have access to team", "user_id", action.Context.UserID, "team_id", action.Context.TeamID)
p.encodeEphermalMessage(w, "WelcomeBot Error: You do not appear to have access to this team")
encodeEphermalMessage(w, "WelcomeBot Error: You do not appear to have access to this team")
return
}

switch r.URL.Path {
case "/addchannels":

for _, wm := range p.getWelcomeMessages() {

if data.Team.Name == wm.TeamName {
for _, ac := range wm.Actions {
if ac.ActionName == action.Context.Action {
p.processActionMessage(*data, action, *ac)
p.encodeEphermalMessage(w, "")
encodeEphermalMessage(w, "")
return
}
}
}
}

p.encodeEphermalMessage(w, "WelcomeBot Error: The action wasn't found for "+action.Context.Action)
encodeEphermalMessage(w, "WelcomeBot Error: The action wasn't found for "+action.Context.Action)
default:
http.NotFound(w, r)
}
}

func (p *Plugin) encodeEphermalMessage(w http.ResponseWriter, message string) {
w.Header().Set("Content-Type", "application/json")
func (p *Plugin) handleSupport(action *Action, data *MessageTemplate) {
p.joinChannel(action, "peer-to-peer-help")
p.joinChannel(action, "bugs")

template, _ := template.New("Response").Parse(
`### Awesome, I have added you to the following support related channels!
~peer-to-peer-help - General help and setup
~bugs - To help investigate or report bugs
`)
var message bytes.Buffer
template.Execute(&message, data)

post := &model.Post{
Message: message.String(),
ChannelId: data.DirectMessage.Id,
UserId: p.welcomeBotUserID,
}

if _, err := p.API.CreatePost(post); err != nil {
p.API.LogError(
"We could not create the response post",
"user_id", post.UserId,
"err", err.Error(),
)
}
}

func (p *Plugin) handelDeveloper(action *Action, data *MessageTemplate) {
p.joinChannel(action, "developers")
p.joinChannel(action, "developer-toolkit")
p.joinChannel(action, "developer-performance")
p.joinChannel(action, "bugs")

template, _ := template.New("Response").Parse(
`### Baller, I have added you to the following developer related channels!
~developers - Great for general developer questions
~developer-toolkit - Great questions about plugins or integrations
~developer-meeting - Weekly core staff and community meeting
~developer-performance - Great for questions about performance or load testing
~bugs - To help investigate or report bugs
`)
var message bytes.Buffer
template.Execute(&message, data)

resp := model.PostActionIntegrationResponse{
EphemeralText: message,
post := &model.Post{
Message: message.String(),
ChannelId: data.DirectMessage.Id,
UserId: p.welcomeBotUserID,
}

if _, err := w.Write([]byte(resp.ToJson())); err != nil {
p.API.LogWarn("failed to write PostActionIntegrationResponse")
if _, err := p.API.CreatePost(post); err != nil {
p.API.LogError(
"We could not create the response post",
"user_id", post.UserId,
"err", err.Error(),
)
}
}

func (p *Plugin) handleDoNotKnow(action *Action, data *MessageTemplate) {
p.joinChannel(action, "peer-to-peer-help")
p.joinChannel(action, "feature-ideas")
p.joinChannel(action, "developers")
p.joinChannel(action, "bugs")

template, _ := template.New("Response").Parse(
`### Great, I have added you to a few channels that might be interesting!
~peer-to-peer-help - General help and setup
~feature-ideas - To discuss potential feature ideas
~developers - Great for general developer questions
~bugs - To help investigate or report bugs
`)
var message bytes.Buffer
template.Execute(&message, data)

post := &model.Post{
Message: message.String(),
ChannelId: data.DirectMessage.Id,
UserId: p.welcomeBotUserID,
}

if _, err := p.API.CreatePost(post); err != nil {
p.API.LogError(
"We could not create the response post",
"user_id", post.UserId,
"err", err.Error(),
)
}
}

func encodeEphermalMessage(w http.ResponseWriter, message string) {
w.Header().Set("Content-Type", "application/json")
payload := map[string]interface{}{
"ephemeral_text": message,
}

json.NewEncoder(w).Encode(payload)
}
27 changes: 1 addition & 26 deletions server/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,39 +3,14 @@ package main
import (
"sync/atomic"

"github.com/mattermost/mattermost-server/model"
"github.com/mattermost/mattermost-server/plugin"
"github.com/pkg/errors"
)

const (
botUsername = "welcomebot"
botDisplayName = "Welcomebot"
botDescription = "A bot account created by the Welcomebot plugin."
)

// Plugin represents the welcome bot plugin
type Plugin struct {
plugin.MattermostPlugin

// botUserID of the created bot account.
botUserID string
welcomeBotUserID string

welcomeMessages atomic.Value
}

// OnActivate ensure the bot account exists
func (p *Plugin) OnActivate() error {
bot := &model.Bot{
Username: botUsername,
DisplayName: botDisplayName,
Description: botDescription,
}
botUserID, appErr := p.Helpers.EnsureBot(bot)
if appErr != nil {
return errors.Wrap(appErr, "failed to ensure bot user")
}
p.botUserID = botUserID

return nil
}
Loading

0 comments on commit 3cbf576

Please sign in to comment.