- added separate functions as handlers;

This commit is contained in:
naudachu 2023-11-17 13:47:47 +05:00
parent 972e6564ea
commit f677ec5986
5 changed files with 338 additions and 316 deletions

View File

@ -8,11 +8,11 @@ import (
"github.com/bwmarrin/discordgo"
)
func (h *router) CreateFolderHandler(nameMinLenght int) CommandRoute {
func (c *client) CreateFolderHandler(nameMinLenght int) Command {
const (
nameOption string = "folder_name"
)
return CommandRoute{
return Command{
Command: discordgo.ApplicationCommand{
Name: "folder",
@ -28,64 +28,70 @@ func (h *router) CreateFolderHandler(nameMinLenght int) CommandRoute {
},
},
Handler: func(s *discordgo.Session, i *discordgo.InteractionCreate) {
// Моментальный ответ для избежания столкновения с протуханием токена
initialResponse := discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral,
Content: "👩‍🍳 Cooking your query..",
},
}
s.InteractionRespond(i.Interaction, &initialResponse)
// Определение переменной для ответа
var result string = "unexpected result"
// Определение выбранных вариантов ответа
options := i.ApplicationCommandData().Options
optionMap := make(map[string]*discordgo.ApplicationCommandInteractionDataOption, len(options))
for _, opt := range options {
optionMap[opt.Name] = opt
}
// Creating request:
var req controller.FolderRequest
name, insertedValueNotNil := optionMap[nameOption]
dchan, err := s.Channel(i.ChannelID)
if err != nil {
log.Printf("error while identifying channel: %v", err)
} else {
if dchan.ParentID == h.conf.IsProjectChannel {
req.ChannelID = dchan.ID
if insertedValueNotNil {
req.InsertedName = name.StringValue()
}
} else {
req.ChannelID = ""
if insertedValueNotNil {
req.InsertedName = name.StringValue()
}
}
}
// Making request:
resp := h.controller.CreateFolder(context.TODO(), req)
if resp.Project == nil {
result = "Надо написать имя для папки, или создать папку из проекта!"
} else {
result = resp.Project.DiscordString()
if resp.Message != nil {
result += "Errors: " + resp.Message.Error()
}
}
h.defaultFollowUp(result, s, i)
},
Handler: c.createFolderHandler,
}
}
func (c *client) createFolderHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
const (
nameOption string = "folder_name"
)
// Моментальный ответ для избежания столкновения с протуханием токена
initialResponse := discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral,
Content: "👩‍🍳 Cooking your query..",
},
}
s.InteractionRespond(i.Interaction, &initialResponse)
// Определение переменной для ответа
var result string = "unexpected result"
// Определение выбранных вариантов ответа
options := i.ApplicationCommandData().Options
optionMap := make(map[string]*discordgo.ApplicationCommandInteractionDataOption, len(options))
for _, opt := range options {
optionMap[opt.Name] = opt
}
// Creating request:
var req controller.FolderRequest
name, insertedValueNotNil := optionMap[nameOption]
dchan, err := s.Channel(i.ChannelID)
if err != nil {
log.Printf("error while identifying channel: %v", err)
} else {
if dchan.ParentID == c.conf.IsProjectChannel {
req.ChannelID = dchan.ID
if insertedValueNotNil {
req.InsertedName = name.StringValue()
}
} else {
req.ChannelID = ""
if insertedValueNotNil {
req.InsertedName = name.StringValue()
}
}
}
// Making request:
resp := c.controller.CreateFolder(context.TODO(), req)
if resp.Project == nil {
result = "Надо написать имя для папки, или создать папку из проекта!"
} else {
result = resp.Project.DiscordString()
if resp.Message != nil {
result += "Errors: " + resp.Message.Error()
}
}
c.defaultFollowUp(result, s, i)
}

View File

