Beispiel #1
0
            public async Task ShowQuote([Remainder] string keyword)
            {
                if (string.IsNullOrWhiteSpace(keyword))
                {
                    return;
                }

                var quote = uow.Quotes.GetRandomQuoteByKeyword(Context.Guild.Id, keyword);

                if (quote != null)
                {
                    var replacer = new ReplacementBuilder().WithDefault(Context).Build();

                    if (CREmbed.TryParse(quote.Text, out var crembed))
                    {
                        replacer.Replace(crembed);
                        await Context.Channel.EmbedAsync(crembed.ToEmbedBuilder(), crembed.PlainText?.SanitizeMentions() ?? "").ConfigureAwait(false);
                    }
                    else
                    {
                        await Context.Channel.SendMessageAsync($"`#{quote.Id}` 📣 {quote.Keyword.SanitizeMentions()}: {replacer.Replace(quote.Text)?.SanitizeMentions()}").ConfigureAwait(false);
                    }
                }
                else
                {
                    await ReplyErrorLocalized("quote_not_found", keyword).ConfigureAwait(false);

                    return;
                }
            }
Beispiel #2
0
            public async Task QuoteId(int id)
            {
                if (id < 0)
                {
                    return;
                }

                using (var uow = _db.UnitOfWork)
                {
                    var qfromid = uow.Quotes.GetById(id);

                    var rep = new ReplacementBuilder()
                              .WithDefault(Context)
                              .Build();

                    var infoText = $"`#{qfromid.Id} added by {qfromid.AuthorName.SanitizeMentions()}` 🗯� " + qfromid.Keyword.ToLowerInvariant().SanitizeMentions() + ":\n";
                    if (qfromid == null)
                    {
                        await Context.Channel.SendErrorAsync(GetText("quotes_notfound")).ConfigureAwait(false);
                    }
                    else if (CREmbed.TryParse(qfromid.Text, out var crembed))
                    {
                        rep.Replace(crembed);

                        await Context.Channel.EmbedAsync(crembed.ToEmbed(), infoText + crembed.PlainText?.SanitizeMentions())
                        .ConfigureAwait(false);
                    }
                    else
                    {
                        await Context.Channel.SendMessageAsync(infoText + rep.Replace(qfromid.Text)?.SanitizeMentions())
                        .ConfigureAwait(false);
                    }
                }
            }
Beispiel #3
0
        public async Task Say(ITextChannel channel, [Leftover] string message)
        {
            if (string.IsNullOrWhiteSpace(message))
            {
                return;
            }

            var rep = new ReplacementBuilder()
                      .WithDefault(ctx.User, channel, (SocketGuild)ctx.Guild, (DiscordSocketClient)ctx.Client)
                      .Build();

            if (CREmbed.TryParse(message, out var embedData))
            {
                rep.Replace(embedData);
                await channel.EmbedAsync(embedData, sanitizeAll : !((IGuildUser)Context.User).GuildPermissions.MentionEveryone).ConfigureAwait(false);
            }
            else
            {
                var msg = rep.Replace(message);
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    await channel.SendConfirmAsync(msg).ConfigureAwait(false);
                }
            }
        }
Beispiel #4
0
            public async Task ShowQuote([Remainder] string keyword)
            {
                if (string.IsNullOrWhiteSpace(keyword))
                {
                    return;
                }

                keyword = keyword.ToUpperInvariant();

                Quote quote;

                using (var uow = DbHandler.UnitOfWork())
                {
                    quote = await uow.Quotes.GetRandomQuoteByKeywordAsync(Context.Guild.Id, keyword).ConfigureAwait(false);
                }

                if (quote == null)
                {
                    return;
                }

                CREmbed crembed;

                if (CREmbed.TryParse(quote.Text, out crembed))
                {
                    try { await Context.Channel.EmbedAsync(crembed.ToEmbed(), crembed.PlainText ?? "").ConfigureAwait(false); }
                    catch (Exception ex)
                    {
                        _log.Warn("Sending CREmbed failed");
                        _log.Warn(ex);
                    }
                    return;
                }
                await Context.Channel.SendMessageAsync("📣 " + quote.Text.SanitizeMentions());
            }
        public async Task EditMessage(ICommandContext context, ulong messageId, string text)
        {
            var msg = await context.Channel.GetMessageAsync(messageId);

            if (!(msg is IUserMessage umsg) || msg.Author.Id != context.Client.CurrentUser.Id)
            {
                return;
            }

            var rep = new ReplacementBuilder()
                      .WithDefault(context)
                      .Build();

            if (CREmbed.TryParse(text, out var crembed))
            {
                rep.Replace(crembed);
                await umsg.ModifyAsync(x =>
                {
                    x.Embed   = crembed.ToEmbed().Build();
                    x.Content = crembed.PlainText?.SanitizeMentions() ?? "";
                }).ConfigureAwait(false);
            }
            else
            {
                await umsg.ModifyAsync(x => x.Content = text.SanitizeMentions())
                .ConfigureAwait(false);
            }
        }
