Beispiel #1
0
        public static Tuple <string, Embed> Response(UnifiedContext context)
        {
            var embed = new EmbedBuilder
            {
                Author = new EmbedAuthorBuilder
                {
                    Name = "Guide"
                },
                ThumbnailUrl = "https://nminchow.github.io/VoltaireWeb/images/quill.png",
                Description  = "Voltaire allows you to send messages to a discord server anonymously.\n\n" +
                               "Support Server: https://discord.gg/xyzMyJH \n\n" +
                               "**Direct Message Commands:**",
                Color = new Color(111, 111, 111),
            };

            embed.AddField("/volt", "Sends an anonymous message to the current channel.");
            embed.AddField("/send-dm", "Sends an anonymous message to the specified user.");
            embed.AddField("/send", "Sends an anonymous message to the specified channel in the current server.");
            embed.AddField("/send-reply", "Sends a reply to the specified message in the current server.");

            embed.AddField("/react",
                           "Send a reaction to a message. [Enable dev settings to get message IDs](https://support.discord.com/hc/en-us/articles/206346498-Where-can-I-find-my-User-Server-Message-ID). " +
                           "The `emote/emoji` param can be either a unicode emoji, or the name of a custom emote.");

            embed.AddField("/volt-link", "Display the [bot's invite link](https://discordapp.com/oauth2/authorize?client_id=425833927517798420&permissions=2147998784&scope=bot%20applications.commands).");
            embed.AddField("/volt-faq", "Display the [FAQ link](https://discordapp.com/channels/426894892262752256/581280324340940820/612849796025155585).");
            embed.AddField("/volt-admin help", "Get a list of admin commands, including details on Voltaire Pro.");
            embed.AddField("/volt-help", "(callable from anywhere) Display this help dialogue.");

            return(new Tuple <string, Embed>("", embed.Build()));
        }
Beispiel #2
0
        public static async Task PerformAsync(UnifiedContext 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;
            }
        }
Beispiel #3
0
        public static async Task PerformAsync(UnifiedContext context, string identifier, DataBase db)
        {
            if (!BanIdentifier.ValidIdentifier(identifier))
            {
                await Send.SendErrorWithDeleteReaction(context, "Please use the 4 digit number following the identifier to unban users.");

                return;
            }

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

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

            if (identifiers.Count() == 0)
            {
                await Send.SendErrorWithDeleteReaction(context, "That user is not currently banned.");

                return;
            }

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

            await db.SaveChangesAsync();

            await Send.SendMessageToContext(context, $"{identifier} is now unbanned");
        }
Beispiel #4
0
        public static async Task PerformAsync(UnifiedContext context, DataBase db)
        {
            var guild = await 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 `/pro-cancel` command.";

                await Send.SendMessageToContext(context, 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 Send.SendMessageToContext(context, view.Item1, embed : view.Item2);
                } catch (Discord.Net.HttpException e) {
                    await Send.SendMessageToContext(context, $"Use this URL to upgrade to Volatire Pro: {url}");
                }
            }
        }
Beispiel #5
0
        public static async Task PerformAsync(UnifiedContext context, string identifier, DataBase db)
        {
            if (!ValidIdentifier(identifier))
            {
                await Send.SendErrorWithDeleteReaction(context, "Please use the 4 digit number following the identifier to ban users.");

                return;
            }

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

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

                return;
            }

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

                return;
            }

            guild.BannedIdentifiers.Add(new BannedIdentifier {
                Identifier = identifier
            });
            await db.SaveChangesAsync();

            await Send.SendMessageToContext(context, $"{identifier} is now banned");
        }