@ -8,7 +8,7 @@ import (
"github.com/bwmarrin/discordgo"
)
func (h *router) CreateRepoHandler(repoNameMinLength int) CommandRoute {
func (c *client) CreateRepoHandler(repoNameMinLength int) Command {
const (
repoType = "repo_type"
projectRepo = "project_repo"
@ -16,10 +16,10 @@ func (h *router) CreateRepoHandler(repoNameMinLength int) CommandRoute {
nameOption = "repo_name"
)
return CommandRoute{
return Command{
Command: discordgo.ApplicationCommand{
Name: "repo",
Description: "Command for repository creation",
Description: "Creates repository of selected type. Name used for projects channels only",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionString,
@ -46,67 +46,75 @@ func (h *router) CreateRepoHandler(repoNameMinLength int) CommandRoute {
},
},
},
Handler: func(s *discordgo.Session, i *discordgo.InteractionCreate) {
// Моментальный ответ для избежания столкновения с протуханием токена
initialResponse := discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral,
Content: "👩‍🍳 Cooking your query..",
},
}
s.InteractionRespond(i.Interaction, &initialResponse)
// Определение переменной для ответа
var result string = "unexpected result"
// Access options in the order provided by the user.
options := i.ApplicationCommandData().Options
// Or convert the slice into a map
optionMap := make(map[string]*discordgo.ApplicationCommandInteractionDataOption, len(options))
for _, opt := range options {
optionMap[opt.Name] = opt
}
// Creating request:
var req controller.GitRequest
name, insertedValueNotNil := optionMap[nameOption]
isBuild := optionMap[repoType]
switch isBuild.StringValue() {
case buildRepo:
req.IsBuildGit = true
case projectRepo:
req.IsBuildGit = false
}
dchan, err := s.Channel(i.ChannelID)
if err != nil {
log.Printf("error while identifying channel: %v", err)
} else {
if dchan.ParentID == h.conf.IsProjectChannel {
req.ChannelID = dchan.ID
if insertedValueNotNil {
req.InsertedName = name.StringValue()
}
} else {
req.ChannelID = ""
if insertedValueNotNil {
req.InsertedName = name.StringValue()
}
}
}
// Making request:
resp := h.controller.CreateGit(context.TODO(), req)
if resp.Project == nil {
result = resp.Message.Error()
} else {
result = resp.Project.DiscordString() + "Errors: " + resp.Message.Error()
}
h.defaultFollowUp(result, s, i)
},
Handler: c.createRepoHandler,
}
}
func (c *client) createRepoHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
const (
repoType = "repo_type"
projectRepo = "project_repo"
buildRepo = "build_repo"
nameOption = "repo_name"
)
// Моментальный ответ для избежания столкновения с протуханием токена
initialResponse := discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral,
Content: "👩‍🍳 Cooking your query..",
},
}
s.InteractionRespond(i.Interaction, &initialResponse)
// Определение переменной для ответа
var result string = "unexpected result"
// Access options in the order provided by the user.
options := i.ApplicationCommandData().Options
// Or convert the slice into a map
optionMap := make(map[string]*discordgo.ApplicationCommandInteractionDataOption, len(options))
for _, opt := range options {
optionMap[opt.Name] = opt
}
// Creating request:
var req controller.GitRequest
name, insertedValueNotNil := optionMap[nameOption]
isBuild := optionMap[repoType]
switch isBuild.StringValue() {
case buildRepo:
req.IsBuildGit = true
case projectRepo:
req.IsBuildGit = false
}
dchan, err := s.Channel(i.ChannelID)
if err != nil {
log.Printf("error while identifying channel: %v", err)
} else {
if dchan.ParentID == c.conf.IsProjectChannel {
req.ChannelID = dchan.ID
if insertedValueNotNil {
req.InsertedName = name.StringValue()
}
} else {
req.ChannelID = ""
if insertedValueNotNil {
req.InsertedName = name.StringValue()
}
}
}
// Making request:
resp := c.controller.CreateGit(context.TODO(), req)
if resp.Project == nil {
result = resp.Message.Error()
} else {
result = resp.Project.DiscordString() + "Errors: " + resp.Message.Error()
}
c.defaultFollowUp(result, s, i)
}

