This repository has been archived on 2024-05-11. You can view files and clone it, but cannot push or open issues or pull requests.
Corn-Utility/events/interaction.go

256 lines
7.0 KiB
Go
Raw Normal View History

2023-10-19 18:08:38 -04:00
package botEvents
import (
2023-10-20 01:18:13 -04:00
"corn-util/bot/loaders"
2023-10-19 18:08:38 -04:00
"corn-util/bot/toolbox"
2023-10-20 01:18:13 -04:00
"encoding/json"
2023-10-19 18:08:38 -04:00
"fmt"
"os"
2023-10-19 18:08:38 -04:00
"runtime"
"strings"
"time"
"github.com/disgoorg/disgo"
"github.com/disgoorg/disgo/discord"
"github.com/disgoorg/disgo/events"
"github.com/disgoorg/log"
"github.com/dustin/go-humanize"
"github.com/mackerelio/go-osstat/cpu"
"github.com/shirou/gopsutil/v3/mem"
"github.com/zcalusic/sysinfo"
)
var (
mainEmbedColor = 0xf9c62c // main embed color for the bot (saffron / yellow)
2023-10-20 01:18:13 -04:00
noPermText = "You need to have a role with `Manage Server` permission to use this command."
attemptFailText = "There was an attempt..."
noConfigValText = "Unconfigured"
2023-10-19 18:08:38 -04:00
)
func ListenForCommand(e *events.ApplicationCommandInteractionCreate) {
TRUE := true
switch name := e.Data.CommandName(); name {
case "host-stats":
before, err := cpu.Get()
if err != nil {
DumpErrToConsole(err)
return
}
time.Sleep(time.Duration(1) * time.Second)
after, err := cpu.Get()
if err != nil {
DumpErrToConsole(err)
return
}
total := float64(after.Total - before.Total)
memInfo, _ := mem.VirtualMemory()
var si sysinfo.SysInfo
si.GetSysInfo()
if err := e.CreateMessage(discord.MessageCreate{
Embeds: []discord.Embed{
{
Description: fmt.Sprintf("**OS:** %s\n**CPU:** %s", si.OS.Name, si.CPU.Model),
Fields: []discord.EmbedField{
{
Name: "CPU Usage",
Value: fmt.Sprintf("User: %.1f %%\nSys: %.1f %%", float64(after.User-before.User)/total*100, float64(after.System-before.System)/total*100),
Inline: &TRUE,
},
{
Name: "Memory",
Value: fmt.Sprintf("Used: %v\nTotal: %v", humanize.IBytes(memInfo.Used), humanize.IBytes(memInfo.Total)),
Inline: &TRUE,
},
{
Name: "\u200b",
Value: "\u200b",
Inline: &TRUE,
},
{
Name: "Version",
Value: fmt.Sprintf("Disgo %v\nGo %v", disgo.Version, strings.TrimPrefix(runtime.Version(), "go")),
Inline: &TRUE,
},
{
Name: "Goroutines",
Value: fmt.Sprintf("%v", runtime.NumGoroutine()),
Inline: &TRUE,
},
},
Footer: &discord.EmbedFooter{
Text: fmt.Sprintf("Uptime: %v", toolbox.GetUptime()),
},
Color: mainEmbedColor,
},
},
}); err != nil {
DumpErrToConsole(err)
}
break
2023-10-20 01:18:13 -04:00
case "repository":
2023-10-19 18:08:38 -04:00
e.CreateMessage(discord.MessageCreate{
Components: []discord.ContainerComponent{
discord.ActionRowComponent{
discord.ButtonComponent{
2023-10-20 03:52:58 -04:00
Label: "Check out the repository!",
2023-10-19 18:08:38 -04:00
Style: discord.ButtonStyleLink,
2023-10-20 01:18:13 -04:00
URL: "https://git.toast-server.net/toast/Corn-Utility.git",
2023-10-19 18:08:38 -04:00
},
},
},
})
break
2023-10-20 01:18:13 -04:00
case "config":
type jsonDataStruct struct {
2023-10-23 03:36:40 -04:00
BanRecords string `json:"banRecords"`
GoogleSpreadsheetID string `json:"googleSpreadsheetId"`
2023-10-20 01:18:13 -04:00
}
readData, _ := loaders.DataLoader.Read(&loaders.JSON{}, "config.json")
jsonData := jsonDataStruct{}
jsonDataBytes, _ := json.Marshal(readData)
json.Unmarshal(jsonDataBytes, &jsonData)
type googleServiceAccStruct struct {
ClientEmail string `json:"client_email"`
}
readGCPJSON, _ := os.ReadFile("GCP_SERVICE.json")
googleServiceAcc := googleServiceAccStruct{}
json.Unmarshal(readGCPJSON, &googleServiceAcc)
2023-10-20 01:18:13 -04:00
banRecordsCh, _ := e.SlashCommandInteractionData().OptChannel("ban-records")
2023-10-23 03:36:40 -04:00
googleSpreadsheet_Id, _ := e.SlashCommandInteractionData().OptString("google-spreadsheet-id")
2023-10-20 01:18:13 -04:00
if !isGuildManager(e) {
DumpErrToInteraction(e, fmt.Errorf(noPermText))
return
}
if len(e.SlashCommandInteractionData().Options) == 0 {
e.CreateMessage(discord.MessageCreate{
Embeds: []discord.Embed{
{
Title: "Current configuration",
Description: "You can configure the bot using the options below.",
Fields: []discord.EmbedField{
{
Name: "Ban Records",
Value: func() string {
if jsonData.BanRecords == "" || jsonData.BanRecords == "0" {
return noConfigValText
} else {
return fmt.Sprintf("<#%v>", jsonData.BanRecords)
}
}(),
Inline: &TRUE,
},
{
2023-10-23 03:36:40 -04:00
Name: "Google Spreadsheet ID",
2023-10-20 01:18:13 -04:00
Value: func() string {
2023-10-23 03:36:40 -04:00
if jsonData.GoogleSpreadsheetID == "" {
2023-10-20 01:18:13 -04:00
return noConfigValText
} else {
2023-10-23 03:36:40 -04:00
return fmt.Sprintf("`%v`", jsonData.GoogleSpreadsheetID)
2023-10-20 01:18:13 -04:00
}
}(),
Inline: &TRUE,
},
},
Color: mainEmbedColor,
},
},
})
return
}
if banRecordsCh.Permissions.Has(discord.PermissionSendMessages, discord.PermissionEmbedLinks) {
// Create a placeholder embed in the configured channel.
if _, err := e.Client().Rest().CreateMessage(banRecordsCh.ID, discord.MessageCreate{
Embeds: []discord.Embed{
{
Description: "Ban records on Google Sheets will now be sent in this channel.\n" +
fmt.Sprintf("*Add the bot's service account to the spreadsheet for this to work:*\n`%v`", googleServiceAcc.ClientEmail),
Color: mainEmbedColor,
2023-10-20 01:18:13 -04:00
},
},
}); err != nil {
DumpErrToChannel(e, err)
return
}
}
if err := e.CreateMessage(discord.MessageCreate{
Embeds: []discord.Embed{{Title: "Config saved!", Color: mainEmbedColor}},
}); err != nil {
DumpErrToInteraction(e, err)
return
}
// Update the config file with the new configuration.
data := map[string]interface{}{}
if banRecordsCh.ID.String() != "0" {
data["banRecords"] = banRecordsCh.ID
} else {
data["banRecords"] = jsonData.BanRecords
}
2023-10-23 03:36:40 -04:00
if googleSpreadsheet_Id != "" {
if strings.Contains(googleSpreadsheet_Id, "docs.google.com/spreadsheets/d/") {
googleSpreadsheet_Id = strings.Split(googleSpreadsheet_Id, "/")[5]
log.Warnf("detected the url: \"%v\", splitting...", googleSpreadsheet_Id)
} else {
googleSpreadsheet_Id = strings.Split(googleSpreadsheet_Id, "/")[0]
}
data["googleSpreadsheetId"] = googleSpreadsheet_Id
2023-10-20 01:18:13 -04:00
} else {
2023-10-23 03:36:40 -04:00
data["googleSpreadsheetId"] = jsonData.GoogleSpreadsheetID
2023-10-20 01:18:13 -04:00
}
err := loaders.DataLoader.Write(&loaders.JSON{}, "config.json", data)
if err != nil {
DumpErrToChannel(e, err)
return
}
2023-10-19 18:08:38 -04:00
}
}
func DumpErrToConsole(err error) {
log.Errorf("failed to send interaction response: %v", err.Error())
}
func DumpErrToInteraction(e *events.ApplicationCommandInteractionCreate, err error) {
if err := e.CreateMessage(discord.MessageCreate{
Embeds: []discord.Embed{
{
2023-10-20 01:18:13 -04:00
Title: attemptFailText,
2023-10-19 18:08:38 -04:00
Description: fmt.Sprintf("```%v```", err.Error()),
Color: 0x560000,
},
},
}); err != nil {
DumpErrToConsole(err)
}
}
func DumpErrToChannel(e *events.ApplicationCommandInteractionCreate, err error) {
if _, err := e.Client().Rest().CreateMessage(e.Channel().ID(), discord.MessageCreate{
Embeds: []discord.Embed{
{
2023-10-20 01:18:13 -04:00
Title: attemptFailText,
2023-10-19 18:08:38 -04:00
Description: fmt.Sprintf("```%v```", err.Error()),
Color: 0x560000,
},
},
}); err != nil {
DumpErrToConsole(err)
}
}
func isGuildManager(e *events.ApplicationCommandInteractionCreate) bool {
2023-10-20 01:18:13 -04:00
if e.Member().Permissions.Has(discord.PermissionManageGuild) {
2023-10-19 18:08:38 -04:00
return true
} else {
return false
}
}