Skip to content

Commit

Permalink
Merge branch 'dev'
Browse files Browse the repository at this point in the history
  • Loading branch information
jonas747 committed May 13, 2021
2 parents 79f2333 + 41a4215 commit b0fc19a
Show file tree
Hide file tree
Showing 20 changed files with 758 additions and 247 deletions.
17 changes: 16 additions & 1 deletion bot/shardmemberfetcher/shardmemberfetcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,20 @@ OUTER_SEND:
// not found, sendn il
go s.sendGWResult(gs, req, nil)
}

// add to state
gs.Lock()
defer gs.Unlock()

for _, v := range chunk.Members {
if ms, ok := gs.Members[v.User.ID]; ok {
if ms.MemberSet {
continue
}
}

gs.MemberAddUpdate(false, v)
}
}

func (s *shardMemberFetcher) sendResult(req *MemberFetchRequest, result *MemberFetchResult) {
Expand All @@ -372,6 +386,8 @@ func (s *shardMemberFetcher) sendGWResult(gs *dstate.GuildState, req *MemberFetc
MemberID: req.Member,
}
} else {
metricsProcessed.With(prometheus.Labels{"type": "gateway"}).Add(1)

ms := dstate.MSFromDGoMember(gs, member)
req.resp <- &MemberFetchResult{
Err: nil,
Expand Down Expand Up @@ -548,7 +564,6 @@ OUTER:
s.fetchingGWState.Nonce = nonce
s.fetchingGWState.Started = time.Now()
s.fetchingGWState.Members = ids
metricsProcessed.With(prometheus.Labels{"type": "gateway"}).Add(float64(len(ids)))

s.gwRequestFunc(biggestQueueGuild, ids, nonce)
}
Expand Down
14 changes: 14 additions & 0 deletions bot/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,20 @@ func BotProbablyHasPermissionGS(gs *dstate.GuildState, channelID int64, permissi
return false
}

func BotPermissions(gs *dstate.GuildState, channelID int64) (int64, error) {
ms, err := GetMember(gs.ID, common.BotUser.ID)
if err != nil {
return 0, err
}

perms, err := gs.MemberPermissionsMS(true, channelID, ms)
if err != nil {
return 0, err
}

return int64(perms), nil
}

func SendMessage(guildID int64, channelID int64, msg string) (permsOK bool, resp *discordgo.Message, err error) {
if !BotProbablyHasPermission(guildID, channelID, discordgo.PermissionSendMessages) {
return false, nil, nil
Expand Down
6 changes: 4 additions & 2 deletions cmd/yagpdb/static/js/spongebob.js
Original file line number Diff line number Diff line change
Expand Up @@ -231,8 +231,10 @@ function updateSelectedMenuItem(pathname) {
}
}

function addAlert(kind, msg) {
$("<div/>").addClass("row").append(
function addAlert(kind, msg, id) {
const alert = $(`<div/>`);
if (id !== undefined) alert.prop("id", id)
alert.addClass("row").append(
$("<div/>").addClass("col-lg-12").append(
$("<div/>").addClass("alert alert-" + kind).text(msg)
)
Expand Down
101 changes: 97 additions & 4 deletions commands/assets/commands.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,35 @@ <h2>Command settings</h2>

{{template "cp_alerts" .}}

<div id="confirm-disable-all-commands-modal" class="modal" data-backdrop="static">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content border-0">
<div class="modal-header">
<h2 class="modal-title">Warning!</h2>
</div>

<div class="modal-body border-0">
<div class="modal-wrapper">
<div class="modal-icon">
<i class="fas fa-exclamation-triangle"></i>
</div>
<div class="modal-text">
<h4>Are you sure you want to disable all commands?</h4>
<p>
This will cause all commands to <b>not respond at all</b> unless enabled in other overrides.
Unless you know precisely what you are doing, it is advised that you do not do this.
</p>
</div>
</div>
</div>
<div class="modal-footer border-0">
<button id="cancel-disable-all-commands" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button class="btn btn-warning" data-dismiss="modal">Dismiss warning</button>
</div>
</div>
</div>
</div>

<!-- /.row -->
<div class="row">
<div class="col-lg-12">
Expand All @@ -30,6 +59,9 @@ <h2>Command settings</h2>
<div class="col-lg-6">
<div class="form-group">
<label for="prefix">Command Prefix</label>
<div class="row-lg-6">
<p id="example-command-usage">Example command usage: <code>{{.CommandPrefix}}ping</code></p>
</div>
<input type="text" class="form-control" id="prefix" name="Prefix"
value="{{.CommandPrefix}}">
</div>
Expand Down Expand Up @@ -75,6 +107,59 @@ <h2>Command settings</h2>
</div>
<!-- /.row -->

<script>
$("#commands-enabled-global").click(function() {
if (!this.checked) {
$("#confirm-disable-all-commands-modal").modal("show");
}
});

$("#cancel-disable-all-commands").click(function() {
$("#commands-enabled-global").prop("checked", true).change();
});

$("#prefix").keyup(function() {
const prefix = $(this).val();
if (prefix.length === 0) return;

$("#example-command-usage > code").text(`${prefix}ping`);

const existingWarning = $("#trailing-space-warning");
if (prefix[prefix.length - 1] === " ") {
if (existingWarning.length > 0) return; // don't duplicate warnings
addAlert("warning", `You have a trailing space in your command prefix, meaning that while '${prefix}ping' would trigger, '${prefix.trimRight()}ping' would not.`, "trailing-space-warning")
} else if (existingWarning.length) {
existingWarning.remove();
}
});
</script>

<style>
.modal-header {
background-color: #212121;
}

.modal-body, .modal-footer {
background-color: #424242;
}

#cancel-disable-all-commands {
background-color: #9e9e9e;
}

#unsaved-changes-popup {
z-index: 10000;
}

.modal-backdrop {
z-index: 10001;
}

.modal {
z-index: 10002;
}
</style>

{{template "cp_footer" .}}

{{end}}
Expand All @@ -85,7 +170,7 @@ <h2>Command settings</h2>
.Commands
*/}}
{{define "commands_channel_override"}}
<form data-async-form method="POST"
<form data-async-form method="POST" {{if .Override.Global}}id="command-settings-global-form"{{end}}
action="{{if .Override}}/manage/{{.ActiveGuild.ID}}/commands/settings/channel_overrides/{{if .Override.Global}}global{{else}}{{.Override.ID}}{{end}}/update{{else}}/manage/{{.ActiveGuild.ID}}/commands/settings/channel_overrides/new{{end}}">

{{if not .Override.Global}}
Expand Down Expand Up @@ -121,11 +206,19 @@ <h2>Command settings</h2>
</div>
<div class="form-row">
{{$desc := "All commands enabled?"}}
{{if .Override.Global}}{{$desc = `All commands enabled? <br><b>Warning: disabling this
will disable all commands unless enabled in other overrides</b>`}}{{end}}
{{$commandsEnabled := true}}
{{if .Override}}{{$commandsEnabled = .Override.CommandsEnabled}}{{end}}
{{checkbox "CommandsEnabled" (joinStr "" "commands-enabled-" .Override.ID) $desc $commandsEnabled}}

{{if not .Override.Global}}
{{checkbox "CommandsEnabled" (joinStr "" "commands-enabled-" .Override.ID) $desc $commandsEnabled}}
{{else}}
<div class="form-group d-flex align-items-center">
<input type="checkbox" class="tgl tgl-flat" name="CommandsEnabled" id="commands-enabled-global"
{{if $commandsEnabled}} checked{{end}}>
<label for="commands-enabled-global" class="tgl-btn mb-2"></label>
<span class="ml-2 mb-2">{{$desc}}</span>
</div>
{{end}}
<hr />

<div class="form-group col-md-5 ml-2">
Expand Down
32 changes: 16 additions & 16 deletions commands/plugin_bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -190,25 +190,25 @@ func YAGCommandMiddleware(inner dcmd.RunFunc) dcmd.RunFunc {
yc.Logger(data).WithError(err).Error("An error occured while checking if we could run command")
}

if resp != "" {
if resp == ReasonCooldown {
switch data.TriggerType {
case dcmd.TriggerTypeSlashCommands:
common.BotSession.CreateFollowupMessage(data.SlashCommandTriggerData.Interaction.ApplicationID, data.SlashCommandTriggerData.Interaction.Token, &discordgo.WebhookParams{
Flags: 64,
Content: "Command is on cooldown.",
})
default:
if (data.GuildData != nil && bot.BotProbablyHasPermissionGS(data.GuildData.GS, data.GuildData.CS.ID, discordgo.PermissionAddReactions)) || data.GuildData.GS == nil {
common.BotSession.MessageReactionAdd(data.ChannelID, data.TraditionalTriggerData.Message.ID, "⏳")
}
if resp != nil {

if resp.Type == ReasonCooldown && data.TriggerType != dcmd.TriggerTypeSlashCommands {
if (data.GuildData != nil && bot.BotProbablyHasPermissionGS(data.GuildData.GS, data.GuildData.CS.ID, discordgo.PermissionAddReactions)) || data.GuildData.GS == nil {
common.BotSession.MessageReactionAdd(data.ChannelID, data.TraditionalTriggerData.Message.ID, "⏳")
return nil, nil
}
}

return &EphemeralOrNone{
Content: "You're unable to run this command: " + resp,
}, nil

switch resp.Type {
case ReasonBotMissingPerms:
return &EphemeralOrGuild{
Content: "You're unable to run this command:\n> " + resp.Message,
}, nil
default:
return &EphemeralOrNone{
Content: "You're unable to run this command:\n> " + resp.Message,
}, nil
}
}

if !canExecute {
Expand Down
87 changes: 3 additions & 84 deletions commands/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"unicode"
"unicode/utf8"

"emperror.dev/errors"
"github.com/jonas747/dcmd/v2"
"github.com/jonas747/discordgo"
"github.com/jonas747/dstate/v2"
Expand All @@ -33,12 +32,12 @@ func (d *DurationArg) Matches(def *dcmd.ArgDef, part string) bool {
return false
}

_, err := ParseDuration(part)
_, err := common.ParseDuration(part)
return err == nil
}

func (d *DurationArg) ParseFromMessage(def *dcmd.ArgDef, part string, data *dcmd.Data) (interface{}, error) {
dur, err := ParseDuration(part)
dur, err := common.ParseDuration(part)
if err != nil {
return nil, err
}
Expand All @@ -59,7 +58,7 @@ func (d *DurationArg) ParseFromInteraction(def *dcmd.ArgDef, data *dcmd.Data, op
if err != nil {
return nil, err
}
dur, err := ParseDuration(s)
dur, err := common.ParseDuration(s)
if err != nil {
return nil, err
}
Expand All @@ -83,86 +82,6 @@ func (d *DurationArg) SlashCommandOptions(def *dcmd.ArgDef) []*discordgo.Applica
return []*discordgo.ApplicationCommandOption{def.StandardSlashCommandOption(discordgo.CommandOptionTypeString)}
}

// Parses a time string like 1day3h
func ParseDuration(str string) (time.Duration, error) {
var dur time.Duration

currentNumBuf := ""
currentModifierBuf := ""

// Parse the time
for _, v := range str {
// Ignore whitespace
if unicode.Is(unicode.White_Space, v) {
continue
}

if unicode.IsNumber(v) {
// If we reached a number and the modifier was also set, parse the last duration component before starting a new one
if currentModifierBuf != "" {
if currentNumBuf == "" {
currentNumBuf = "1"
}
d, err := parseDurationComponent(currentNumBuf, currentModifierBuf)
if err != nil {
return d, err
}

dur += d

currentNumBuf = ""
currentModifierBuf = ""
}

currentNumBuf += string(v)

} else {
currentModifierBuf += string(v)
}
}

if currentNumBuf != "" {
d, err := parseDurationComponent(currentNumBuf, currentModifierBuf)
if err != nil {
return dur, errors.WrapIf(err, "not a duration")
}

dur += d
}

return dur, nil
}

func parseDurationComponent(numStr, modifierStr string) (time.Duration, error) {
parsedNum, err := strconv.ParseInt(numStr, 10, 64)
if err != nil {
return 0, err
}

parsedDur := time.Duration(parsedNum)

if strings.HasPrefix(modifierStr, "s") {
parsedDur = parsedDur * time.Second
} else if modifierStr == "" || (strings.HasPrefix(modifierStr, "m") && (len(modifierStr) < 2 || modifierStr[1] != 'o')) {
parsedDur = parsedDur * time.Minute
} else if strings.HasPrefix(modifierStr, "h") {
parsedDur = parsedDur * time.Hour
} else if strings.HasPrefix(modifierStr, "d") {
parsedDur = parsedDur * time.Hour * 24
} else if strings.HasPrefix(modifierStr, "w") {
parsedDur = parsedDur * time.Hour * 24 * 7
} else if strings.HasPrefix(modifierStr, "mo") {
parsedDur = parsedDur * time.Hour * 24 * 30
} else if strings.HasPrefix(modifierStr, "y") {
parsedDur = parsedDur * time.Hour * 24 * 365
} else {
return parsedDur, errors.New("couldn't figure out what '" + numStr + modifierStr + "` was")
}

return parsedDur, nil

}

type DurationOutOfRangeError struct {
Min, Max time.Duration
Got time.Duration
Expand Down
Loading

0 comments on commit b0fc19a

Please sign in to comment.