View File

@ -6,31 +6,25 @@ import (
"github.com/bwmarrin/discordgo"
)
func (h *router) Ping() CommandRoute {
return CommandRoute{
func (c *client) Ping() Command {
return Command{
Command: discordgo.ApplicationCommand{
Name: "ping",
Description: "pongs in a reply",
},
Handler: func(s *discordgo.Session, i *discordgo.InteractionCreate) {
err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
TTS: false,
Content: "Pong to: " + i.Member.User.Mention(),
Components: []discordgo.MessageComponent{},
Embeds: []*discordgo.MessageEmbed{},
Files: []*discordgo.File{},
Flags: 0,
Choices: []*discordgo.ApplicationCommandOptionChoice{},
CustomID: "",
Title: "",
},
})
if err != nil {
log.Println(err)
}
},
Handler: c.ping,
}
}
func (c *client) ping(s *discordgo.Session, i *discordgo.InteractionCreate) {
err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Pong to: " + i.Member.User.Mention(),
},
})
if err != nil {
log.Println(err)
}
}

View File

@ -9,133 +9,133 @@ import (
"github.com/bwmarrin/discordgo"
)
func (h *router) GetInfo() CommandRoute {
return CommandRoute{
func (c *client) GetInfo() Command {
return Command{
Command: discordgo.ApplicationCommand{
Name: "info",
Description: "Get project's info",
},
Handler: func(s *discordgo.Session, i *discordgo.InteractionCreate) {
// Моментальный ответ для избежания столкновения с протуханием токена
initialResponse := discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral,
Content: "👩‍🍳 Cooking your query..",
},
}
s.InteractionRespond(i.Interaction, &initialResponse)
var result string
// Get channel from the request
dchan, err := s.Channel(i.ChannelID)
if err != nil {
result = "unable to get channel from the message"
} else {
project, err := h.controller.GetProjectByChannelID(context.TODO(), dchan.ID)
if err != nil {
result = err.Error()
} else {
result = project.DiscordString()
if err != nil {
result += "Errors: " + err.Error()
}
}
}
h.defaultFollowUp(result, s, i)
},
Handler: c.getInfo,
}
}
func (h *router) InitProjectFromChannel(minLength int) CommandRoute {
const (
keyOption = "key"
)
return CommandRoute{
func (c *client) getInfo(s *discordgo.Session, i *discordgo.InteractionCreate) {
// Моментальный ответ для избежания столкновения с протуханием токена
initialResponse := discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral,
Content: "👩‍🍳 Cooking your query..",
},
}
s.InteractionRespond(i.Interaction, &initialResponse)
var result string
// Get channel from the request
dchan, err := s.Channel(i.ChannelID)
if err != nil {
result = "unable to get channel from the message"
} else {
project, err := c.controller.GetProjectByChannelID(context.TODO(), dchan.ID)
if err != nil {
result = err.Error()
} else {
result = project.DiscordString()
if err != nil {
result += "Errors: " + err.Error()
}
}
}
c.defaultFollowUp(result, s, i)
}
func (c *client) InitProjectFromChannel(minLength int) Command {
return Command{
Command: discordgo.ApplicationCommand{
Name: "init_project",
Description: "Connect project with Coda ID",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionString,
Name: keyOption,
Name: "key",
Description: "Project's key from Coda.io",
Required: true,
MinLength: &minLength,
},
},
},
Handler: func(s *discordgo.Session, i *discordgo.InteractionCreate) {
// Моментальный ответ для избежания столкновения с протуханием токена
initialResponse := discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral,
Content: "👩‍🍳 Cooking your query..",
},
}
s.InteractionRespond(i.Interaction, &initialResponse)
var result string
// Get channel from the request
dchan, err := s.Channel(i.ChannelID)
if err != nil {
result = "unable to get channel from the message"
} else {
if dchan.ParentID != h.conf.IsProjectChannel {
// Sending result:
_, err := s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
Content: "This channel is not at the project's group",
})
if err != nil {
s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
Content: fmt.Sprintf("Something went wrong: %v", err),
})
return
}
return
}
// Access options in the order provided by the user.
options := i.ApplicationCommandData().Options
// Or convert the slice into a map
optionMap := make(map[string]*discordgo.ApplicationCommandInteractionDataOption, len(options))
for _, opt := range options {
optionMap[opt.Name] = opt
}
if option, ok := optionMap[keyOption]; ok {
var errMsg error = nil
project, err := h.controller.InitProjectInChannel(context.TODO(), i.ChannelID, option.StringValue())
if err != nil {
result = fmt.Sprintf("unable to init project: %v", err)
} else {
result = project.DiscordString()
if errMsg != nil {
result += "Errors: " + errMsg.Error()
}
}
}
}
h.defaultFollowUp(result, s, i)
},
Handler: c.initProjectFromChannel,
}
}
func (h *router) CreateTicketHandler(repoNameMinLength int) CommandRoute {
return CommandRoute{
func (c *client) initProjectFromChannel(s *discordgo.Session, i *discordgo.InteractionCreate) {
// Моментальный ответ для избежания столкновения с протуханием токена
initialResponse := discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral,
Content: "👩‍🍳 Cooking your query..",
},
}
s.InteractionRespond(i.Interaction, &initialResponse)
var result string
// Get channel from the request
dchan, err := s.Channel(i.ChannelID)
if err != nil {
result = "unable to get channel from the message"
} else {
if dchan.ParentID != c.conf.IsProjectChannel {
// Sending result:
_, err := s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
Content: "This channel is not at the project's group",
})
if err != nil {
s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
Content: fmt.Sprintf("Something went wrong: %v", err),
})
return
}
return
}
// Access options in the order provided by the user.
options := i.ApplicationCommandData().Options
// Or convert the slice into a map
optionMap := make(map[string]*discordgo.ApplicationCommandInteractionDataOption, len(options))
for _, opt := range options {
optionMap[opt.Name] = opt
}
if option, ok := optionMap["key"]; ok {
var errMsg error = nil
project, err := c.controller.InitProjectInChannel(context.TODO(), i.ChannelID, option.StringValue())
if err != nil {
result = fmt.Sprintf("unable to init project: %v", err)
} else {
result = project.DiscordString()
if errMsg != nil {
result += "Errors: " + errMsg.Error()
}
}
}
}
c.defaultFollowUp(result, s, i)
}
func (c *client) CreateTicketHandler(repoNameMinLength int) Command {
return Command{
Command: discordgo.ApplicationCommand{
Name: "project",
Description: "Create new development ticket",
@ -149,65 +149,67 @@ func (h *router) CreateTicketHandler(repoNameMinLength int) CommandRoute {
},
},
},
Handler: func(s *discordgo.Session, i *discordgo.InteractionCreate) {
// Моментальный ответ для избежания столкновения с протуханием токена
initialResponse := discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral,
Content: "👩‍🍳 Cooking your query..",
},
}
s.InteractionRespond(i.Interaction, &initialResponse)
var result string
// Access options in the order provided by the user.
options := i.ApplicationCommandData().Options
// Or convert the slice into a map
optionMap := make(map[string]*discordgo.ApplicationCommandInteractionDataOption, len(options))
for _, opt := range options {
optionMap[opt.Name] = opt
}
if option, ok := optionMap["project_name"]; ok {
dchan, err := s.GuildChannelCreate(i.GuildID, option.StringValue(), discordgo.ChannelTypeGuildText)
if err != nil {
result = fmt.Sprintf("chan creation problem: %v\n", err)
} else {
p, err := h.controller.ProjectCreate(context.TODO(), domain.Project{
ChannelID: dchan.ID,
})
if err != nil {
result = fmt.Sprintf("unable to create project: %v\n", err)
_, err := s.ChannelDelete(dchan.ID)
if err != nil {
result += fmt.Sprintf("\nunable to clean channel: %v\n", err)
}
} else {
edit := discordgo.ChannelEdit{
Name: p.ShortName,
ParentID: "1150719794853716028",
}
dchan, err = s.ChannelEdit(dchan.ID, &edit)
if err != nil {
result = fmt.Sprintf("channel created, but unable to edit: %v\n", err)
} else {
_, err = s.ChannelMessageSend(dchan.ID, "Hello!")
if err != nil {
log.Printf("message send problem: %v\n", err)
}
result = dchan.ID
}
}
}
}
h.defaultFollowUp(result, s, i)
},
Handler: c.createTicketHandler,
}
}
func (c *client) createTicketHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
// Моментальный ответ для избежания столкновения с протуханием токена
initialResponse := discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral,
Content: "👩‍🍳 Cooking your query..",
},
}
s.InteractionRespond(i.Interaction, &initialResponse)
var result string
// Access options in the order provided by the user.
options := i.ApplicationCommandData().Options
// Or convert the slice into a map
optionMap := make(map[string]*discordgo.ApplicationCommandInteractionDataOption, len(options))
for _, opt := range options {
optionMap[opt.Name] = opt
}
if option, ok := optionMap["project_name"]; ok {
dchan, err := s.GuildChannelCreate(i.GuildID, option.StringValue(), discordgo.ChannelTypeGuildText)
if err != nil {
result = fmt.Sprintf("chan creation problem: %v\n", err)
} else {
p, err := c.controller.ProjectCreate(context.TODO(), domain.Project{
ChannelID: dchan.ID,
})
if err != nil {
result = fmt.Sprintf("unable to create project: %v\n", err)
_, err := s.ChannelDelete(dchan.ID)
if err != nil {
result += fmt.Sprintf("\nunable to clean channel: %v\n", err)
}
} else {
edit := discordgo.ChannelEdit{
Name: p.ShortName,
ParentID: "1150719794853716028",
}
dchan, err = s.ChannelEdit(dchan.ID, &edit)
if err != nil {
result = fmt.Sprintf("channel created, but unable to edit: %v\n", err)
} else {
_, err = s.ChannelMessageSend(dchan.ID, "Hello!")
if err != nil {
log.Printf("message send problem: %v\n", err)
}
result = dchan.ID
}
}
}
}
c.defaultFollowUp(result, s, i)
}

View File

@ -60,6 +60,11 @@ func (h *Handler) FarmTaskHandler(ctx context.Context, mu *tgb.MessageUpdate) er
tg.HTML.Code(i),
tg.HTML.Text(" was created"),
),
tg.HTML.Line(
"Заходи в наш",
tg.HTML.Link("discord", "https://discord.gg/RHdzK3kUr7"),
"чтобы отслеживать статус по задаче",
),
)
if mu.Caption != "" {
answer = tg.HTML.Text(
@ -67,9 +72,16 @@ func (h *Handler) FarmTaskHandler(ctx context.Context, mu *tgb.MessageUpdate) er
tg.HTML.Bold("I'm unable to work with files, but"),
),
tg.HTML.Line(
tg.HTML.Bold("Task ID: "),
tg.HTML.Code(i),
tg.HTML.Text(" was created"),
tg.HTML.Italic(
tg.HTML.Bold("Task ID: "),
tg.HTML.Code(i),
tg.HTML.Text(" was created")),
),
tg.HTML.Line(
"Заходи в наш",
tg.HTML.Link("discord", "https://discord.gg/RHdzK3kUr7"),
"чтобы отслеживать статус по задаче",
),
)
}