public ReplacementBuilderAndSugarEstimatorFacadeImpl(PatternBuilder patternBuilder, ReplacementBuilder replacementBuilder, SugarEstimator sugarEstimator) { this.patternBuilder = patternBuilder; this.replacementBuilder = replacementBuilder; this.sugarEstimator = sugarEstimator; }
public async Task SetGame(ActivityType type, [Remainder] string game = null) { var rep = new ReplacementBuilder() .WithDefault(Context) .Build(); await _bot.SetGameAsync(game == null?game : rep.Replace(game), type).ConfigureAwait(false); await ReplyConfirmLocalized("set_game").ConfigureAwait(false); }
private static string ResolveTriggerString(this string str, IUserMessage ctx, DiscordSocketClient client) { var rep = new ReplacementBuilder() .WithUser(ctx.Author) .WithMention(client) .Build(); str = rep.Replace(str.ToLowerInvariant()); return(str); }
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"); } } }
public async Task StartReminder(Reminder r) { var t = cancelAllToken; var now = DateTime.UtcNow; var time = r.When - now; if (time.TotalMilliseconds > int.MaxValue) { return; } await Task.Delay(time, t).ConfigureAwait(false); try { IMessageChannel ch; if (r.IsPrivate) { var user = _client.GetGuild(r.ServerId).GetUser(r.ChannelId); if (user == null) { return; } ch = await user.GetOrCreateDMChannelAsync().ConfigureAwait(false); } else { ch = _client.GetGuild(r.ServerId)?.GetTextChannel(r.ChannelId); } if (ch == null) { return; } var rep = new ReplacementBuilder() .WithOverride("%user%", () => $"<@!{r.UserId}>") .WithOverride("%message%", () => r.Message) .WithOverride("%target%", () => r.IsPrivate ? "Direct Message" : $"<#{r.ChannelId}>") .Build(); await ch.SendMessageAsync(rep.Replace(RemindMessageFormat).SanitizeMentions()).ConfigureAwait(false); //it works trust me } catch (Exception ex) { _log.Warn(ex); } finally { using (var uow = _db.UnitOfWork) { uow.Reminders.Remove(r); await uow.CompleteAsync(); } } }
public async Task QuoteId(int id) { if (id < 0) { return; } Quote quote; var rep = new ReplacementBuilder() .WithDefault(Context) .Build(); using (var uow = _db.UnitOfWork) { quote = uow.Quotes.GetById(id); if (quote.GuildId != Context.Guild.Id) { quote = null; } } if (quote == null) { await Context.Channel.SendErrorAsync(GetText("quotes_notfound")).ConfigureAwait(false); return; } var infoText = $"`#{quote.Id} added by {quote.AuthorName.SanitizeMentions()}` 🗯� " + quote.Keyword.ToLowerInvariant().SanitizeMentions() + ":\n"; if (CREmbed.TryParse(quote.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(quote.Text)?.SanitizeMentions()) .ConfigureAwait(false); } }
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); } } } } }
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); } }
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); }
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)); }
private static async Task <string> ResolveResponseStringAsync(this string str, IUserMessage ctx, DiscordSocketClient client, string resolvedTrigger, bool containsAnywhere) { var substringIndex = resolvedTrigger.Length; if (containsAnywhere) { var pos = ctx.Content.AsSpan().GetWordPosition(resolvedTrigger); if (pos == WordPosition.Start) { substringIndex += 1; } else if (pos == WordPosition.End) { substringIndex = ctx.Content.Length; } else if (pos == WordPosition.Middle) { substringIndex += ctx.Content.IndexOf(resolvedTrigger, 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(); str = rep.Replace(str); #if !GLOBAL_NADEKO foreach (var ph in regexPlaceholders) { str = await ph.Key.ReplaceAsync(str, ph.Value).ConfigureAwait(false); } #endif return(str); }
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() ?? "")); }
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()); }
public async Task Edit(ulong messageId, [Remainder] string text) { if (string.IsNullOrWhiteSpace(text)) { return; } 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); } }
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); } }
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); }
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++); } }