Beispiel #6
0
        public async Task Say(ITextChannel channel, [Leftover] string message)
        {
            if (string.IsNullOrWhiteSpace(message))
            {
                return;
            }

            var rep = new ReplacementBuilder()
                      .WithDefault(ctx.User, channel, (SocketGuild)ctx.Guild, (DiscordSocketClient)ctx.Client)
                      .Build();

            if (CREmbed.TryParse(message, out var embedData))
            {
                rep.Replace(embedData);
                try
                {
                    await channel.EmbedAsync(embedData.ToEmbed(), embedData.PlainText?.SanitizeMentions() ?? "").ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    _log.Warn(ex);
                }
            }
            else
            {
                var msg = rep.Replace(message);
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    await channel.SendConfirmAsync(msg).ConfigureAwait(false);
                }
            }
        }
        public async Task Edit(IMessageChannel channel, ulong messageId, [Remainder] string text)
        {
            if (string.IsNullOrWhiteSpace(text) || channel == null)
            {
                return;
            }

            var imsg = await channel.GetMessageAsync(messageId).ConfigureAwait(false);

            if (!(imsg is IUserMessage msg) || imsg.Author.Id != Context.Client.CurrentUser.Id)
            {
                return;
            }

            var rep = new ReplacementBuilder()
                      .WithDefault(Context)
                      .Build();

            if (CREmbed.TryParse(text, out var crembed))
            {
                rep.Replace(crembed);
                await msg.ModifyAsync(x => {
                    x.Embed   = crembed.ToEmbedBuilder().Build();
                    x.Content = crembed.PlainText?.SanitizeMentions() ?? "";
                }).ConfigureAwait(false);
            }
            else
            {
                await msg.ModifyAsync(x => x.Content = text.SanitizeMentions())
                .ConfigureAwait(false);
            }
        }
Beispiel #8
0
            private static Task UserLeft(IGuildUser user)
            {
                var _ = Task.Run(async() =>
                {
                    try
                    {
                        var conf = GetOrAddSettingsForGuild(user.GuildId);

                        if (!conf.SendChannelByeMessage)
                        {
                            return;
                        }
                        var channel = (await user.Guild.GetTextChannelsAsync()).SingleOrDefault(c => c.Id == conf.ByeMessageChannelId);

                        if (channel == null) //maybe warn the server owner that the channel is missing
                        {
                            return;
                        }
                        CREmbed embedData;
                        if (CREmbed.TryParse(conf.ChannelByeMessageText, out embedData))
                        {
                            embedData.PlainText   = embedData.PlainText?.Replace("%user%", user.Username).Replace("%id%", user.Id.ToString()).Replace("%server%", user.Guild.Name);
                            embedData.Description = embedData.Description?.Replace("%user%", user.Username).Replace("%id%", user.Id.ToString()).Replace("%server%", user.Guild.Name);
                            embedData.Title       = embedData.Title?.Replace("%user%", user.Username).Replace("%id%", user.Id.ToString()).Replace("%server%", user.Guild.Name);
                            try
                            {
                                var toDelete = await channel.EmbedAsync(embedData.ToEmbed(), embedData.PlainText ?? "").ConfigureAwait(false);
                                if (conf.AutoDeleteByeMessagesTimer > 0)
                                {
                                    toDelete.DeleteAfter(conf.AutoDeleteByeMessagesTimer);
                                }
                            }
                            catch (Exception ex) { _log.Warn(ex); }
                        }
                        else
                        {
                            var msg = conf.ChannelByeMessageText.Replace("%user%", user.Username).Replace("%id%", user.Id.ToString()).Replace("%server%", user.Guild.Name);
                            if (string.IsNullOrWhiteSpace(msg))
                            {
                                return;
                            }
                            try
                            {
                                var toDelete = await channel.SendMessageAsync(msg.SanitizeMentions()).ConfigureAwait(false);
                                if (conf.AutoDeleteByeMessagesTimer > 0)
                                {
                                    toDelete.DeleteAfter(conf.AutoDeleteByeMessagesTimer);
                                }
                            }
                            catch (Exception ex) { _log.Warn(ex); }
                        }
                    }
                    catch
                    {
                        // ignored
                    }
                });

                return(Task.CompletedTask);
            }
        public async Task EditMessage(ICommandContext context, ulong messageId, string text)
        {
            var msgs = await context.Channel.GetMessagesAsync().FlattenAsync()
                       .ConfigureAwait(false);

            IUserMessage msg = (IUserMessage)msgs.FirstOrDefault(x => x.Id == messageId &&
                                                                 x.Author.Id == context.Client.CurrentUser.Id &&
                                                                 x is IUserMessage);

            if (msg == null)
            {
                return;
            }

            var rep = new ReplacementBuilder()
                      .WithDefault(context)
                      .Build();

            if (CREmbed.TryParse(text, out var crembed))
            {
                rep.Replace(crembed);
                await msg.ModifyAsync(x =>
                {
                    x.Embed   = crembed.ToEmbed().Build();
                    x.Content = crembed.PlainText?.SanitizeMentions() ?? "";
                }).ConfigureAwait(false);
            }
            else
            {
                await msg.ModifyAsync(x => x.Content = text.SanitizeMentions())
                .ConfigureAwait(false);
            }
        }
