|
| 1 | +package handler |
| 2 | + |
| 3 | +import ( |
| 4 | + "os" |
| 5 | + |
| 6 | + "github.com/open-runtimes/types-for-go/v4" |
| 7 | +) |
| 8 | + |
| 9 | +type any = map[string]interface{} |
| 10 | + |
| 11 | +func Main(Context *types.Context) types.ResponseOutput { |
| 12 | + err := errorIfEnvMissing([]string{ |
| 13 | + "DISCORD_PUBLIC_KEY", |
| 14 | + "DISCORD_APPLICATION_ID", |
| 15 | + "DISCORD_TOKEN", |
| 16 | + }) |
| 17 | + if err != nil { |
| 18 | + Context.Error(err.Error()) |
| 19 | + return Context.Res.Text("", 500, nil) |
| 20 | + } |
| 21 | + |
| 22 | + err = discordVerifyKey( |
| 23 | + Context.Req.BodyText(), |
| 24 | + Context.Req.Headers["x-signature-ed25519"], |
| 25 | + Context.Req.Headers["x-signature-timestamp"], |
| 26 | + os.Getenv("DISCORD_PUBLIC_KEY"), |
| 27 | + ) |
| 28 | + if err != nil { |
| 29 | + Context.Error(err.Error()) |
| 30 | + return Context.Res.Json(any{ |
| 31 | + "error": "Invalid request signature.", |
| 32 | + }, 401, nil) |
| 33 | + } |
| 34 | + |
| 35 | + Context.Log("Valid request") |
| 36 | + |
| 37 | + discordBody, err := discordParseBody(Context) |
| 38 | + if err != nil { |
| 39 | + Context.Error(err.Error()) |
| 40 | + return Context.Res.Json(any{ |
| 41 | + "error": "Invalid body.", |
| 42 | + }, 400, nil) |
| 43 | + } |
| 44 | + |
| 45 | + ApplicationCommandType := 2 |
| 46 | + if discordBody.Type == ApplicationCommandType && discordBody.Data.Name == "hello" { |
| 47 | + Context.Log("Matched hello command - returning message") |
| 48 | + |
| 49 | + channelMessageWithSource := 4 |
| 50 | + return Context.Res.Json( |
| 51 | + any{ |
| 52 | + "type": channelMessageWithSource, |
| 53 | + "data": any{ |
| 54 | + "content": "Hello, World!", |
| 55 | + }, |
| 56 | + }, |
| 57 | + 200, |
| 58 | + nil, |
| 59 | + ) |
| 60 | + } |
| 61 | + |
| 62 | + Context.Log("Didn't match command - returning PONG") |
| 63 | + |
| 64 | + return Context.Res.Json(any{"type": 1}, 200, nil) |
| 65 | +} |
0 commit comments