public static async Task PerformAsync(ShardedCommandContext context, DataBase db)
        {
            try
            {
                var guild = FindOrCreateGuild.Perform(context.Guild, db);

                // toList to force enumeration before we shuffle identifier
                var bannedUsers = context.Guild.Users.Where(x => PrefixHelper.UserBlocked(x.Id, guild)).ToList();

                guild.UserIdentifierSeed = new Random().Next(int.MinValue, int.MaxValue);

                var items = bannedUsers.Select(x => PrefixHelper.GetIdentifierString(x.Id, guild)).Select(x => new BannedIdentifier {
                    Identifier = x
                });

                db.RemoveRange(guild.BannedIdentifiers);

                items.Select((x) => {
                    guild.BannedIdentifiers.Add(x);
                    return(true);
                }).ToList();

                db.SaveChanges();

                await context.Channel.SendMessageAsync(text : "User identifiers have been randomized.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("error rotating");
                Console.WriteLine(ex.ToString());
            }
        }
Exemplo n.º 2
0
        public static async Task PerformAsync(ShardedCommandContext context, DataBase db)
        {
            var guild = FindOrCreateGuild.Perform(context.Guild, db);

            if (EnsureActiveSubscription.Perform(guild, db))
            {
                var service      = new SubscriptionService();
                var subscription = service.Get(guild.SubscriptionId);
                var amount       = subscription.Plan.Amount;
                var date         = subscription.CurrentPeriodEnd;

                var message = $"Your current subscription will renew {date.Value.ToLongDateString()}.\n" +
                              $"To cancel your subscription, use the `!volt cancel` command.";

                await context.Channel.SendMessageAsync(text : message);
            }
            else
            {
                var size = context.Guild.MemberCount <= 200 ? "s" : "l";
                var url  = $"https://nminchow.github.io/VoltaireWeb/upgrade?serverId={context.Guild.Id.ToString()}&type={size}";
                var view = Views.Info.Pro.Response(url, guild, db);
                try {
                    await context.Channel.SendMessageAsync(view.Item1, embed : view.Item2);
                } catch (Discord.Net.HttpException e) {
                    await context.Channel.SendMessageAsync(text : $"Use this URL to upgrade to Volatire Pro: {url}");
                }
            }
        }
Exemplo n.º 3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="rawMessage"></param>
        /// <returns></returns>
        public async Task MessageReceivedAsync(SocketMessage rawMessage)
        {
            // Ignore system messages, or messages from other bots
            if (!(rawMessage is SocketUserMessage message))
            {
                return;
            }
            if (message.Source != MessageSource.User)
            {
                return;
            }


            // Perform a basic check to verify the incoming message is a command invocation
            var argPos = 0;

            if (!message.HasCharPrefix('!', ref argPos) && (!message.HasMentionPrefix(this.discord.CurrentUser, ref argPos)))
            {
                return;
            }

            var context = new ShardedCommandContext(this.discord, message);

            await this.commands.ExecuteAsync(context, argPos, this.services);
        }
Exemplo n.º 4
0
        public async Task <IUserMessage> SendPaginatedMessageAsync(ShardedCommandContext context, PaginatedMessage pager, ICriterion <SocketReaction> criterion = null)
        {
            var callback = new PaginatedMessageCallback(this, context, pager, criterion);
            await callback.DisplayAsync().ConfigureAwait(false);

            return(callback.Message);
        }
Exemplo n.º 5
0
        public async Task <Embed> NowPlayingAsync(ShardedCommandContext context)
        {
            if (!_lavaNode.TryGetPlayer(context.Guild, out var player))
            {
                return(EmbedHandler.CreateEmbed(context, "Music",
                                                $"{Global.ENo} | I'm not connected to a voice channel.", EmbedHandler.EmbedMessageType.Error));
            }

            if (player.PlayerState != PlayerState.Playing)
            {
                return(EmbedHandler.CreateEmbed(context, "Music",
                                                $"{Global.ENo} | There's nothing playing at the moment", EmbedHandler.EmbedMessageType.Error));
            }

            var track   = player.Track;
            var artwork = await track.FetchArtworkAsync();

            var embed = new EmbedBuilder
            {
                Title        = $"{track.Author} - {track.Title}",
                ThumbnailUrl = artwork,
                Description  = GetSong(player),
                Url          = track.Url,
                Color        = Global.NayuColor,
            };

            embed.WithFooter($"Id: {track.Id}");

            return(embed.Build());
        }
Exemplo n.º 6
0
        private Task ExecuteAsync(SocketUserMessage message, int argPos)
        {
            // A new kind of command context, ShardedCommandContext can be utilized with the commands framework
            var context = new ShardedCommandContext(_discord, message);

            return(_commands.ExecuteAsync(context, argPos, _services));
        }
Exemplo n.º 7
0
        public virtual async Task <(GameResult, string)> PickOneAsync(Database db, ShardedCommandContext context, GameResult game, SocketGuildUser[] users, TeamCaptain cap1, TeamCaptain cap2)
        {
            var uc             = users.Count();
            var teamCaptain    = game.Picks % 2 == 0 ? cap1 : cap2;
            var offTeamCaptain = game.Picks % 2 == 0 ? cap2 : cap1;

            if (context.User.Id != teamCaptain.UserId)
            {
                await context.Channel.SendMessageAsync("", false, $"{context.User.Mention} - It is currently the other captains turn to pick.".QuickEmbed(Color.Red));

                return(null, null);
            }

            if (uc == 0)
            {
                await context.Channel.SendMessageAsync("", false, $"{context.User.Mention} - You must specify a player to pick.".QuickEmbed(Color.Red));

                return(null, null);
            }
            else if (uc != 1)
            {
                await context.Channel.SendMessageAsync("", false, $"{context.User.Mention} - You can only specify one player for this pick.".QuickEmbed(Color.Red));

                return(null, null);
            }

            db.TeamPlayers.Add(GetPlayer(game, users[0], game.Picks % 2 == 0 ? 1 : 2));
            var pickResponse = $"{MentionUtils.MentionUser(offTeamCaptain.UserId)} can select **1** player for the next pick.";

            return(game, pickResponse);
        }
Exemplo n.º 8
0
        private async Task HandleCommandAsync(SocketMessage msg)
        {
            var argPos = 0;

            if (!(msg is SocketUserMessage message))
            {
                return;
            }

            await _balanceService.MessageCoin(message.Author.Id);

            var guildChannel = (SocketGuildChannel)message.Channel;

            var r = await _databaseService.LoadRecordsByGuildId(guildChannel.Guild.Id);

            if (message.HasStringPrefix(r.Prefix, ref argPos))
            {
                var context = new ShardedCommandContext(_client, message);

                var result = await _commandService.ExecuteAsync(context, argPos, _services);

                if (!result.IsSuccess && result.Error != CommandError.UnknownCommand)
                {
                    await context.Channel.SendMessageAsync(result.ErrorReason);
                }
            }
        }
Exemplo n.º 9
0
        internal static bool UserHasRole(ShardedCommandContext ctx, ulong roleId)
        {
            var targetRole = ctx.Guild.Roles.FirstOrDefault(r => r.Id == roleId);
            var guildUser  = ctx.User as SocketGuildUser;

            return(guildUser.Roles.Contains(targetRole));
        }
Exemplo n.º 10
0
        public static async Task Reset(ShardedCommandContext context, Core.Entities.Chomusuke chom1,
                                       Core.Entities.Chomusuke chom2)
        {
            var config  = GlobalUserAccounts.GetUserAccount(context.User);
            var player2 = context.Guild.GetUser(config.OpponentId);
            var configg = GlobalUserAccounts.GetUserAccount(player2);

            config.Fighting      = false;
            configg.Fighting     = false;
            chom1.Health         = chom1.HealthCapacity;
            chom2.Health         = chom2.HealthCapacity;
            config.OpponentId    = 0;
            configg.OpponentId   = 0;
            config.OpponentName  = null;
            configg.OpponentName = null;
            config.WhosTurn      = null;
            config.WhoWaits      = null;
            config.PlaceHolder   = null;
            configg.WhosTurn     = null;
            configg.WhoWaits     = null;
            chom1.Effects?.Clear();
            chom2.Effects?.Clear();
            chom1.PotionEffects?.Clear();
            chom2.PotionEffects?.Clear();
            await ActiveChomusuke.ConvertActiveVariable(context.User.Id, config.OpponentId, chom1, chom2);

            GlobalUserAccounts.SaveAccounts(config.Id, configg.Id);
        }
Exemplo n.º 11
0
        public static AttackResult DeflectAttack(ShardedCommandContext context)
        {
            var config = GlobalUserAccounts.GetUserAccount(context.User);
            var chom   = ActiveChomusuke.GetOneActiveChomusuke(config.Id);

            string response;
            bool   success = false;
            int    dmg     = 0;

            if (chom.Effects.Contains(Effect.Blocking))
            {
                response = "You cannot block while already in blocking formation! Try again!";
                return(new AttackResult {
                    Success = success, Response = response, Damage = dmg
                });
            }

            if (chom.Effects.Contains(Effect.Deflecting))
            {
                response = "You are already in deflecting formation! Try again!";
                return(new AttackResult {
                    Success = success, Response = response, Damage = dmg
                });
            }

            chom.Effects.Add(Effect.Deflecting);
            GlobalUserAccounts.SaveAccounts(config.Id);
            response =
                $":shield:  **|** **{config.OpponentName}**, You are now in deflecting formation!\n\n**{config.OpponentName}**'s shield will deflect 50% of the damage from the next attack";
            success = true;
            return(new AttackResult {
                Success = success, Response = response, Damage = dmg
            });
        }
Exemplo n.º 12
0
        public static async Task PerformAsync(ShardedCommandContext context, string identifier, DataBase db)
        {
            if (!BanIdentifier.ValidIdentifier(identifier))
            {
                await context.Channel.SendMessageAsync("Please use the 4 digit number following the identifier to unban users.");

                return;
            }

            var guild = FindOrCreateGuild.Perform(context.Guild, db);

            var identifiers = guild.BannedIdentifiers.Where(x => x.Identifier == identifier);

            if (identifiers.Count() == 0)
            {
                await context.Channel.SendMessageAsync("That user is not currently banned.");

                return;
            }

            db.BannedIdentifiers.RemoveRange(identifiers.ToList());

            db.SaveChanges();
            await context.Channel.SendMessageAsync(text : $"{identifier} is now unbanned");
        }
Exemplo n.º 13
0
        public static async Task Burned(ShardedCommandContext context)
        {
            var config = GlobalUserAccounts.GetUserAccount(context.User);
            var chom   = ActiveChomusuke.GetOneActiveChomusuke(config.Id);

            var dmg = (uint)Global.Rng.Next(2, 5);

            if (!chom.Effects.Contains(Effect.Burned))
            {
                return;
            }
            var rng = Global.Rng.Next(1, 5);

            if (rng == 4)
            {
                chom.Effects.Remove(Effect.Burned);
                GlobalUserAccounts.SaveAccounts(config.Id);
                await SendMessage(context, null, $"{chom.Name} stopped burning!");

                return;
            }

            chom.Health -= dmg;
            GlobalUserAccounts.SaveAccounts(config.Id);
            await SendMessage(context, null, $"{chom.Name} took {dmg} from being burned!");
        }
Exemplo n.º 14
0
        public static PotionResult ExecutePotion(ShardedCommandContext context, string potion, ulong user, ulong target)
        {
            var config = GlobalUserAccounts.GetUserAccount(user);
            var choms  = ActiveChomusuke.GetActiveChomusuke(user, config.OpponentId);
            var chom1  = choms.Item1;
            var chom2  = choms.Item2;
            var result = new PotionResult();

            switch (potion)
            {
            case "Strength Potion":
                result = Potions.StrengthPotion(context, chom1, chom2, target);
                break;

            case "Debuff Potion":
                result = Potions.DebuffPotion(context, chom1, chom2, target);
                break;

            case "Speed Potion":
                result = Potions.SpeedPotion(context, chom1, chom2, target);
                break;

            case "Equalizer Potion":
                result = Potions.EqualizerPotion(context, chom1, chom2, target);
                break;
            }

            return(result);
        }
Exemplo n.º 15
0
        public static async Task PerformAsync(ShardedCommandContext context, string identifier, DataBase db)
        {
            if (!ValidIdentifier(identifier))
            {
                await context.Channel.SendMessageAsync("Please use the 4 digit number following the identifier to ban users.");

                return;
            }

            var guild = FindOrCreateGuild.Perform(context.Guild, db);

            if (!EnsureActiveSubscription.Perform(guild, db))
            {
                await context.Channel.SendMessageAsync("You need an active Voltaire Pro subscription to ban users. To get started, use `!volt pro`");

                return;
            }

            if (guild.BannedIdentifiers.Any(x => x.Identifier == identifier))
            {
                await context.Channel.SendMessageAsync("That identifier is already banned!");

                return;
            }

            guild.BannedIdentifiers.Add(new BannedIdentifier {
                Identifier = identifier
            });
            db.SaveChanges();
            await context.Channel.SendMessageAsync(text : $"{identifier} is now banned");
        }
Exemplo n.º 16
0
        public static EmbedBuilder CreateEmbed(ShardedCommandContext ctx, string title, string desc)
        {
            var thumbnailurl = ctx.User.GetAvatarUrl();
            var boturl       = Global.Client.CurrentUser.GetAvatarUrl();
            var auth         = new EmbedAuthorBuilder()
            {
                IconUrl = thumbnailurl,
                Name    = ctx.User.Username
            };

            var footer = new EmbedFooterBuilder()
            {
                IconUrl = boturl,
                Text    = "Nayu | n!help"
            };

            var embed = new EmbedBuilder()
            {
                Author      = auth,
                Footer      = footer,
                Color       = Global.NayuColor,
                Title       = title,
                Description = desc,
            };

            return(embed);
        }
Exemplo n.º 17
0
        public static AttackResult MeditateAttack(ShardedCommandContext context, Core.Entities.Chomusuke chom)
        {
            var    config = GlobalUserAccounts.GetUserAccount(context.User);
            string response;
            bool   success = false;
            var    dmg     = 0;

            if (chom.Effects.Contains(Effect.Meditating))
            {
                response = $"{chom.Name} has already meditated! Try Again!";
            }
            else if (chom.Effects.Contains(Effect.Blocking))
            {
                response = $"{chom.Name} cannot meditate while in blocking formation! Try Again!";
            }
            else if (chom.Effects.Contains(Effect.Deflecting))
            {
                response = $"{chom.Name} cannot meditate while in deflecting formation! Try Again!";
            }
            else
            {
                response =
                    $":shield:  **|** **{config.OpponentName}**, {chom.Name} just meditated! \n\n**{config.OpponentName}**'s next attack will deal 30% more damage";
                chom.Effects.Add(Effect.Meditating);
                GlobalUserAccounts.SaveAccounts(config.Id);
                success = true;
            }

            return(new AttackResult {
                Success = success, Response = response, Damage = dmg
            });
        }
Exemplo n.º 18
0
        public async Task HandleCommandAsync(SocketMessage message)
        {
            if (message is not SocketUserMessage possibleCmd ||
                possibleCmd.Author.IsBot ||
                string.IsNullOrEmpty(possibleCmd.Content))
            {
                return;
            }

            var prefix = "y!";

            if (possibleCmd.Channel is SocketTextChannel textChannel)
            {
                var id          = textChannel.Guild.Id;
                var guildConfig = await _guildConfigDbService.GetGuildConfigAsync(id);

                prefix = guildConfig.Prefix;
            }

            var argPos = 0;

            if ((possibleCmd.HasStringPrefix(prefix, ref argPos) || possibleCmd.HasMentionPrefix(_client.CurrentUser, ref argPos)) &&
                possibleCmd.Content.Trim() != prefix)
            {
                var context = new ShardedCommandContext(_client, possibleCmd);
                var user    = possibleCmd.Author;

                switch (possibleCmd.Channel)
                {
                case SocketDMChannel:
                    _logger.Info("{Username:l}#{Discriminator:l} in DM's", user.Username, user.Discriminator);
                    break;

                case SocketTextChannel txtChannel:
                    _logger.Info("{Username:l}#{Discriminator:l} from {GuildName:l}/{ChannelName:l}", user.Username, user.Discriminator, txtChannel.Guild.Name, txtChannel.Name);
                    break;
                }

                _logger.Info(possibleCmd.Content);

                var result = await _commandService.ExecuteAsync(context, argPos, _serviceProvider);

                if (!result.IsSuccess)
                {
                    if (result.ErrorReason.Contains("unknown command", StringComparison.OrdinalIgnoreCase))
                    {
                        return;
                    }

                    if (result.ErrorReason.Contains("you are currently in timeout", StringComparison.OrdinalIgnoreCase))
                    {
                        await context.Channel.SendMessageAsync("Please wait 5 seconds between each type of paginator command!");
                    }

                    //await context.Channel.SendMessageAsync("https://goo.gl/JieFJM");

                    _logger.Error(result.ErrorReason);
                }
            }
        }
Exemplo n.º 19
0
        private async Task MessageReceived(SocketMessage message)
        {
            SocketUserMessage    Message = message as SocketUserMessage;
            SocketCommandContext Context = new ShardedCommandContext(_client, Message);

            if (Context.User.IsBot)
            {
                return;
            }

            int argpos = 0;

            var user = await Users.GetOrAddValue((long)Context.User.Id);

            await Users.SaveAsync(user);

            if (!Message.HasStringPrefix(user.Prefix, ref argpos) && !Message.HasMentionPrefix(Context.Client.CurrentUser, ref argpos))
            {
                return;
            }

            if (_userTimeouts.AddOrUpdate(Context.User.Id, 1, (ulong id, int i) => { return(i + 1); }) == 5)
            {
                _userTimeouts[Context.User.Id]--;
                return;
            }

            var result = await _commandService.ExecuteAsync(Context, argpos, _services);

            if (!result.IsSuccess)
            {
                _ = Context.Channel.SendMessageAsync($"{Context.User.Mention} Error: `{result.ErrorReason}`");
            }
        }
Exemplo n.º 20
0
        private Task OnMessageReceivedAsync(SocketMessage s)
        {
            _ = Task.Run(async() =>
            {
                if (!(s is SocketUserMessage msg))
                {
                    return;
                }
                if (!(s.Channel is SocketGuildChannel))
                {
                    return;
                }

                int argPos  = 0;
                var context = new ShardedCommandContext(_discord, msg);
                if (msg.HasMentionPrefix(_discord.CurrentUser, ref argPos))
                {
                    if (!(context.User as SocketGuildUser).GuildPermissions.Administrator)
                    {
                        if (IsRatelimited(context.User.Id))
                        {
                            return;
                        }
                    }

                    using (context.Channel.EnterTypingState())
                    {
                        await ExecuteAsync(context, _provider, context.Message.Content.Substring(argPos));
                    }
                }
            });
            return(Task.CompletedTask);
        }
Exemplo n.º 21
0
        public async Task <SocketMessage> NextMessageAsync(ShardedCommandContext context, ICriterion <SocketMessage> criterion, TimeSpan?timeout = null)
        {
            timeout = timeout ?? _defaultTimeout;

            var eventTrigger = new TaskCompletionSource <SocketMessage>();

            async Task Handler(SocketMessage message)
            {
                var result = await criterion.JudgeAsync(context, message).ConfigureAwait(false);

                if (result)
                {
                    eventTrigger.SetResult(message);
                }
            }

            context.Client.MessageReceived += Handler;

            var trigger = eventTrigger.Task;
            var delay   = Task.Delay(timeout.Value);
            var task    = await Task.WhenAny(trigger, delay).ConfigureAwait(false);

            context.Client.MessageReceived -= Handler;

            if (task == trigger)
            {
                return(await trigger.ConfigureAwait(false));
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 22
0
        public static async Task PerformAsync(ShardedCommandContext context, string guildName, string channelName, string message, bool replyable, DataBase db)
        {
            var unfilteredList  = Send.GuildList(context);
            var candidateGuilds = unfilteredList.Where(x => x.Id.ToString() == guildName || x.Name.ToLower().Contains(guildName.ToLower()));

            switch (candidateGuilds.Count())
            {
            case 0:
                await Send.SendErrorWithDeleteReaction(context, "No servers with the specified name could be found. The servers must have Voltaire installed and you must be a member of the server.");

                break;

            case 1:
                await LookupAndSendAsync(candidateGuilds.First(), context, channelName, message, replyable, db);

                break;

            default:
                // check for exact match
                var exactNameMatch = candidateGuilds.First(x => x.Id.ToString() == guildName || x.Name.ToLower() == guildName.ToLower());
                if (exactNameMatch != null)
                {
                    await LookupAndSendAsync(exactNameMatch, context, channelName, message, replyable, db);

                    return;
                }
                await Send.SendErrorWithDeleteReaction(context, "More than one server with the spcified name was found. Please use a more specific server name.");

                break;
            }
        }
Exemplo n.º 23
0
        private async Task HandleCommandAsync(SocketMessage message)
        {
            var msg = message as SocketUserMessage;

            if (msg == null)
            {
                return;
            }

            var context = new ShardedCommandContext(_client, msg);

            int argPos = 0;

            if (msg.Author.IsBot)
            {
                return;
            }

            if (msg.HasStringPrefix(_botPrefix, ref argPos))
            {
                var result = await _command.ExecuteAsync(context, argPos, _services);

                if (!result.IsSuccess && result.Error != CommandError.UnknownCommand)
                {
                    Console.WriteLine(result.ErrorReason);
                    return;
                }
            }
        }
Exemplo n.º 24
0
        private async Task OnMessageReceivedAsync(SocketMessage s)
        {
            var msg = s as SocketUserMessage; // Ensure the message is from a user/bot

            if (msg == null)
            {
                return;
            }

            if (msg.Author.Id == this._discord.CurrentUser.Id)
            {
                return; // Ignore self when checking commands
            }

            if (msg.Author.IsBot)
            {
                return; // Ignore bots
            }

            var context = new ShardedCommandContext(this._discord, msg); // Create the command context

            var argPos       = 0;                                        // Check if the message has a valid command prefix
            var customPrefix = this._prefixService.GetPrefix(context.Guild?.Id);

            if (msg.HasStringPrefix(ConfigData.Data.CommandPrefix, ref argPos) && customPrefix == null || msg.HasMentionPrefix(this._discord.CurrentUser, ref argPos))
            {
                await ExecuteCommand(msg, context, argPos);
            }
            else if (msg.HasStringPrefix(customPrefix, ref argPos, StringComparison.CurrentCultureIgnoreCase))
            {
                await ExecuteCommand(msg, context, argPos, customPrefix);
            }
        }
Exemplo n.º 25
0
        private static async Task FaqProccesser(SocketMessage socketMessage)
        {
            var argPos  = 0;
            var message = socketMessage as SocketUserMessage;

            if (message == null)
            {
                return;
            }
            if (!message.HasStringPrefix("?fa", ref argPos))
            {
                return;
            }
            var context = new ShardedCommandContext(_client, message);

            if (context.IsPrivate)
            {
                return;
            }
            if (!context.Channel.CheckChannelPermission(ChannelPermission.SendMessages, context.Guild.CurrentUser))
            {
                return;
            }

            var result = await _commandService.ExecuteAsync(context, argPos, _provider);

            if (!result.IsSuccess)
            {
                Logger.Warn(result);
            }
        }
Exemplo n.º 26
0
        private async Task <bool> CommandAsync(SocketUserMessage message)
        {
            var context = new ShardedCommandContext(client, message);

            string prefix          = storage.GetPrefix(context.Guild);
            int    commandPosition = 0;

            if (message.HasMentionPrefix(client.CurrentUser, ref commandPosition) ||
                message.HasStringPrefix($"{prefix} ", ref commandPosition) || message.HasStringPrefix(prefix, ref commandPosition) ||
                context.Channel is IDMChannel || storage.NoPrefixChannel(context.Channel.Id))
            {
                var result = await commands.ExecuteAsync(context, commandPosition, provider);

                if (result.IsSuccess)
                {
                    return(true);
                }
                else if (!result.ErrorReason.Contains("Unknown command"))
                {
                    await logger.Log(LogSeverity.Verbose, LogSource.Command,
                                     $"\"{message}\" by {message.Author.FullName()} in {context.Channel.FullName()} " +
                                     $"couldn't be executed. {result.ErrorReason}");

                    string reply = CommandErrorReply(result.ErrorReason, context.Guild);
                    if (reply != null && context.BotCan(ChannelPermission.SendMessages))
                    {
                        await context.Channel.SendMessageAsync(reply, options : Bot.DefaultOptions);
                    }

                    return(true);
                }
            }

            return(false);
        }
Exemplo n.º 27
0
        private async Task FaqProccesser(SocketMessage socketMessage)
        {
            var argPos  = 0;
            var message = socketMessage as SocketUserMessage;

            if (message == null)
            {
                return;
            }
            if (!message.HasStringPrefix(_config["Prefixes:Faq"], ref argPos, StringComparison.OrdinalIgnoreCase))
            {
                return;
            }
            var context = new ShardedCommandContext(_client, message);

            if (context.IsPrivate)
            {
                return;
            }
            if (!context.Channel.CheckChannelPermission(ChannelPermission.SendMessages, context.Guild.CurrentUser))
            {
                return;
            }

            var result = await _commandService.ExecuteAsync(context, argPos, _provider);

            if (!result.IsSuccess)
            {
                if (message.HasStringPrefix(_config["Prefixes:Main"], ref argPos, StringComparison.OrdinalIgnoreCase))
                {
                    return;
                }
                _logger.LogWarning(new EventId(515), result.ErrorReason);
            }
        }
Exemplo n.º 28
0
        public async Task MessageReceivedAsync(SocketMessage rawMessage)
        {
            // Ignore system messages, or messages from other bots
            if (!(rawMessage is SocketUserMessage message))
            {
                return;
            }
            if (message.Source != MessageSource.User)
            {
                return;
            }

            // This value holds the offset where the prefix ends
            var argPos = 0;

            if (!message.HasMentionPrefix(_discord.CurrentUser, ref argPos))
            {
                if (message.Content.ToUpper().StartsWith("BG") || message.Content.ToUpper().StartsWith("JB"))
                {
                    argPos = 2;
                }
                else
                {
                    return;
                }
            }
            // A new kind of command context, ShardedCommandContext can be utilized with the commands framework
            var context = new ShardedCommandContext(_discord, message);
            await _commands.ExecuteAsync(context, argPos, _services);
        }
        /// <summary>
        ///     Checks if the message contains a prefix.
        /// </summary>
        /// <param name="msg">The socket user message.</param>
        private async Task CheckForPrefixAsync(SocketUserMessage msg)
        {
            // If the user is a bot, return.
            if (msg.Author.IsBot)
            {
                return;
            }

            // Create the shared command context.
            var context = new ShardedCommandContext(_client, msg);
            var argPos  = 0;

            // Check if the message has a valid default command prefix.
            if (context.Message.HasStringPrefix(Constants.Prefix, ref argPos, StringComparison.CurrentCultureIgnoreCase) ||
                context.Message.HasMentionPrefix(_client.CurrentUser, ref argPos))
            {
                await HandleCommandAsync(context, argPos).ConfigureAwait(false);
            }

            // Check if the message has a valid custom command prefix.
            var customPrefix = _prefixService.GetPrefix(context.Guild.Id);

            if (customPrefix == null)
            {
                return;
            }
            if (context.Message.HasStringPrefix(customPrefix, ref argPos, StringComparison.CurrentCultureIgnoreCase))
            {
                await HandleCommandAsync(context, argPos).ConfigureAwait(false);
            }
        }
Exemplo n.º 30
0
        public static async Task SendMessageAndCatchError(Func <Task> send, ShardedCommandContext context)
        {
            try
            {
                await send();
            }
            catch (Discord.Net.HttpException e)
            {
                switch (e.DiscordCode)
                {
                case 50007:
                    await context.Channel.SendMessageAsync("Voltaire has been blocked by this user.");

                    break;

                case 50013:
                case 50001:
                    await context.Channel.SendMessageAsync("Voltaire doesn't have the " +
                                                           "permissions required to send this message. Ensure Voltaire can access the channel you are tyring to send to, and that it has " +
                                                           " \"Embed Links\" and \"Use External Emojis\" permission.");

                    break;
                }

                throw e;
            }
        }