Beispiel #10
0
        public static Task <IUserMessage> EmbedAsync(this IMessageChannel channel, CREmbed crEmbed, bool sanitizeAll = false)
        {
            var plainText = sanitizeAll
                ? crEmbed.PlainText?.SanitizeAllMentions() ?? ""
                : crEmbed.PlainText?.SanitizeMentions() ?? "";

            return(channel.SendMessageAsync(plainText, embed: crEmbed.IsEmbedValid?crEmbed.ToEmbed().Build() : null));
        }
        private async Task ByeUsers(GreetSettings conf, ITextChannel channel, IEnumerable <IUser> users)
        {
            if (!users.Any())
            {
                return;
            }

            var rep = new ReplacementBuilder()
                      .WithChannel(channel)
                      .WithClient(_client)
                      .WithServer(_client, (SocketGuild)channel.Guild)
                      .WithManyUsers(users)
                      .Build();

            if (CREmbed.TryParse(conf.ChannelByeMessageText, out var embedData))
            {
                rep.Replace(embedData);
                try
                {
                    var toDelete = await channel.EmbedAsync(embedData).ConfigureAwait(false);

                    if (conf.AutoDeleteByeMessagesTimer > 0)
                    {
                        toDelete.DeleteAfter(conf.AutoDeleteByeMessagesTimer);
                    }
                }
                catch (Exception ex)
                {
                    Log.Warning(ex, "Error embeding bye message");
                }
            }
            else
            {
                var msg = rep.Replace(conf.ChannelByeMessageText);
                if (string.IsNullOrWhiteSpace(msg))
                {
                    return;
                }
                try
                {
                    var toDelete = await channel.SendMessageAsync(msg.SanitizeMentions()).ConfigureAwait(false);

                    if (conf.AutoDeleteByeMessagesTimer > 0)
                    {
                        toDelete.DeleteAfter(conf.AutoDeleteByeMessagesTimer);
                    }
                }
                catch (Exception ex)
                {
                    Log.Warning(ex, "Error sending bye message");
                }
            }
        }
Beispiel #12
0
        public static async Task <IUserMessage> Send(this CustomReaction cr, IUserMessage context)
        {
            var channel = cr.DmResponse ? await context.Author.CreateDMChannelAsync() : context.Channel;

            CustomReactions.ReactionStats.AddOrUpdate(cr.Trigger, 1, (k, old) => ++ old);

            CREmbed crembed;

            if (CREmbed.TryParse(cr.Response, out crembed))
            {
                return(await channel.EmbedAsync(crembed.ToEmbed(), crembed.PlainText ?? ""));
            }
            return(await channel.SendMessageAsync(cr.ResponseWithContext(context).SanitizeMentions()));
        }
Beispiel #13
0
            public async Task QuoteId(int id)
            {
                if (id < 0)
                {
                    return;
                }

                Quote quote;

                var rep = new ReplacementBuilder()
                          .WithDefault(Context)
                          .Build();

                using (var uow = _db.GetDbContext())
                {
                    quote = uow.Quotes.GetById(id);
                    if (quote.GuildId != ctx.Guild.Id)
                    {
                        quote = null;
                    }
                }

                if (quote == null)
                {
                    await ctx.Channel.SendErrorAsync(GetText("quotes_notfound")).ConfigureAwait(false);

                    return;
                }

                var infoText = $"`#{quote.Id} added by {quote.AuthorName.SanitizeAllMentions()}` 🗯� " + quote.Keyword.ToLowerInvariant().SanitizeAllMentions() + ":\n";

                if (CREmbed.TryParse(quote.Text, out var crembed))
                {
                    rep.Replace(crembed);

                    await ctx.Channel.EmbedAsync(crembed.ToEmbed(), infoText + crembed.PlainText?.SanitizeAllMentions())
                    .ConfigureAwait(false);
                }
                else
                {
                    await ctx.Channel.SendMessageAsync(infoText + rep.Replace(quote.Text)?.SanitizeAllMentions())
                    .ConfigureAwait(false);
                }
            }