Beispiel #6
0
        public static async Task PerformAsync(UnifiedContext context, DataBase db)
        {
            try
            {
                var guild = await 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();

                await db.SaveChangesAsync();

                await Send.SendMessageToContext(context, "User identifiers have been randomized.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("error rotating");
                Console.WriteLine(ex.ToString());
            }
        }
Beispiel #7
0
 public static string ComputePrefix(UnifiedContext context, Guild guild, string defaultValue = "")
 {
     if (!guild.UseUserIdentifiers)
     {
         return(defaultValue);
     }
     return(Generate(GetIdentifierInteger(context.User.Id, guild)));
 }
Beispiel #8
0
        public static async Task SendToChannelById(ulong channelId, UnifiedContext context, string message, bool replyable, DataBase db)
        {
            var unfilteredList = ToChannelList(Send.GuildList(context));
            var target         = unfilteredList.FirstOrDefault(x => x.Id == channelId);

            await LookupAndSendAsync(target.Guild, context, channelId.ToString(), message, replyable, db);

            return;
        }
Beispiel #9
0
        public static async Task PerformAsync(UnifiedContext context, SocketRole role, DataBase db)
        {
            var guild = await FindOrCreateGuild.Perform(context.Guild, db);

            guild.AllowedRole = role.Id.ToString();
            await db.SaveChangesAsync();

            await Send.SendMessageToContext(context, $"{role.Name} is now the only role that can use Voltaire on this server");
        }
Beispiel #10
0
        public static async Task PerformAsync(UnifiedContext context, DataBase db)
        {
            var guild = await FindOrCreateGuild.Perform(context.Guild, db);

            db.RemoveRange(guild.BannedIdentifiers);
            await db.SaveChangesAsync();

            await Send.SendMessageToContext(context, "Bans cleared");
        }
Beispiel #11
0
        public static async Task PerformAsync(UnifiedContext context, DataBase db)
        {
            var guild = await FindOrCreateGuild.Perform(context.Guild, db);

            guild.AllowedRole = null;
            await db.SaveChangesAsync();

            await Send.SendMessageToContext(context, $"All users can now use Voltaire.");
        }
        public static async Task PerformAsync(UnifiedContext context, Boolean setting, DataBase db)
        {
            var guild = await FindOrCreateGuild.Perform(context.Guild, db);

            guild.UseUserIdentifiers = setting;
            await db.SaveChangesAsync();

            await Send.SendMessageToContext(context, $"'User Identifiers' set to {setting}");
        }
        public EmailAppServiceInMemoryTests(WarmupUnifiedContext unifiedContext, ITestOutputHelper output)
        {
            _output            = output;
            _faker             = new Faker();
            UnifiedContextData = unifiedContext;
            _emailAppService   = UnifiedContextData.Services.GetRequiredService <IEmailAppService>();
            _database          = UnifiedContextData.Services.GetRequiredService <UnifiedContext>();
            _notifications     = (DomainNotificationHandler)UnifiedContextData.Services.GetRequiredService <INotificationHandler <DomainNotification> >();

            _notifications.Clear();
        }
Beispiel #14
0
 public static async Task SendMessageToContext(UnifiedContext context, string message, Embed embed = null)
 {
     if (context is CommandBasedContext commandContext)
     {
         await commandContext.Channel.SendMessageAsync(message, embed : embed);
     }
     else if (context is InteractionBasedContext interactionContext)
     {
         await interactionContext.Responder(message, embed);
     }
 }
Beispiel #15
0
 public static async Task SendErrorWithDeleteReaction(UnifiedContext context, string errorMessage, Embed embed = null)
 {
     if (context is CommandBasedContext commandContext)
     {
         var message = await commandContext.Channel.SendMessageAsync(errorMessage, embed : embed);
         await AddReactionToMessage(message);
     }
     else if (context is InteractionBasedContext interactionContext)
     {
         await interactionContext.Responder(errorMessage, embed);
     }
 }
Beispiel #16
0
 public static async Task SendSentEmoteIfCommand(UnifiedContext context)
 {
     if (context is CommandBasedContext commandContext)
     {
         var emote = Emote.Parse(LoadConfig.Instance.config["sent_emoji"]);
         await commandContext.Message.AddReactionAsync(emote);
     }
     else if (context is InteractionBasedContext interactionContext)
     {
         await interactionContext.Responder("Sent!", null);
     }
 }
Beispiel #17
0
        public static Tuple <string, Embed> Response(UnifiedContext context)
        {
            var embed = new EmbedBuilder
            {
                Author = new EmbedAuthorBuilder
                {
                    Name = "Admin Guide"
                },
                ThumbnailUrl = "https://nminchow.github.io/VoltaireWeb/images/quill.png",
                Description  = "These commands are only callable by admin users.\n\n" +
                               "Commands should be sent to the bot in a server channel.\n\n" +
                               "**Guild Channel Commands:**",
                Color = new Color(111, 111, 111)
            };

            embed.AddField("!volt allow_dm {true|false}", "Allow or disallow users to send direct messages to other members of the server." +
                           $"\nex: `!volt allow_dm false`");

            embed.AddField("!volt embeds {true|false}", "Make all messages sent via the bot appear as embeds     on this server." +
                           $"\nex: `!volt embeds true`");

            embed.AddField("!volt permitted_role \"{role name}\"", "Only allow users with the supplied role to send server messages and direct messages on the server." +
                           "Note that all users can still send replies. To clear, set the permitted role to @everyone." +
                           $"\nex: `!volt permitted_role \"speakers of truth\"`");

            embed.AddField("!volt user_identifiers {true|false}", "Enable or disable the use of a unique (yet annonymous) identifier for users when they send messages." +
                           $"\nex: `!volt user_identifiers false`");

            embed.AddField("!volt new_identifiers", "Generate new random identifiers for users. (Note: Banned users will still be banned.)" +
                           $"\nex: `!volt new_identifiers`");

            embed.AddField("!volt pro", "Upgrade and monitor your Pro subscription." +
                           $"\nex: `!volt pro`");

            embed.AddField("!volt ban {user id}", "Blacklists a user from the bot by user ID. This is the 4 digit number after their identifier when the \"user_identifiers\" setting is enabled." +
                           $"\nex: `!volt ban 4321`");

            embed.AddField("!volt list_bans", "List currently banned user IDs." +
                           $"\nex: `!volt list_bans`");

            embed.AddField("!volt clear_bans", "Clear the currently banned user list." +
                           $"\nex: `!volt clear_bans`");

            embed.AddField("!volt admin_role \"{role name}\"", "Set a role which can use admin commands and ban users on this server. (True server admins can always use commands as well)" +
                           $"\nex: `!volt admin_role \"mods of truth\"`");

            embed.AddField("!volt refresh ", "Refresh the user list for this server. This command isn't regularly necessary, but may be helpful when the bot first joins your server." +
                           $"\nex: `!volt refresh`");

            embed.AddField("!volt admin", "(callable from anywhere) Display this help dialogue.");

            return(new Tuple <string, Embed>("", embed.Build()));
        }
        public EventAppServiceTest(WarmupUnifiedContext unifiedContext, ITestOutputHelper output)
        {
            _output               = output;
            _faker                = new Faker();
            UnifiedContextData    = unifiedContext;
            _eventStoreAppService = UnifiedContextData.Services.GetRequiredService <IEventStoreAppService>();
            _userAppService       = UnifiedContextData.Services.GetRequiredService <IUserAppService>();
            _database             = UnifiedContextData.Services.GetRequiredService <UnifiedContext>();
            _notifications        = (DomainNotificationHandler)UnifiedContextData.Services.GetRequiredService <INotificationHandler <DomainNotification> >();

            _notifications.Clear();
        }
Beispiel #19
0
        public static async Task PerformAsync(UnifiedContext context, DataBase db)
        {
            var guild = await FindOrCreateGuild.Perform(context.Guild, db);

            var bannedIdentifiers = guild.BannedIdentifiers.Select(x => x.Identifier).ToArray();

            if (bannedIdentifiers.Count() == 0)
            {
                await Send.SendMessageToContext(context, $"No users are currently banned.");

                return;
            }

            await Send.SendMessageToContext(context, $"**Banned Users:**\n{String.Join("\n", bannedIdentifiers)}");
        }
Beispiel #20
0
        public static async Task PerformAsync(UnifiedContext context, ulong messageId, string emoji, DataBase db)
        {
            var guildList = Send.GuildList(context);

            var task = await Task.WhenAll(guildList.SelectMany(x => x.TextChannels).Select(async x => {
                try {
                    var message = await x.GetMessageAsync(messageId);
                    return(message);
                } catch {
                    return(null);
                }
            }));

            var r = task.Where(x => x != null);

            if (r.Count() == 0)
            {
                await Send.SendErrorWithDeleteReaction(context, "message not found");

                return;
            }

            // test for simple emoji (😃)
            try {
                var d = new Discord.Emoji(emoji);
                await r.First().AddReactionAsync(d);

                await Send.SendSentEmoteIfCommand(context);

                return;
            } catch (Discord.Net.HttpException) {}

            // look for custom discord emotes
            var emote = guildList.SelectMany(x => x.Emotes).FirstOrDefault(x => $":{x.Name}:".IndexOf(
                                                                               emoji, StringComparison.OrdinalIgnoreCase) != -1);

            if (emote != null)
            {
                await r.First().AddReactionAsync(emote);

                await Send.SendSentEmoteIfCommand(context);
            }
            else
            {
                await Send.SendErrorWithDeleteReaction(context, "Emoji not found. To send a custom emote, use the emote's name.");
            }
            return;
        }
Beispiel #21
0
        public static async Task PerformAsync(UnifiedContext context, SocketRole role, DataBase db)
        {
            var guild = await FindOrCreateGuild.Perform(context.Guild, db);

            if (!EnsureActiveSubscription.Perform(guild, db))
            {
                await Send.SendMessageToContext(context, "You need an active Voltaire Pro subscription to set an admin role. To get started, use `/pro`");

                return;
            }

            guild.AdminRole = role.Id.ToString();
            await db.SaveChangesAsync();

            await Send.SendMessageToContext(context, $"{role.Name} can now configure Voltaire and ban users on this server.");
        }
Beispiel #22
0
        public static async Task LookupAndSendAsync(SocketGuild guild, UnifiedContext context, string channelName, string message, bool replyable, DataBase db)
        {
            var dbGuild = await FindOrCreateGuild.Perform(guild, db);

            if (!UserHasRole.Perform(guild, context.User, dbGuild))
            {
                await Send.SendErrorWithDeleteReaction(context, "You do not have the role required to send messages to this server.");

                return;
            }

            var candidateChannels = guild.TextChannels.Where(x => x.Name.ToLower().Contains(channelName.ToLower()) || x.Id.ToString() == channelName);

            if (!candidateChannels.Any())
            {
                await Send.SendErrorWithDeleteReaction(context, "The channel you specified couldn't be found. Please specify your desired channel before your message: `send (channel_name) (message)` ex: `send some-channel Nothing is true, everything is permitted.`");

                return;
            }

            if (PrefixHelper.UserBlocked(context.User.Id, dbGuild))
            {
                await Send.SendErrorWithDeleteReaction(context, "It appears that you have been banned from using Voltaire on the targeted server. If you think this is an error, contact one of your admins.");

                return;
            }

            if (!await IncrementAndCheckMessageLimit.Perform(dbGuild, db))
            {
                await Send.SendErrorWithDeleteReaction(context, "This server has reached its limit of 50 messages for the month. To lift this limit, ask an admin or moderator to upgrade your server to Voltaire Pro. (This can be done via the `/pro` command.)");

                return;
            }

            var prefix          = PrefixHelper.ComputePrefix(context, dbGuild);
            var channel         = candidateChannels.OrderBy(x => x.Name.Length).First();
            var messageFunction = Send.SendMessageToChannel(channel, replyable, context, dbGuild.UseEmbed);

            await messageFunction(prefix, message);

            await Send.SendSentEmoteIfCommand(context);

            return;
        }
Beispiel #23
0
        public static async Task PerformAsync(UnifiedContext context, DataBase db)
        {
            var guild = await FindOrCreateGuild.Perform(context.Guild, db);

            if (EnsureActiveSubscription.Perform(guild, db))
            {
                var service = new SubscriptionService();
                var options = new SubscriptionCancelOptions {
                    Prorate = false
                };
                service.Cancel(guild.SubscriptionId, options);

                await Send.SendMessageToContext(context, "Your subscription has been canceled. Use `/pro` to re-upgrade at any time!");
            }
            else
            {
                await Send.SendMessageToContext(context, "You do not currently have an active Voltaire Pro subscription. To create one, use the" +
                                                " `/pro` command.");
            }
        }
Beispiel #24
0
        public static async Task PerformAsync(UnifiedContext context, string replyKey, string message, bool replyable, DataBase db)
        {
            var candidateGuilds = Send.GuildList(context);

            var key         = LoadConfig.Instance.config["encryptionKey"];
            var candidateId = Rijndael.Decrypt(replyKey, key, KeySize.Aes256);

            // TODO: potentially want to bake guilds into reply codes so we can ensure that the the replier isn't banned on the server where the original
            // message was sent
            var users = SendDirectMessage.ToUserList(candidateGuilds).Where(x => x.Id.ToString() == candidateId);

            if (users.Count() == 0)
            {
                await Send.SendErrorWithDeleteReaction(context, "Something is wrong with that reply code. It is possible the sender has left your server.");

                return;
            }

            var allowedGuild = users.ToList().Select(async x => await FindOrCreateGuild.Perform(x.Guild, db)).FirstOrDefault(x => !PrefixHelper.UserBlocked(context.User.Id, x.Result));

            if (allowedGuild == null)
            {
                await Send.SendErrorWithDeleteReaction(context, "It appears that you have been banned from using Voltaire on the targeted server. If you think this is an error, contact one of your admins.");

                return;
            }

            var prefix = $"{PrefixHelper.ComputePrefix(context, allowedGuild.Result, "someone")} replied";

            // all 'users' here are technically the same user, so just take the first
            var channel = await users.First().CreateDMChannelAsync();

            var messageFunction = Send.SendMessageToChannel(channel, replyable, context);
            var sentMessage     = await messageFunction(prefix, message);

            await Send.AddReactionToMessage(sentMessage);

            await Send.SendSentEmoteIfCommand(context);
        }
Beispiel #25
0
        public static async Task PerformAsync(UnifiedContext context, string channelName, string message, bool reply, DataBase db)
        {
            var candidateGuilds = GuildList(context);

            switch (candidateGuilds.Count())
            {
            case 0:
                await SendErrorWithDeleteReaction(context, "It doesn't look like you belong to any servers where Voltaire is installed. Please add Voltaire to your desired server.");

                break;

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

                break;

            default:
                var view = Views.Info.MultipleGuildSendResponse.Response(candidateGuilds, message);
                await SendErrorWithDeleteReaction(context, view.Item1, view.Item2);

                break;
            }
        }
Beispiel #26
0
        public static Tuple <string, Embed> Response(UnifiedContext context)
        {
            var embed = new EmbedBuilder
            {
                Author = new EmbedAuthorBuilder
                {
                    Name = "Admin Guide"
                },
                ThumbnailUrl = "https://nminchow.github.io/VoltaireWeb/images/quill.png",
                Description  = "These commands are only callable by admin users.\n\n" +
                               "Commands should be sent to the bot in a server channel.\n\n" +
                               "**Guild Channel Commands:**",
                Color = new Color(111, 111, 111)
            };

            embed.AddField("/volt-admin settings", "Configure Voltaire's general settings, including DMs, identifiers, the use of embeds, and permitted role.");

            embed.AddField("/volt-admin new-identifiers ", "rotate user identifiers");

            embed.AddField("/pro", "Upgrade and monitor your Pro subscription.");

            embed.AddField("/volt-admin ban", "Blacklists a user from the bot by user ID. This is the 4 digit number after their identifier when the \"use-identifiers\" setting is enabled.");

            embed.AddField("/volt-admin unban", "Unban a user from the bot by user ID.");

            embed.AddField("/volt-admin list-bans list_bans", "List currently banned user IDs.");

            embed.AddField("/volt-admin clear-bans", "Clear the currently banned user list.");

            embed.AddField("/volt-admin refresh", "Refresh the user list for this server. This command isn't regularly necessary, but may be helpful when the bot first joins your server.");

            embed.AddField("/volt-admin role", "Set a role which can use admin commands and ban users on this server. (True server admins can always use admin commands as well)");

            embed.AddField("/volt-admin help", "(callable from anywhere) Display this help dialogue.");

            return(new Tuple <string, Embed>("", embed.Build()));
        }
Beispiel #27
0
        public static async Task PerformAsync(UnifiedContext context, DataBase db)
        {
            Helpers.JoinedGuild.Refresh(context.Guild);

            await Send.SendMessageToContext(context, "User list has been refreshed.");
        }
Beispiel #28
0
        public static Func <string, string, Task <IUserMessage> > SendMessageToChannel(IMessageChannel channel, bool replyable, UnifiedContext context, bool forceEmbed = false)
        {
            if (!replyable)
            {
                return(async(username, message) =>
                {
                    message = CheckForMentions(channel, message);
                    if (forceEmbed)
                    {
                        var view = Views.Message.Response(username, message, null);
                        return await SendMessageAndCatchError(() => { return channel.SendMessageAsync(view.Item1, embed: view.Item2); }, context);
                    }

                    if (string.IsNullOrEmpty(username))
                    {
                        return await SendMessageAndCatchError(() => { return channel.SendMessageAsync(message); }, context);
                    }
                    return await SendMessageAndCatchError(() => { return channel.SendMessageAsync($"**{username}**: {message}"); }, context);
                });
            }
            return(async(username, message) =>
            {
                var key = LoadConfig.Instance.config["encryptionKey"];
                var replyHash = Rijndael.Encrypt(context.User.Id.ToString(), key, KeySize.Aes256);
                var view = Views.Message.Response(username, message, replyHash.ToString());
                return await SendMessageAndCatchError(() => { return channel.SendMessageAsync(view.Item1, embed: view.Item2); }, context);
            });
        }
Beispiel #29
0
        public static async Task <IUserMessage> SendMessageAndCatchError(Func <Task <IUserMessage> > send, UnifiedContext context)
        {
            try
            {
                return(await send());
            }
            catch (Discord.Net.HttpException e)
            {
                switch (e.DiscordCode)
                {
                case DiscordErrorCode.CannotSendMessageToUser:
                    await SendMessageToContext(context, "Voltaire has been blocked by this user, or they have DMs dsiabled.");

                    break;

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

                    break;
                }

                throw e;
            }
        }
Beispiel #30
0
        public static async Task PerformAsync(UnifiedContext context, string userName, string message, bool replyable, DataBase db)
        {
            // convert special discord tag to regular ID format
            userName = userName.StartsWith("<@!") && userName.EndsWith('>') ? userName.Substring(3, userName.Length - 4) : userName;
            userName = userName.StartsWith("<@") && userName.EndsWith('>') ? userName.Substring(2, userName.Length - 3) : userName;

            userName = userName.StartsWith('@') ? userName.Substring(1) : userName;
            try
            {
                var guildList = Send.GuildList(context);
                List <SocketGuildUser> allUsersList = ToUserList(guildList);

                var userList = allUsersList.Where(x => x.Username != null &&
                                                  (
                                                      // simple username
                                                      x.Username.ToLower() == userName.ToLower() ||
                                                      // id
                                                      x.Id.ToString() == userName ||
                                                      // username with discriminator
                                                      $"{x.Username}#{x.Discriminator}".ToLower() == userName.ToLower()
                                                  ) &&
                                                  !x.IsBot);

                var allowDmList = userList.Where(x => FilterGuildByDirectMessageSetting(x, db).Result);

                if (!allowDmList.Any() && userList.Any())
                {
                    await Send.SendErrorWithDeleteReaction(context, "user found, but channel permissions do not allow annonymous direct messaging");

                    return;
                }

                var requiredRoleList = allowDmList.Where(x => FilterGuildByRole(x, context.User, db));

                if (!requiredRoleList.Any() && allowDmList.Any())
                {
                    await Send.SendErrorWithDeleteReaction(context, "user found, but you do not have the role required to DM them");

                    return;
                }

                var list = requiredRoleList.ToList().Select(async x => Tuple.Create(x, await FindOrCreateGuild.Perform(x.Guild, db)));

                var userGuild = list.FirstOrDefault(x => !PrefixHelper.UserBlocked(context.User.Id, x.Result.Item2));

                if (userGuild == null && requiredRoleList.Any())
                {
                    await Send.SendErrorWithDeleteReaction(context, "user found, but you have been banned from using Voltaire on your shared server");
                }
                else if (userGuild == null)
                {
                    await Send.SendErrorWithDeleteReaction(context, "user not found");

                    return;
                }

                var userChannel = await userGuild.Result.Item1.CreateDMChannelAsync();

                var prefix          = PrefixHelper.ComputePrefix(context, userGuild.Result.Item2, "anonymous user");
                var messageFunction = Send.SendMessageToChannel(userChannel, replyable, context);
                var sentMessage     = await messageFunction(prefix, message);

                await Send.AddReactionToMessage(sentMessage);

                await Send.SendSentEmoteIfCommand(context);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            return;
        }