...
1 package upload
2
3 import (
4 "fmt"
5 "io"
6 "log"
7 "net/http"
8 "os"
9
10 "github.com/bwmarrin/discordgo"
11 client "go.formulabun.club/replays/ingest/client"
12 )
13
14 var logger = log.New(os.Stdout, "/records upload ", log.LstdFlags)
15
16 var fileOption = &discordgo.ApplicationCommandOption{
17 Type: discordgo.ApplicationCommandOptionAttachment,
18 Name: "replay",
19 Description: "srb2kart replay file",
20 Required: true,
21 }
22
23 var CommandOption = &discordgo.ApplicationCommandOption{
24 Type: discordgo.ApplicationCommandOptionSubCommand,
25 Name: "upload",
26 Description: "add your record",
27 Options: []*discordgo.ApplicationCommandOption{fileOption},
28 }
29
30 func errorResponse(err error) discordgo.InteractionResponse {
31 logger.Print(err)
32 return discordgo.InteractionResponse{
33 Type: discordgo.InteractionResponseChannelMessageWithSource,
34 Data: &discordgo.InteractionResponseData{
35 Content: fmt.Sprintf("Something went wrong, ||%s||", err),
36 },
37 }
38 }
39
40 func Reply(options []*discordgo.ApplicationCommandInteractionDataOption, interactionData *discordgo.ApplicationCommandInteractionDataResolved, request client.ApiRootPostRequest) discordgo.InteractionResponse {
41 attachmentId := options[0].Value.(string)
42
43 file := interactionData.Attachments[attachmentId]
44
45 tempFile, err := os.CreateTemp("", file.Filename+"*")
46 if err != nil {
47 return errorResponse(fmt.Errorf("Couldn't create a temporary file for the record: %s", err))
48 }
49
50 resp, err := http.Get(file.URL)
51 if err != nil {
52 return errorResponse(fmt.Errorf("Couldn't download the record: %s", err))
53 }
54
55 _, err = io.Copy(tempFile, resp.Body)
56 if err != nil {
57 return errorResponse(fmt.Errorf("Couldn't save the record: %s", err))
58 }
59 resp.Body.Close()
60
61 tempFile.Seek(0, 0)
62
63 request = request.Body(tempFile)
64 resp, err = request.Execute()
65 if err != nil {
66 if resp.StatusCode == http.StatusConflict {
67 return discordgo.InteractionResponse{
68 Type: discordgo.InteractionResponseChannelMessageWithSource,
69 Data: &discordgo.InteractionResponseData{
70 Content: "It looks like this replay was already added.",
71 },
72 }
73 }
74 return errorResponse(fmt.Errorf("could not process replay: %s", resp.Body))
75 }
76
77 logger.Print("upload file response: ", resp.Status)
78
79 return discordgo.InteractionResponse{
80 Type: discordgo.InteractionResponseChannelMessageWithSource,
81 Data: &discordgo.InteractionResponseData{
82 Content: "Thank you for your replay",
83 },
84 }
85 }
86
View as plain text