Beispiel #14
0
        public EmbedBuilder GetHelpStringEmbed()
        {
            var r = new ReplacementBuilder()
                    .WithDefault(Context)
                    .WithOverride("{0}", () => _creds.ClientId.ToString())
                    .WithOverride("{1}", () => Prefix)
                    .Build();


            if (!CREmbed.TryParse(_bc.BotConfig.HelpString, out var embed))
            {
                return(new EmbedBuilder().WithOkColor()
                       .WithDescription(String.Format(_bc.BotConfig.HelpString, _creds.ClientId, Prefix)));
            }

            r.Replace(embed);

            return(embed.ToEmbed());
        }
        private async Task SendGreetMessage(IGuild guild, IUser user, IMessageChannel channel, string messageText, int autoDeleteTimer)
        {
            if (channel != null)
            {
                var rep = new ReplacementBuilder()
                          .WithDefault(user, channel, guild, _client)
                          .Build();

                if (CREmbed.TryParse(messageText, out var embedData))
                {
                    rep.Replace(embedData);
                    try {
                        var toDelete = await channel.EmbedAsync(embedData.ToEmbedBuilder(), embedData.PlainText?.SanitizeMentions() ?? "").ConfigureAwait(false);

                        if (autoDeleteTimer > 0)
                        {
                            toDelete.DeleteAfter(autoDeleteTimer);
                        }
                    } catch (Exception ex) {
                        _log.Warn(ex);
                    }
                }
                else
                {
                    var msg = rep.Replace(messageText);

                    if (!string.IsNullOrWhiteSpace(msg))
                    {
                        try {
                            var toDelete = await channel.SendMessageAsync(msg.SanitizeMentions()).ConfigureAwait(false);

                            if (autoDeleteTimer > 0)
                            {
                                toDelete.DeleteAfter(autoDeleteTimer);
                            }
                        } catch (Exception ex) {
                            _log.Warn(ex);
                        }
                    }
                }
            }
        }
Beispiel #16
0
            public async Task QuoteId(ushort id)
            {
                var quote = uow.Quotes.Get(id);

                var replacer = new ReplacementBuilder().WithDefault(Context).Build();

                if (quote == null)
                {
                    await Context.Channel.SendErrorAsync(GetText("quotes_notfound", id));
                }
                else if (CREmbed.TryParse(quote.Text, out var crembed))
                {
                    replacer.Replace(crembed);
                    await Context.Channel.EmbedAsync(crembed.ToEmbedBuilder(), crembed.PlainText?.SanitizeMentions() ?? "").ConfigureAwait(false);
                }
                else
                {
                    await Context.Channel.SendMessageAsync($"`#{quote.Id}` 🗯️ {quote.Keyword.ToLowerInvariant().SanitizeMentions()}:  {replacer.Replace(quote.Text)?.SanitizeMentions()}").ConfigureAwait(false);
                }
            }
Beispiel #17
0
        public Task LateExecute(DiscordSocketClient client, IGuild guild, IUserMessage msg)
        {
            try
            {
                if (guild == null)
                {
                    if (CREmbed.TryParse(_bc.BotConfig.DMHelpString, out var embed))
                    {
                        return(msg.Channel.EmbedAsync(embed.ToEmbed(), embed.PlainText?.SanitizeMentions() ?? ""));
                    }

                    return(msg.Channel.SendMessageAsync(_bc.BotConfig.DMHelpString));
                }
            }
            catch (Exception ex)
            {
                _log.Warn(ex);
            }
            return(Task.CompletedTask);
        }
Beispiel #18
0
        public Task LateExecute(DiscordSocketClient client, IGuild guild, IUserMessage msg)
        {
            var settings = _bss.Data;

            if (guild == null)
            {
                if (string.IsNullOrWhiteSpace(settings.DmHelpText) || settings.DmHelpText == "-")
                {
                    return(Task.CompletedTask);
                }

                if (CREmbed.TryParse(settings.DmHelpText, out var embed))
                {
                    return(msg.Channel.EmbedAsync(_rep.Replace(embed)));
                }

                return(msg.Channel.SendMessageAsync(_rep.Replace(settings.DmHelpText)));
            }
            return(Task.CompletedTask);
        }
Beispiel #19
0
            public async Task ShowQuote([Remainder] string keyword)
            {
                if (string.IsNullOrWhiteSpace(keyword))
                {
                    return;
                }

                keyword = keyword.ToUpperInvariant();

                Quote quote;

                using (var uow = _db.UnitOfWork)
                {
                    quote = await uow.Quotes.GetRandomQuoteByKeywordAsync(Context.Guild.Id, keyword);

                    //if (quote != null)
                    //{
                    //    quote.UseCount += 1;
                    //    uow.Complete();
                    //}
                }

                if (quote == null)
                {
                    return;
                }

                var rep = new ReplacementBuilder()
                          .WithDefault(Context)
                          .Build();

                if (CREmbed.TryParse(quote.Text, out var crembed))
                {
                    rep.Replace(crembed);
                    await Context.Channel.EmbedAsync(crembed.ToEmbed(), $"`#{quote.Id}` 📣 " + crembed.PlainText?.SanitizeMentions() ?? "")
                    .ConfigureAwait(false);

                    return;
                }
                await Context.Channel.SendMessageAsync($"`#{quote.Id}` 📣 " + rep.Replace(quote.Text)?.SanitizeMentions()).ConfigureAwait(false);
            }
