- fixed AddHandler logic;

This commit is contained in:
naudachu 2023-11-06 11:43:44 +05:00
parent 59d9fc567f
commit ecad950f54
4 changed files with 44 additions and 52 deletions

View File

@ -86,6 +86,7 @@ func run(conf domain.Config) {
} }
}() }()
// go func() {
opts := telegram.TelegramOptions{ opts := telegram.TelegramOptions{
TicketsRepo: ticketsRepo, TicketsRepo: ticketsRepo,
GitService: gitService, GitService: gitService,
@ -98,4 +99,6 @@ func run(conf domain.Config) {
log.Fatalf("telegram bot cannot be runned: %v", err) log.Fatalf("telegram bot cannot be runned: %v", err)
defer os.Exit(1) defer os.Exit(1)
} }
// }()
} }

View File

@ -40,9 +40,19 @@ func Run(conf domain.Config, opts DiscordOptions) error {
router := handler.InitRouter(opts.GitService) router := handler.InitRouter(opts.GitService)
for _, h := range router.Routes { commandHandlers := map[string]func(s *discordgo.Session, i *discordgo.InteractionCreate){}
session.AddHandler(h.Handler) for _, handler := range router.Routes {
commandHandlers[handler.Command.Name] = handler.Handler
} }
session.AddHandler(func(s *discordgo.Session, i *discordgo.InteractionCreate) {
if h, ok := commandHandlers[i.ApplicationCommandData().Name]; ok {
h(s, i)
}
})
// for _, h := range router.Routes {
// session.AddHandler(h.Handler) // [ ] Как-то я неправильно хэндлеры добавляю, на проджект отрабатывает /repo
// }
if err := session.Open(); err != nil { if err := session.Open(); err != nil {
return fmt.Errorf("cannot open the session: %v", err) return fmt.Errorf("cannot open the session: %v", err)

View File

@ -21,9 +21,8 @@ func InitRouter(gitService services.IGit) *router {
r.Routes = append( r.Routes = append(
r.Routes, r.Routes,
r.CreateRepoHandler(3), r.CreateRepoHandler(3),
// r.CreateTicketHandler(3), r.CreateTicketHandler(3),
) )
r.git = gitService r.git = gitService
return &r return &r
@ -119,7 +118,7 @@ func (h *router) CreateRepoHandler(repoNameMinLength int) route {
func (h *router) CreateTicketHandler(repoNameMinLength int) route { func (h *router) CreateTicketHandler(repoNameMinLength int) route {
return route{ return route{
Command: discordgo.ApplicationCommand{ Command: discordgo.ApplicationCommand{
Name: "new", Name: "project",
Description: "Create new development ticket", Description: "Create new development ticket",
Options: []*discordgo.ApplicationCommandOption{ Options: []*discordgo.ApplicationCommandOption{
{ {
@ -132,6 +131,7 @@ func (h *router) CreateTicketHandler(repoNameMinLength int) route {
}, },
}, },
Handler: func(s *discordgo.Session, i *discordgo.InteractionCreate) { Handler: func(s *discordgo.Session, i *discordgo.InteractionCreate) {
var result string
// Access options in the order provided by the user. // Access options in the order provided by the user.
options := i.ApplicationCommandData().Options options := i.ApplicationCommandData().Options
@ -141,27 +141,38 @@ func (h *router) CreateTicketHandler(repoNameMinLength int) route {
optionMap[opt.Name] = opt optionMap[opt.Name] = opt
} }
// This example stores the provided arguments in an []interface{}
// which will be used to format the bot's response
margs := make([]interface{}, 0, len(options))
msgformat := "You learned how to use command options! " +
"Take a look at the value(s) you entered:\n"
if option, ok := optionMap["project_name"]; ok { if option, ok := optionMap["project_name"]; ok {
// Option values must be type asserted from interface{}. dchan, err := s.GuildChannelCreate(i.GuildID, option.StringValue(), discordgo.ChannelTypeGuildText)
// Discordgo provides utility functions to make this simple. if err != nil {
margs = append(margs, option.StringValue()) log.Printf("chan creation problem: %v\n", err)
msgformat += "> string-option: %s\n" }
// permissions := discordgo.PermissionOverwrite{
// ID: i.User.ID,
// Type: 1,
// //Deny: 0,
// Allow: 1,
// }
edit := discordgo.ChannelEdit{
// PermissionOverwrites: []*discordgo.PermissionOverwrite{&permissions}, // [ ] Как сделать приватный канал то???
ParentID: "1150719794853716028",
}
dchan, err = s.ChannelEdit(dchan.ID, &edit)
if err != nil {
log.Printf("chan editing problem: %v\n", err)
}
_, err = s.ChannelMessageSend(dchan.ID, "Hello!")
if err != nil {
log.Printf("message send problem: %v\n", err)
}
result = dchan.ID
} }
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
// Ignore type for now, they will be discussed in "responses" // Ignore type for now, they will be discussed in "responses"
Type: discordgo.InteractionResponseChannelMessageWithSource, Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{ Data: &discordgo.InteractionResponseData{
Content: fmt.Sprintf( Content: result,
msgformat,
margs...,
),
}, },
}) })
}, },

View File

@ -21,36 +21,4 @@ sql-migrate up
# Repository code-gen # Repository code-gen
Запулить докер sqlc: `docker pull sqlc/sqlc` Запулить докер sqlc: `docker pull sqlc/sqlc`
Перейти в директорию: `cd ./internal/storage` Перейти в директорию: `cd ./internal/storage`
Запустить команду из докера: `docker run --rm -v "$(pwd):/src" -w /src sqlc/sqlc generate` Запустить команду из докера: `docker run --rm -v "$(pwd):/src" -w /src sqlc/sqlc generate`
# To-do P1:
- [ ] Сделать нормальный Gracefull ShutDown с потоками и всей хернёй
https://callistaenterprise.se/blogg/teknik/2019/10/05/go-worker-cancellation/
# To-do P2*:
- [ ] Нормальное сообщение об ошибке с созданием репо с уже существующим именем;
- [ ] Отказ от инициализации бота (автоинкремент ключа по данным базы?)
- [ ] В уведомлении об успешном создании сообщать всю инфу:
- git;
- git-build url + ssh url;
- ссылку на графику;
- добавлять название игры;
- [ ] Сохранять внешнюю ссылку на графику;
- [ ] Сделать бота в Discord;
- [ ] Подумать над нормальной обработкой ошибок, сейчас достаточно всрато;
- [ ] Складывать в описание репозитория ссылку на тикет;
- [ ] Сделать базулю с достойными пользователями;
# Готово:
- [x] Выбирать проект в YouTrack по имени во время flow, а не по ID
- [x] Делать запросы в Git, ownCloud параллельно;
- [x] Сохранять правильную ссылку на Git;
- [x] Сохранять правильную ссылку на GitBuild;
- [x] Сделать бота в Telegram;
- [x] Run bot on docker scratch: https://github.com/jeremyhuiskamp/golang-docker-scratch/blob/main/README.mdа
- [x] Сохранять короткую ссылку на графику;