Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WebhookをBotに置き換え #553

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
SESSION_KEY=
TRAQ_CALENDARID=
CLIENT_ID=
WEBHOOK_ID=
WEBHOOK_SECRET=
TRAQ_BOT_TOKEN=
ACTIVITY_CHANNEL_ID=
DAILY_CHANNEL_ID=
TOKEN_KEY=
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ debug

# for development
_development/*
.env
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@ knoQ の全ての機能を動作させるためには、追加の情報が必要
| SESSION_KEY | 環境変数 | `random32wordsXXXXXXXXXXXXXXXXXXX` | session を暗号化するもの |
| TRAQ_CALENDARID | 環境変数 | | 進捗部屋の提供元(公開されている google calendar の id なら何でもいい) |
| CLIENT_ID | 環境変数 | `d1hDlIRNfCBerXdZkH1VR8lJwCBpIuMgiv42` | 認証に必要 |
| WEBHOOK_ID | 環境変数 | | Bot 情報 |
| WEBHOOK_SECRET | 環境変数 | | Bot 情報 |
| TRAQ_BOT_TOKEN | 環境変数 | | Bot 情報 |
| CHANNEL_ID | 環境変数 | | Bot の送信先チャンネル (deprecated) |
| DAILY_CHANNEL_ID | 環境変数 | | Bot が毎日定時に投稿する先のチャンネル |
| ACTIVITY_CHANNEL_ID | 環境変数 | | Bot が都度送信するチャンネル |
Expand Down
7 changes: 1 addition & 6 deletions compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,24 +16,19 @@ services:
SESSION_KEY: ${SESSION_KEY:-random32wordsXXXXXXXXXXXXXXXXXXX}
TRAQ_CALENDARID: ${TRAQ_CALENDARID}
CLIENT_ID: ${CLIENT_ID:-d1hDlIRNfCBerXdZkH1VR8lJwCBpIuMgiv42}
WEBHOOK_ID: ${WEBHOOK_ID}
WEBHOOK_SECRET: ${WEBHOOK_SECRET}
CHANNEL_ID: ${CHANNEL_ID}
DAILY_CHANNEL_ID: ${DAILY_CHANNEL_ID}
ACTIVITY_CHANNEL_ID: ${ACTIVITY_CHANNEL_ID}
TOKEN_KEY: ${TOKEN_KEY:-random32wordsXXXXXXXXXXXXXXXXXXX}
KNOQ_VERSION: ${KNOQ_VERSION:-dev}
TRAQ_BOT_TOKEN: ${TRAQ_BOT_TOKEN}
DEVELOPMENT: true
GORM_LOG_LEVEL: info
ports:
- "${APP_PORT:-3000}:3000"
depends_on:
db:
condition: service_healthy
develop:
watch:
- action: rebuild
path: ./

db:
image: mariadb:10.6.4
Expand Down
1 change: 1 addition & 0 deletions domain/domain.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,5 @@ type Repository interface {
RoomRepository
TagRepository
UserRepository
PostRepository
}
18 changes: 18 additions & 0 deletions domain/post.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package domain

import "github.com/gofrs/uuid"

type Post struct {
MessageID uuid.UUID
EventID uuid.UUID
}
Comment on lines +5 to +8
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

eventにtraQのmessageを紐づけるなら新しくテーブルを作らなくてもeventsテーブルにカラムを追加するのでもいいかもしれないです


type WritePostParams struct {
MessageID uuid.UUID
EventID uuid.UUID
}

type PostRepository interface {
CreatePost(params WritePostParams) (*Post, error)
GetPost(MessageID uuid.UUID) (*Post, error)
}
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ require (
github.com/robfig/cron/v3 v3.0.1
github.com/stretchr/testify v1.9.0
github.com/traPtitech/go-traq v0.0.0-20240509050113-9343acbeec35
github.com/traPtitech/traq-ws-bot v1.1.3
go.uber.org/zap v1.27.0
golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1
golang.org/x/oauth2 v0.20.0
Expand Down Expand Up @@ -54,6 +55,7 @@ require (
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect
github.com/googleapis/enterprise-certificate-proxy v0.3.2 // indirect
github.com/gorilla/context v1.1.2 // indirect
github.com/gorilla/websocket v1.5.0 // indirect
github.com/imdario/mergo v0.3.12 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,8 @@ github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kX
github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=
github.com/gorilla/sessions v1.2.2 h1:lqzMYz6bOfvn2WriPUjNByzeXIlVzURcPmgMczkmTjY=
github.com/gorilla/sessions v1.2.2/go.mod h1:ePLdVu+jbEgHH+KWw8I1z2wqd0BAdAQh/8LRvBeoNcQ=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/imdario/mergo v0.3.12 h1:b6R2BslTbIEToALKP7LxUvijTsNI9TAe80pLWN2g/HU=
github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA=
github.com/jinzhu/copier v0.4.0 h1:w3ciUoD19shMCRargcpm0cm91ytaBhDvuRpz1ODO/U8=
Expand Down Expand Up @@ -172,6 +174,8 @@ github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsT
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/traPtitech/go-traq v0.0.0-20240509050113-9343acbeec35 h1:NoEvHqFhmtyy7ELLp1chwM4R1vhXw2zKeEotkmKvSJw=
github.com/traPtitech/go-traq v0.0.0-20240509050113-9343acbeec35/go.mod h1:7yJs1m/ddCG39XF78GA8FrXqyc4fNPfHp8BSLjMVMY8=
github.com/traPtitech/traq-ws-bot v1.1.3 h1:Cehz+ORmz/j2HexJHtm6yS/lmAq99REpojfwj0vjjBY=
github.com/traPtitech/traq-ws-bot v1.1.3/go.mod h1:mnUHbZiFLydoUxS2q8kzR1E+1RMRXrmEpUdSAxh0jvo=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
Expand Down
51 changes: 51 additions & 0 deletions infra/bot/bot.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package bot

import (
"fmt"
"time"

"github.com/gofrs/uuid"
"github.com/traPtitech/knoQ/domain"
"github.com/traPtitech/knoQ/infra/db"
traqwsbot "github.com/traPtitech/traq-ws-bot"
"github.com/traPtitech/traq-ws-bot/payload"
)

var Bot *traqwsbot.Bot

const (
AttendanceStampID = "93d376c3-80c9-4bb2-909b-2bbe2fbf9e93"
AbsentStampID = "544c04db-9cc3-4c0e-935d-571d4cf103a2"
PendingStampID = "bc9a3814-f185-4b3d-ac1f-3c8f12ad7b52"
)

func BotMessageStampsUpdatedHandler(p *payload.BotMessageStampsUpdated, gormRepo db.GormRepository) {
post, err := gormRepo.GetPost(uuid.FromStringOrNil(p.MessageID))
if err != nil {
fmt.Println(err)
}
for _, stamp := range p.Stamps {
if time.Now().After(stamp.UpdatedAt.Add(3 * time.Second)) {
// 3秒以上経過したスタンプは無視
continue
}
var scheduleStatus domain.ScheduleStatus
switch stamp.StampID {
case AttendanceStampID:
// 出席
scheduleStatus = domain.Attendance
case AbsentStampID:
// 欠席
scheduleStatus = domain.Absent
case PendingStampID:
// 未定
scheduleStatus = domain.Pending
default:
continue
}
err := gormRepo.UpsertEventSchedule(post.EventID, uuid.FromStringOrNil(stamp.UserID), scheduleStatus)
if err != nil {
fmt.Println(err)
}
}
}
13 changes: 13 additions & 0 deletions infra/db/converter.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions infra/db/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ var tables = []interface{}{
EventTag{}, // Eventより下にないと、overrideされる
EventAdmin{},
EventAttendee{},
Post{},
}

type Model struct {
Expand Down Expand Up @@ -167,6 +168,11 @@ type EventAttendee struct {
Schedule int
}

type Post struct {
MessageID uuid.UUID `gorm:"type:char(36); primaryKey"`
EventID uuid.UUID `gorm:"type:char(36); not null"`
}

// Event is event for gorm
//
//go:generate go run github.com/fuji8/gotypeconverter/cmd/gotypeconverter@latest -s Event -d domain.Event -o converter.go .
Expand Down
36 changes: 36 additions & 0 deletions infra/db/post.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package db

import (
"github.com/gofrs/uuid"
"github.com/traPtitech/knoQ/domain"
"gorm.io/gorm"
)

type WritePostParams struct {
domain.WritePostParams
}

func (repo *GormRepository) CreatePost(params WritePostParams) (*Post, error) {
p, err := createPost(repo.db, params)
return p, defaultErrorHandling(err)
}

func (repo *GormRepository) GetPost(MessageID uuid.UUID) (*Post, error) {
post, err := getPost(repo.db, MessageID)
return post, defaultErrorHandling(err)
}

func createPost(db *gorm.DB, params WritePostParams) (*Post, error) {
post := ConvWritePostParamsToPost(params)
err := db.Create(&post).Error
if err != nil {
return nil, err
}
return &post, nil
}

func getPost(db *gorm.DB, messageID uuid.UUID) (*Post, error) {
post := Post{}
err := db.Take(&post, messageID).Error
return &post, err
}
29 changes: 22 additions & 7 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,22 @@ import (
"time"

"github.com/traPtitech/knoQ/domain"
"github.com/traPtitech/knoQ/infra/bot"
"github.com/traPtitech/knoQ/infra/db"
"github.com/traPtitech/knoQ/infra/traq"
"github.com/traPtitech/knoQ/repository"
"github.com/traPtitech/knoQ/utils"
"github.com/traPtitech/knoQ/utils/tz"
"github.com/traPtitech/traq-ws-bot/payload"
"golang.org/x/oauth2"

"github.com/traPtitech/knoQ/router"

"github.com/gorilla/sessions"
"github.com/robfig/cron/v3"
"go.uber.org/zap"

traqwsbot "github.com/traPtitech/traq-ws-bot"
)

var (
Expand All @@ -39,8 +43,6 @@ var (
clientID = getenv("CLIENT_ID", "client_id")
origin = getenv("ORIGIN", "http://localhost:3000")
sessionKey = getenv("SESSION_KEY", "random32wordsXXXXXXXXXXXXXXXXXXX")
webhookID = getenv("WEBHOOK_ID", "")
webhookSecret = getenv("WEBHOOK_SECRET", "")
activityChannelID = getenv("ACTIVITY_CHANNEL_ID", "")
dailyChannelID = getenv("DAILY_CHANNEL_ID", "")
)
Expand Down Expand Up @@ -83,24 +85,20 @@ func main() {
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
},
WebhookID: webhookID,
WebhookSecret: webhookSecret,
ActivityChannelID: activityChannelID,
DailyChannelId: dailyChannelID,
Origin: origin,
}

e := handler.SetupRoute()

// webhook
// cron
c := cron.New(cron.WithLocation(tz.JST))
_, err = c.AddFunc(
"0 8 * * *",
utils.InitPostEventToTraQ(
&repo.GormRepo,
handler.WebhookSecret,
handler.DailyChannelId,
handler.WebhookID,
handler.Origin,
),
)
Expand All @@ -115,10 +113,27 @@ func main() {
e.Logger.Info("shutting down the server")
}
}()

// bot
bot.Bot, err = traqwsbot.NewBot(&traqwsbot.Options{
AccessToken: os.Getenv("TRAQ_BOT_TOKEN"),
})
if err != nil {
panic(err)
}
bot.Bot.OnBotMessageStampsUpdated(func(p *payload.BotMessageStampsUpdated) {
bot.BotMessageStampsUpdatedHandler(p, gormRepo)
})

if err := bot.Bot.Start(); err != nil {
panic(err)
}

quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
<-quit
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)

defer cancel()
if err := e.Shutdown(ctx); err != nil {
e.Logger.Fatal(err)
Expand Down
1 change: 1 addition & 0 deletions migration/current.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,6 @@ func Migrations() []*gormigrate.Migration {
v10(),
v11(),
v12(),
v13(),
}
}
25 changes: 25 additions & 0 deletions migration/v13.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package migration

import (
"github.com/go-gormigrate/gormigrate/v2"
"github.com/gofrs/uuid"
"gorm.io/gorm"
)

type v13Post struct {
MessageID uuid.UUID `gorm:"type:char(36); primaryKey"`
EventID uuid.UUID `gorm:"type:char(36); not null"`
}

func (*v13Post) TableName() string {
return "posts"
}

func v13() *gormigrate.Migration {
return &gormigrate.Migration{
ID: "13",
Migrate: func(db *gorm.DB) error {
return db.Migrator().CreateTable(&v13Post{})
},
}
}
28 changes: 28 additions & 0 deletions repository/post.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package repository

import (
"github.com/gofrs/uuid"
"github.com/traPtitech/knoQ/domain"
"github.com/traPtitech/knoQ/infra/db"
)

func (repo *Repository) CreatePost(params domain.WritePostParams) (*domain.Post, error) {
p := db.WritePostParams{
WritePostParams: params,
}
post, err := repo.GormRepo.CreatePost(p)
if err != nil {
return nil, defaultErrorHandling(err)
}
domainPost := db.ConvPostTodomainPost(*post)
return &domainPost, nil
}

func (repo *Repository) GetPost(MessageID uuid.UUID) (*domain.Post, error) {
post, err := repo.GormRepo.GetPost(MessageID)
if err != nil {
return nil, defaultErrorHandling(err)
}
domainPost := db.ConvPostTodomainPost(*post)
return &domainPost, nil
}
Loading