Beispiel #20
0
        public static async Task <IUserMessage> Send(this CustomReaction cr, IUserMessage ctx, DiscordSocketClient client, bool sanitize)
        {
            var channel = cr.DmResponse ? await ctx.Author.GetOrCreateDMChannelAsync().ConfigureAwait(false) : ctx.Channel;

            if (CREmbed.TryParse(cr.Response, out CREmbed crembed))
            {
                var trigger        = cr.Trigger.ResolveTriggerString(ctx, client);
                var substringIndex = trigger.Length;
                if (cr.ContainsAnywhere)
                {
                    var pos = ctx.Content.AsSpan().GetWordPosition(trigger);
                    if (pos == WordPosition.Start)
                    {
                        substringIndex += 1;
                    }
                    else if (pos == WordPosition.End)
                    {
                        substringIndex = ctx.Content.Length;
                    }
                    else if (pos == WordPosition.Middle)
                    {
                        substringIndex += ctx.Content.IndexOf(trigger, StringComparison.InvariantCulture);
                    }
                }

                var canMentionEveryone = (ctx.Author as IGuildUser)?.GuildPermissions.MentionEveryone ?? true;

                var rep = new ReplacementBuilder()
                          .WithDefault(ctx.Author, ctx.Channel, (ctx.Channel as ITextChannel)?.Guild as SocketGuild, client)
                          .WithOverride("%target%", () => canMentionEveryone
                        ? ctx.Content.Substring(substringIndex).Trim()
                        : ctx.Content.Substring(substringIndex).Trim().SanitizeMentions(true))
                          .Build();

                rep.Replace(crembed);

                return(await channel.EmbedAsync(crembed, sanitize).ConfigureAwait(false));
            }
            return(await channel.SendMessageAsync((await cr.ResponseWithContextAsync(ctx, client, cr.ContainsAnywhere).ConfigureAwait(false)).SanitizeMentions(sanitize)).ConfigureAwait(false));
        }
        public static async Task <IUserMessage> Send(this CustomReaction cr, IUserMessage ctx, DiscordSocketClient client, CustomReactionsService crs)
        {
            var channel = cr.DmResponse ? await ctx.Author.CreateDMChannelAsync() : ctx.Channel;

            crs.ReactionStats.AddOrUpdate(cr.Trigger, 1, (k, old) => ++ old);

            if (!CREmbed.TryParse(cr.Response, out var crembed))
            {
                return(await channel.SendMessageAsync(cr.ResponseWithContext(ctx, client, cr.ContainsAnywhere).SanitizeMentions()));
            }
            var trigger        = cr.ResolveTriggerString(ctx, client);
            var substringIndex = trigger.Length;

            if (cr.ContainsAnywhere)
            {
                var pos = ctx.Content.GetWordPosition(trigger);
                if (pos == WordPosition.Start)
                {
                    substringIndex += 1;
                }
                else if (pos == WordPosition.End)
                {
                    substringIndex = ctx.Content.Length;
                }
                else if (pos == WordPosition.Middle)
                {
                    substringIndex += ctx.Content.IndexOf(trigger, StringComparison.Ordinal);
                }
            }

            var rep = new ReplacementBuilder()
                      .WithDefault(ctx.Author, ctx.Channel, (ctx.Channel as ITextChannel)?.Guild, client)
                      .WithOverride("%target%", () => ctx.Content.Substring(substringIndex).Trim())
                      .Build();

            rep.Replace(crembed);

            return(await channel.EmbedAsync(crembed.ToEmbedBuilder(), crembed.PlainText?.SanitizeMentions() ?? ""));
        }
Beispiel #22
0
        public async Task <(string plainText, EmbedBuilder embed)> GetHelpStringEmbed()
        {
            var clientId = await _lazyClientId.Value;
            var r        = new ReplacementBuilder()
                           .WithDefault(Context)
                           .WithOverride("{0}", () => clientId.ToString())
                           .WithOverride("{1}", () => Prefix)
                           .Build();

            var app = await _client.GetApplicationInfoAsync();


            if (!CREmbed.TryParse(Bc.BotConfig.HelpString, out var embed))
            {
                return("", new EmbedBuilder().WithOkColor()
                       .WithDescription(String.Format(Bc.BotConfig.HelpString, clientId, Prefix)));
            }

            r.Replace(embed);

            return(embed.PlainText, embed.ToEmbed());
        }
Beispiel #23
0
            public async Task QuoteId(int id)
            {
                if (id < 0)
                {
                    return;
                }

                using (var uow = DbHandler.UnitOfWork())
                {
                    var     qfromid = uow.Quotes.Get(id);
                    CREmbed crembed;

                    if (qfromid == null)
                    {
                        await Context.Channel.SendErrorAsync(GetText("quotes_notfound"));
                    }
                    else if (CREmbed.TryParse(qfromid.Text, out crembed))
                    {
                        try
                        {
                            await Context.Channel.EmbedAsync(crembed.ToEmbed(), crembed.PlainText ?? "")
                            .ConfigureAwait(false);
                        }
                        catch (Exception ex)
                        {
                            _log.Warn("Sending CREmbed failed");
                            _log.Warn(ex);
                        }
                        return;
                    }

                    else
                    {
                        await Context.Channel.SendMessageAsync($"`#{qfromid.Id}` 🗯️ " + qfromid.Keyword.ToLowerInvariant().SanitizeMentions() + ":  " +
                                                               qfromid.Text.SanitizeMentions());
                    }
                }
            }
Beispiel #24
0
        public async Task Say([Remainder] string message)
        {
            Context.Message.DeleteAfter(0);

            await Context.Channel.TriggerTypingAsync().ConfigureAwait(false);

            await Task.Delay(1000).ConfigureAwait(false);

            if (string.IsNullOrWhiteSpace(message))
            {
                return;
            }

            var rep = new ReplacementBuilder()
                      .WithDefault(Context.User, Context.Channel, (SocketGuild)Context.Guild, (DiscordSocketClient)Context.Client)
                      .Build();

            if (CREmbed.TryParse(message, out var embedData))
            {
                rep.Replace(embedData);
                try
                {
                    await Context.Channel.EmbedAsync(embedData.ToEmbed(), embedData.PlainText?.SanitizeMentions() ?? "").ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    _log.Warn(ex);
                }
            }
            else
            {
                var msg = rep.Replace(message);
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    await Context.Channel.SendConfirmAsync(msg).ConfigureAwait(false);
                }
            }
        }
        private async Task <bool> GreetDmUser(GreetSettings conf, IDMChannel channel, IGuildUser user)
        {
            var rep = new ReplacementBuilder()
                      .WithDefault(user, channel, (SocketGuild)user.Guild, _client)
                      .Build();

            if (CREmbed.TryParse(conf.DmGreetMessageText, out var embedData))
            {
                rep.Replace(embedData);
                try
                {
                    await channel.EmbedAsync(embedData).ConfigureAwait(false);
                }
                catch
                {
                    return(false);
                }
            }
            else
            {
                var msg = rep.Replace(conf.DmGreetMessageText);
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    try
                    {
                        await channel.SendConfirmAsync(msg).ConfigureAwait(false);
                    }
                    catch
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
            public async Task Send(string where, [Remainder] string msg = "")
            {
                if (string.IsNullOrWhiteSpace(msg))
                {
                    return;
                }

                var destinationMatch = Regex.Match(where, "\\A(?<serverId>\\d+)\\|(?<channelOrUser>c|u):(?<channelOrUserId>\\d+)\\z", RegexOptions.IgnoreCase);

                if (destinationMatch.Success && ulong.TryParse(destinationMatch.Groups["serverId"].Value, out var destinationServerId) && ulong.TryParse(destinationMatch.Groups["channelOrUserId"].Value, out var destinationChannelOrUserId))
                {
                    var channelOrUser = destinationMatch.Groups["channelOrUser"].Value;

                    var guild = _client.Guilds.FirstOrDefault(g => g.Id == destinationServerId);

                    if (guild != null)
                    {
                        var rep = new ReplacementBuilder().WithDefault(Context).Build();

                        if (channelOrUser.Equals("c", StringComparison.OrdinalIgnoreCase))
                        {
                            var channel = guild.TextChannels.FirstOrDefault(c => c.Id == destinationChannelOrUserId);

                            if (channel != null)
                            {
                                if (CREmbed.TryParse(msg, out var crembed))
                                {
                                    rep.Replace(crembed);
                                    await channel.EmbedAsync(crembed.ToEmbedBuilder(), crembed.PlainText?.SanitizeMentions() ?? "").ConfigureAwait(false);
                                }
                                else
                                {
                                    await channel.SendMessageAsync($"{rep.Replace(msg)?.SanitizeMentions() ?? ""}");
                                }

                                await ReplyConfirmLocalized("message_sent").ConfigureAwait(false);
                            }
                        }
                        else if (channelOrUser.Equals("u", StringComparison.OrdinalIgnoreCase))
                        {
                            var user = guild.Users.FirstOrDefault(u => u.Id == destinationChannelOrUserId);

                            if (user != null)
                            {
                                if (CREmbed.TryParse(msg, out var crembed))
                                {
                                    rep.Replace(crembed);
                                    await(await user.CreateDMChannelAsync()).EmbedAsync(crembed.ToEmbedBuilder(), crembed.PlainText?.SanitizeMentions() ?? "").ConfigureAwait(false);
                                }
                                else
                                {
                                    await(await user.CreateDMChannelAsync()).SendMessageAsync($"`#{msg}` {rep.Replace(msg)?.SanitizeMentions() ?? ""}");
                                }

                                await ReplyConfirmLocalized("message_sent").ConfigureAwait(false);
                            }
                        }
                    }
                }
                else
                {
                    await ReplyErrorLocalized("invalid_format").ConfigureAwait(false);
                }
            }
Beispiel #27
0
            public async Task Send(string where, [Remainder] string msg = null)
            {
                if (string.IsNullOrWhiteSpace(msg))
                {
                    return;
                }

                var ids = where.Split('|');

                if (ids.Length != 2)
                {
                    return;
                }
                var sid    = ulong.Parse(ids[0]);
                var server = _client.Guilds.FirstOrDefault(s => s.Id == sid);

                if (server == null)
                {
                    return;
                }

                var rep = new ReplacementBuilder()
                          .WithDefault(Context)
                          .Build();

                if (ids[1].ToUpperInvariant().StartsWith("C:", StringComparison.InvariantCulture))
                {
                    var cid = ulong.Parse(ids[1].Substring(2));
                    var ch  = server.TextChannels.FirstOrDefault(c => c.Id == cid);
                    if (ch == null)
                    {
                        return;
                    }

                    if (CREmbed.TryParse(msg, out var crembed))
                    {
                        rep.Replace(crembed);
                        await ch.EmbedAsync(crembed.ToEmbed(), crembed.PlainText?.SanitizeMentions() ?? "")
                        .ConfigureAwait(false);
                        await ReplyConfirmLocalized("message_sent").ConfigureAwait(false);

                        return;
                    }
                    await ch.SendMessageAsync(rep.Replace(msg).SanitizeMentions()).ConfigureAwait(false);
                }
                else if (ids[1].ToUpperInvariant().StartsWith("U:", StringComparison.InvariantCulture))
                {
                    var uid  = ulong.Parse(ids[1].Substring(2));
                    var user = server.Users.FirstOrDefault(u => u.Id == uid);
                    if (user == null)
                    {
                        return;
                    }

                    if (CREmbed.TryParse(msg, out var crembed))
                    {
                        rep.Replace(crembed);
                        await(await user.GetOrCreateDMChannelAsync().ConfigureAwait(false)).EmbedAsync(crembed.ToEmbed(), crembed.PlainText?.SanitizeMentions() ?? "")
                        .ConfigureAwait(false);
                        await ReplyConfirmLocalized("message_sent").ConfigureAwait(false);

                        return;
                    }

                    await(await user.GetOrCreateDMChannelAsync().ConfigureAwait(false)).SendMessageAsync(rep.Replace(msg).SanitizeMentions()).ConfigureAwait(false);
                }
                else
                {
                    await ReplyErrorLocalized("invalid_format").ConfigureAwait(false);

                    return;
                }
                await ReplyConfirmLocalized("message_sent").ConfigureAwait(false);
            }
        private Task UserLeft(IGuildUser user)
        {
            var _ = Task.Run(async() =>
            {
                try
                {
                    var conf = GetOrAddSettingsForGuild(user.GuildId);

                    if (!conf.SendChannelByeMessage)
                    {
                        return;
                    }
                    var channel = (await user.Guild.GetTextChannelsAsync().ConfigureAwait(false)).SingleOrDefault(c => c.Id == conf.ByeMessageChannelId);

                    if (channel == null) //maybe warn the server owner that the channel is missing
                    {
                        return;
                    }

                    var rep = new ReplacementBuilder()
                              .WithDefault(user, channel, (SocketGuild)user.Guild, _client)
                              .Build();

                    if (CREmbed.TryParse(conf.ChannelByeMessageText, out var embedData))
                    {
                        rep.Replace(embedData);
                        try
                        {
                            var toDelete = await channel.EmbedAsync(embedData.ToEmbed(), embedData.PlainText?.SanitizeMentions() ?? "").ConfigureAwait(false);
                            if (conf.AutoDeleteByeMessagesTimer > 0)
                            {
                                toDelete.DeleteAfter(conf.AutoDeleteByeMessagesTimer);
                            }
                        }
                        catch (Exception ex) { _log.Warn(ex); }
                    }
                    else
                    {
                        var msg = rep.Replace(conf.ChannelByeMessageText);
                        if (string.IsNullOrWhiteSpace(msg))
                        {
                            return;
                        }
                        try
                        {
                            var toDelete = await channel.SendMessageAsync(msg.SanitizeMentions()).ConfigureAwait(false);
                            if (conf.AutoDeleteByeMessagesTimer > 0)
                            {
                                toDelete.DeleteAfter(conf.AutoDeleteByeMessagesTimer);
                            }
                        }
                        catch (Exception ex) { _log.Warn(ex); }
                    }
                }
                catch
                {
                    // ignored
                }
            });

            return(Task.CompletedTask);
        }
Beispiel #29
0
        private async Task Trigger(RunningRepeater rr)
        {
            var repeater = rr.Repeater;

            void ChannelMissingError()
            {
                rr.ErrorCount = Int32.MaxValue;
                Log.Warning("[Repeater] Channel [{Channelid}] for not found or insufficient permissions. " +
                            "Repeater will be removed. ", repeater.ChannelId);
            }

            var channel = _client.GetChannel(repeater.ChannelId) as ITextChannel;

            if (channel is null)
            {
                channel = await _client.Rest.GetChannelAsync(repeater.ChannelId) as ITextChannel;
            }

            if (channel is null)
            {
                ChannelMissingError();
                return;
            }

            var guild = _client.GetGuild(channel.GuildId);

            if (guild is null)
            {
                ChannelMissingError();
                return;
            }

            if (_noRedundant.Contains(repeater.Id))
            {
                try
                {
                    var lastMsgInChannel = await channel.GetMessagesAsync(2).Flatten().FirstAsync();

                    if (lastMsgInChannel != null && lastMsgInChannel.Id == repeater.LastMessageId)
                    {
                        return;
                    }
                }
                catch (Exception ex)
                {
                    Log.Warning(ex,
                                "[Repeater] Error while getting last channel message in {GuildId}/{ChannelId} " +
                                "Bot probably doesn't have the permission to read message history",
                                guild.Id,
                                channel.Id);
                }
            }

            if (repeater.LastMessageId is ulong lastMessageId)
            {
                try
                {
                    var oldMsg = await channel.GetMessageAsync(lastMessageId);

                    if (oldMsg != null)
                    {
                        await oldMsg.DeleteAsync().ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    Log.Warning(ex, "[Repeater] Error while deleting previous message in {GuildId}/{ChannelId}", guild.Id, channel.Id);
                }
            }

            var rep = new ReplacementBuilder()
                      .WithDefault(guild.CurrentUser, channel, guild, _client)
                      .Build();

            try
            {
                IMessage newMsg;
                if (CREmbed.TryParse(repeater.Message, out var crEmbed))
                {
                    rep.Replace(crEmbed);
                    newMsg = await channel.EmbedAsync(crEmbed);
                }
                else
                {
                    newMsg = await channel.SendMessageAsync(rep.Replace(repeater.Message));
                }

                _ = newMsg.AddReactionAsync(new Emoji("🔄"));
                if (_noRedundant.Contains(repeater.Id))
                {
                    await SetRepeaterLastMessageInternal(repeater.Id, newMsg.Id);

                    repeater.LastMessageId = newMsg.Id;
                }

                rr.ErrorCount = 0;
            }
            catch (Exception ex)
            {
                Log.Error(ex, "[Repeater] Error sending repeat message ({ErrorCount})", rr.ErrorCount++);
            }
        }
Beispiel #30
0
        public static async Task <bool> TryExecuteCustomReaction(SocketUserMessage umsg)
        {
            var channel = umsg.Channel as SocketTextChannel;

            if (channel == null)
            {
                return(false);
            }

            var content = umsg.Content.Trim().ToLowerInvariant();

            CustomReaction[] reactions;

            GuildReactions.TryGetValue(channel.Guild.Id, out reactions);
            if (reactions != null && reactions.Any())
            {
                var rs = reactions.Where(cr =>
                {
                    if (cr == null)
                    {
                        return(false);
                    }

                    var hasTarget = cr.Response.ToLowerInvariant().Contains("%target%");
                    var trigger   = cr.TriggerWithContext(umsg).Trim().ToLowerInvariant();
                    return((hasTarget && content.StartsWith(trigger + " ")) || content == trigger);
                }).ToArray();

                if (rs.Length != 0)
                {
                    var reaction = rs[new NadekoRandom().Next(0, rs.Length)];
                    if (reaction != null)
                    {
                        if (reaction.Response != "-")
                        {
                            CREmbed crembed;
                            if (CREmbed.TryParse(reaction.Response, out crembed))
                            {
                                try { await channel.EmbedAsync(crembed.ToEmbed(), crembed.PlainText ?? "").ConfigureAwait(false); }
                                catch (Exception ex)
                                {
                                    _log.Warn("Sending CREmbed failed");
                                    _log.Warn(ex);
                                }
                            }
                            else
                            {
                                try { await channel.SendMessageAsync(reaction.ResponseWithContext(umsg)).ConfigureAwait(false); } catch { }
                            }
                        }

                        ReactionStats.AddOrUpdate(reaction.Trigger, 1, (k, old) => ++ old);
                        return(true);
                    }
                }
            }

            var grs = GlobalReactions.Where(cr =>
            {
                if (cr == null)
                {
                    return(false);
                }
                var hasTarget = cr.Response.ToLowerInvariant().Contains("%target%");
                var trigger   = cr.TriggerWithContext(umsg).Trim().ToLowerInvariant();
                return((hasTarget && content.StartsWith(trigger + " ")) || content == trigger);
            }).ToArray();

            if (grs.Length == 0)
            {
                return(false);
            }
            var greaction = grs[new NadekoRandom().Next(0, grs.Length)];

            if (greaction != null)
            {
                CREmbed crembed;
                if (CREmbed.TryParse(greaction.Response, out crembed))
                {
                    try { await channel.EmbedAsync(crembed.ToEmbed(), crembed.PlainText ?? "").ConfigureAwait(false); }
                    catch (Exception ex)
                    {
                        _log.Warn("Sending CREmbed failed");
                        _log.Warn(ex);
                    }
                }
                else
                {
                    try { await channel.SendMessageAsync(greaction.ResponseWithContext(umsg)).ConfigureAwait(false); } catch { }
                }
                ReactionStats.AddOrUpdate(greaction.Trigger, 1, (k, old) => ++ old);
                return(true);
            }
            return(false);
        }