コード例 #1
0
ファイル: MessageModule.cs プロジェクト: Nexowned/Freud2.0
        public async Task FlagMessageAsync(CommandContext ctx,
                                           [Description("Message.")] DiscordMessage msg        = null,
                                           [Description("Voting timespan.")] TimeSpan?timespan = null)
        {
            msg = msg ?? (await ctx.Channel.GetMessagesBeforeAsync(ctx.Channel.LastMessageId, 1))?.FirstOrDefault();

            if (msg is null)
            {
                throw new CommandFailedException("Cannot retrieve the message!");
            }

            if (timespan?.TotalSeconds < 5 || timespan?.TotalMinutes > 5)
            {
                throw new InvalidCommandUsageException("Timespan cannot be greater than 5 minutes or lower than 5 seconds.");
            }

            IEnumerable <PollEmoji> res = await msg.DoPollAsync(new[] { StaticDiscordEmoji.ArrowUp, StaticDiscordEmoji.ArrowDown }, PollBehaviour.Default, timeout : timespan ?? TimeSpan.FromMinutes(1));

            var votes = res.ToDictionary(pe => pe.Emoji, pe => pe.Voted.Count);

            if (votes.GetValueOrDefault(StaticDiscordEmoji.ArrowDown) > 2 * votes.GetValueOrDefault(StaticDiscordEmoji.ArrowUp))
            {
                string sanitized = FormatterExtensions.Spoiler(FormatterExtensions.StripMarkdown(msg.Content));
                await msg.DeleteAsync();

                await ctx.RespondAsync($"{msg.Author.Mention} said: {sanitized}");
            }
            else
            {
                await this.InformOfFailureAsync(ctx, "Not enough downvotes required for deletion.");
            }
        }
コード例 #2
0
        private void RegisterType <T>()
            where T : class
        {
            var className = typeof(T).Name;

            this.Get(className, _ =>
            {
                var context = this.persistenceContextProvider.CreateNewContext();
                var allData = context.Get <T>();
                var list    = JsonConvert.SerializeObject(
                    allData,
                    Formatting.None,
                    new JsonSerializerSettings {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                });

                return(list);
            });
            this.Get(className + "/{id:guid}", _ => FormatterExtensions.AsJson <T>(this.Response, this.GetById <T>((Guid)_.id)));
            this.Get(className + "/enums", _ => this.GetEnums <T>());
            this.Post(className, _ => this.Save <T>());
            this.Post(className + "/all", _ => this.SaveAll <T>());
            this.Delete(className, _ => this.DeleteItem(this.Bind <T>()));
            this.Delete(className + "/{id:guid}", _ => this.DeleteItemById <T>((Guid)_.id));

            this.registeredRepositoryTypes.Add(className);
        }
コード例 #3
0
 public SmartFormatterLiteralCharacterExtractor(SmartFormatter parent)
 {
     Settings = parent.Settings;
     Parser   = parent.Parser;
     SourceExtensions.AddRange(parent.SourceExtensions);
     FormatterExtensions.AddRange(parent.FormatterExtensions);
 }
コード例 #4
0
        public static async Task MessageFilterEventHandlerAsync(FreudShard shard, MessageCreateEventArgs e)
        {
            if (e.Author.IsBot || e.Channel.IsPrivate || string.IsNullOrWhiteSpace(e.Message?.Content))
            {
                return;
            }
            if (shard.SharedData.BlockedChannels.Contains(e.Channel.Id))
            {
                return;
            }

            var gcfg = shard.SharedData.GetGuildConfiguration(e.Guild.Id);

            if (gcfg.LinkfilterSettings.Enabled)
            {
                if (await shard.CNext.Services.GetService <LinkfilterService>().HandleNewMessageAsync(e, gcfg.LinkfilterSettings))
                {
                    return;
                }
            }

            if (!shard.SharedData.MessageContainsFilter(e.Guild.Id, e.Message.Content))
            {
                return;
            }
            if (!e.Channel.PermissionsFor(e.Guild.CurrentMember).HasFlag(Permissions.ManageMessages))
            {
                return;
            }

            await e.Message.DeleteAsync("bot: Filter hit");

            await e.Channel.SendMessageAsync($"{e.Author.Mention} said: {FormatterExtensions.Spoiler(Formatter.BlockCode(FormatterExtensions.StripMarkdown(e.Message.Content)))}");
        }
コード例 #5
0
        public static async Task MessageUpdateEventHandlerAsync(FreudShard shard, MessageUpdateEventArgs e)
        {
            if (e.Author is null || e.Author.IsBot || e.Channel is null || e.Channel.IsPrivate || e.Message is null)
            {
                return;
            }
            if (shard.SharedData.BlockedChannels.Contains(e.Channel.Id))
            {
                return;
            }
            if (e.Message.Author == e.Client.CurrentUser && shard.SharedData.IsEventRunningInChannel(e.Channel.Id))
            {
                return;
            }
            if (!(e.Message.Content is null) && shard.SharedData.MessageContainsFilter(e.Guild.Id, e.Message.Content))
            {
                try
                {
                    await e.Message.DeleteAsync("bot: Filter hit after update");

                    await e.Channel.SendMessageAsync($"{e.Author.Mention} said: {FormatterExtensions.Spoiler(Formatter.BlockCode(FormatterExtensions.StripMarkdown(e.Message.Content)))}");
                } catch
                {
                    // swallow
                }
            }

            var logchn = shard.SharedData.GetLogChannelForGuild(shard.Client, e.Guild);

            if (logchn is null || !e.Message.IsEdited || e.Channel.IsExempted(shard))
            {
                return;
            }

            var member = await e.Guild.GetMemberAsync(e.Author.Id);

            if (member.IsExempted(shard))
            {
                return;
            }

            string pcontent = string.IsNullOrWhiteSpace(e.MessageBefore?.Content) ? "" : e.MessageBefore.Content.Truncate(700);
            string acontent = string.IsNullOrWhiteSpace(e.Message?.Content) ? "" : e.Message.Content.Truncate(700);
            string ctime    = e.Message.CreationTimestamp == null ? _unknown : e.Message.CreationTimestamp.ToUtcTimestamp();
            string etime    = e.Message.EditedTimestamp is null ? _unknown : e.Message.EditedTimestamp.Value.ToUtcTimestamp();
            string bextra   = $"Embeds: {e.MessageBefore?.Embeds?.Count ?? 0}, Reactions: {e.MessageBefore?.Reactions?.Count ?? 0}, Attachments: {e.MessageBefore.Attachments?.Count ?? 0}";
            string aextra   = $"Embeds: {e.Message.Embeds.Count}, Reactions: {e.Message.Reactions.Count}, Attachments: {e.Message.Attachments.Count}";

            var emb = FormEmbedBuilder(EventOrigin.Message, "Message updated");

            emb.WithDescription(Formatter.MaskedUrl("Jump to message", e.Message.JumpLink));
            emb.AddField("Location", e.Channel.Mention, inline: true);
            emb.AddField("Author", e.Message.Author?.Mention ?? _unknown, inline: true);
            emb.AddField("Before update", $"Created {ctime}\n{bextra}\nContent:{Formatter.BlockCode(FormatterExtensions.StripMarkdown(pcontent))}");
            emb.AddField("After update", $"Edited {etime}\n{aextra}\nContent:{Formatter.BlockCode(FormatterExtensions.StripMarkdown(acontent))}");

            await logchn.SendMessageAsync(embed : emb.Build());
        }
コード例 #6
0
        public static Response AsXml(this IResponseFormatter formatter, IXMLEntity entity)
        {
            var doc        = new XmlDocument();
            var firstChild = entity.Serialize(doc);

            doc.AppendChild(firstChild);

            return(FormatterExtensions.AsText(formatter, doc.OuterXml).WithContentType("text/xml"));
        }
コード例 #7
0
        public ProductModule(AutoQueryableContext context) : base("/products")
        {
            Get("/", args => FormatterExtensions.AsJson(Response, context.Product.AutoQueryable(Context.Request.Url.Query)));

            Get("/withfilter", args =>
            {
                After.AutoQueryable(Context, context.Product);
                return("");
            });
        }
コード例 #8
0
        public void TestPairIndexes()
        {
            // Arrange

            string test = "{super-{{toRep{dd}lace1}-{Key4}}}";

            // Act
            var result = FormatterExtensions.PairIndexes(test, '{', '}');

            // Assert

            Assert.Equal((14, 17), result);
        }
コード例 #9
0
        public QueryPersonModule(IQueryHandler <GetPersonQuery, PersonDto> getPersonQueryHandler)
            : base("/api/v1/persons")
        {
            Get["/{id:guid}"] = parameters =>
            {
                var result = getPersonQueryHandler.Execute(new GetPersonQuery {
                    Id = parameters.id
                });
                if (result == null)
                {
                    return(HttpStatusCode.NoContent);
                }

                return(FormatterExtensions.AsJson(Response, result, HttpStatusCode.OK));
            };
        }
コード例 #10
0
        public static GuildMap MapGuild(GuildEngine guild)
        {
            var map = new GuildMap()
            {
                Id                = guild.Id,
                Name              = guild.Name,
                Lang              = guild.Lang,
                IconUrl           = guild.IconUrl,
                TicketsBin        = FormatterExtensions.ToBinary(guild.Tickets.Values.ToList()),
                SetupMessagesBin  = FormatterExtensions.ToBinary(guild.SetupMessages.Values.ToList()),
                RolesMessagesBin  = FormatterExtensions.ToBinary(guild.RolesMessagesData.Values.ToList()),
                PermittedRolesCSV = guild.PermittedRoles.ToCSV(";")
            };

            return(map);
        }
コード例 #11
0
        public static GuildEngine UnMapGuild(GuildMap database)
        {
            var         tickets   = FormatterExtensions.ToObject <List <Ticket> >(database.TicketsBin);
            var         smessages = FormatterExtensions.ToObject <List <SetupMessage> >(database.SetupMessagesBin);
            var         sroles    = FormatterExtensions.ToObject <List <RolesMessageData> >(database.RolesMessagesBin);
            GuildEngine info      = new GuildEngine(database.Id, database.Name)
            {
                Lang              = database.Lang,
                IconUrl           = database.IconUrl,
                Tickets           = tickets.ToDictionary(x => x.Id),
                SetupMessages     = smessages.ToDictionary(x => x.MessageId),
                RolesMessagesData = sroles.ToDictionary(x => x.MessageId),
                PermittedRoles    = FormatterExtensions.FromCSV <ulong>(database.PermittedRolesCSV, ";").ToList()
            };

            return(info);
        }
コード例 #12
0
        public RegisterModule(Interactors interactors)
        {
            Get("/register", context => {
                var name   = Request.Query["name"];
                var phone  = Request.Query["phone"];
                var result = interactors.Register(name, phone);
                var json   = FormatterExtensions.AsJson <Result>(Response, result);
                return(json);
            });

            Get("/approve/{id}", context => {
                var id     = context.id;
                var code   = Request.Query["code"];
                var result = interactors.Approve(code, id);
                var json   = FormatterExtensions.AsJson <Result>(Response, result);
                return(json);
            });
        }
コード例 #13
0
        public RollerModule(Interactors interactors)
        {
            Get("/checkin/{id}", context => {
                var id       = context.id;
                var rollerId = Request.Query["rollerid"];
                var result   = interactors.Checkin(id, rollerId);
                var json     = FormatterExtensions.AsJson <Result>(Response, result);
                return(json);
            });

            Get("/checkout/{id}", context => {
                var id       = context.id;
                var rollerId = Request.Query["rollerid"];
                var result   = interactors.Checkout(id, rollerId);
                var json     = FormatterExtensions.AsJson <Result>(Response, result);
                return(json);
            });
        }
コード例 #14
0
        public async Task NsfwAsync(CommandContext ctx,
                                    [Description("URL to wrap.")] Uri url,
                                    [RemainingText, Description("Additional info")] string info = null)
        {
            await ctx.Message.DeleteAsync();

            var emb = new DiscordEmbedBuilder {
                Title       = $"{StaticDiscordEmoji.NoEntry} NSFW link from {ctx.Member.DisplayName} {StaticDiscordEmoji.NoEntry}",
                Description = FormatterExtensions.Spoiler(url.ToString()),
                Color       = DiscordColor.Red
            };

            if (!string.IsNullOrWhiteSpace(info))
            {
                emb.AddField("Additional info", Formatter.BlockCode(FormatterExtensions.StripMarkdown(info)));
            }

            await ctx.RespondAsync(embed : emb.Build());
        }
コード例 #15
0
        public FactTypeApiModule(IFactTypeService factTypeService) :
            base("/api/facttype")
        {
            Get["/"] = _ =>
            {
                if (Request.Query["q"] == null)
                {
                    return(Response.AsJson(factTypeService.ListFactTypes()));
                }
                return(FormatterExtensions.AsJson(Response, factTypeService.FindFactTypes(Request.Query["q"])));
            };


            Post["/"] =
                Post["/{factTypeId}"] = _ =>
            {
                FactTypeModel model      = this.Bind();
                int           factTypeId = model.Id;
                if (factTypeId == 0 && Context.Parameters["factTypeId"] != null)
                {
                    factTypeId = Context.Parameters["factTypeId"] ?? 0;
                }
                try
                {
                    if (factTypeId == 0)
                    {
                        factTypeId = factTypeService.AddFactType(model);
                    }
                    else
                    {
                        factTypeService.UpdateFactType(model);
                    }
                    return(Response.AsJson(new { FactTypeId = factTypeId }));
                }
                catch (InvalidOperationException ex)
                {
                    var response = Response.AsJson(new { ex.Message });
                    return(response.StatusCode = HttpStatusCode.NotFound);
                }
            };
        }
コード例 #16
0
        public DynamicContentModule()
        {
            var factory = new ModelFactory();

            Get["/api/dynamic/model/{id}"] = _ => FormatterExtensions.AsJson(Response, factory.GetModel(_.id));

            Get["/api/dynamic/models/{type?}"] = _ =>
            {
                var page = 0;
                var size = 5;

                if (Request.Query.page.HasValue)
                {
                    int.TryParse(Request.Query.page, out page);
                }
                if (Request.Query.size.HasValue)
                {
                    int.TryParse(Request.Query.size, out size);
                }

                return(FormatterExtensions.AsJson(Response, factory.GetModels(_.type, page, size)));
            };
        }
コード例 #17
0
ファイル: Listeners.Message.cs プロジェクト: happyfeetx/kiosk
        public static async Task MessageUpdateEventHandlerAsync(KioskAppShard shard, MessageUpdateEventArgs e)
        {
            if (e.Author is null || e.Author.IsBot || e.Channel is null || e.Channel.IsPrivate || e.Message is null)
            {
                return;
            }

            if (shard.SharedData.BlockedChannels.Contains(e.Channel.Id))
            {
                return;
            }

            if (!(e.Message.Content is null) && shard.SharedData.MessageContainsFilter(e.Guild.Id, e.Message.Content))
            {
                try
                {
                    await e.Message.DeleteAsync("_gf: Filter hit after update");

                    await e.Channel.SendMessageAsync($"{e.Author.Mention} said: {FormatterExtensions.Spoiler(Formatter.BlockCode(Formatter.Strip(e.Message.Content)))}");
                }
                catch
                {
                }
            }

            DiscordChannel logchn = shard.SharedData.GetLogChannelForGuild(shard.Client, e.Guild);

            if (logchn is null || !e.Message.IsEdited)
            {
                return;
            }

            DiscordMember member = await e.Guild.GetMemberAsync(e.Author.Id);

            using (DatabaseContext db = shard.Database.CreateContext())
            {
                if (db.LoggingExempts.Any(ee => ee.Type == ExemptedEntityType.Channel && ee.Id == e.Channel.Id))
                {
                    return;
                }
                if (db.LoggingExempts.Any(ee => ee.Type == ExemptedEntityType.Member && ee.Id == e.Author.Id))
                {
                    return;
                }
                if (member?.Roles.Any(r => db.LoggingExempts.Any(ee => ee.Type == ExemptedEntityType.Role && ee.Id == r.Id)) ?? false)
                {
                    return;
                }
            }

            string pcontent = string.IsNullOrWhiteSpace(e.MessageBefore?.Content) ? "" : e.MessageBefore.Content.Truncate(700);
            string acontent = string.IsNullOrWhiteSpace(e.Message?.Content) ? "" : e.Message.Content.Truncate(700);
            string ctime    = e.Message.CreationTimestamp == null ? _unknown : e.Message.CreationTimestamp.ToUtcTimestamp();
            string etime    = e.Message.EditedTimestamp is null ? _unknown : e.Message.EditedTimestamp.Value.ToUtcTimestamp();
            string bextra   = $"Embeds: {e.MessageBefore?.Embeds?.Count ?? 0}, Reactions: {e.MessageBefore?.Reactions?.Count ?? 0}, Attachments: {e.MessageBefore?.Attachments?.Count ?? 0}";
            string aextra   = $"Embeds: {e.Message.Embeds.Count}, Reactions: {e.Message.Reactions.Count}, Attachments: {e.Message.Attachments.Count}";

            DiscordEmbedBuilder emb = FormEmbedBuilder(EventOrigin.Message, "Message updated");

            emb.WithDescription(Formatter.MaskedUrl("Jump to message", e.Message.JumpLink));
            emb.AddField("Location", e.Channel.Mention, inline: true);
            emb.AddField("Author", e.Message.Author?.Mention ?? _unknown, inline: true);
            emb.AddField("Before update", $"Created {ctime}\n{bextra}\nContent:{Formatter.BlockCode(Formatter.Strip(pcontent))}");
            emb.AddField("After update", $"Edited {etime}\n{aextra}\nContent:{Formatter.BlockCode(Formatter.Strip(acontent))}");

            await logchn.SendMessageAsync(embed : emb.Build());
        }
コード例 #18
0
        public async Task AnnounceAsync(CommandContext ctx,
                                        [RemainingText, Description("Message to send.")] string message)
        {
            if (!await ctx.WaitForBoolReplyAsync($"Are you sure you want to announce the message:\n\n{Formatter.BlockCode(FormatterExtensions.StripMarkdown(message))}"))
            {
                return;
            }

            var emb = new DiscordEmbedBuilder {
                Title       = "An announcement from my owner",
                Description = message,
                Color       = DiscordColor.Red
            };

            var eb = new StringBuilder();

            foreach (TheGodfatherShard shard in TheGodfather.ActiveShards)
            {
                foreach (DiscordGuild guild in shard.Client.Guilds.Values)
                {
                    try {
                        await guild.GetDefaultChannel().SendMessageAsync(embed: emb.Build());
                    } catch {
                        eb.AppendLine($"Warning: Failed to send a message to {guild.ToString()}");
                    }
                }
            }

            if (eb.Length > 0)
            {
                await this.InformFailureAsync(ctx, $"Action finished with following errors:\n\n{eb.ToString()}");
            }
            else
            {
                await this.InformAsync(ctx, StaticDiscordEmoji.Information, "Sent the message to all guilds!", important : false);
            }
        }
コード例 #19
0
        public static async Task MessageDeleteEventHandlerAsync(FreudShard shard, MessageDeleteEventArgs e)
        {
            if (e.Channel.IsPrivate || e.Message is null)
            {
                return;
            }

            var logchn = shard.SharedData.GetLogChannelForGuild(shard.Client, e.Guild);

            if (logchn is null || e.Channel.IsExempted(shard))
            {
                return;
            }
            if (e.Message.Author == e.Client.CurrentUser && shard.SharedData.IsEventRunningInChannel(e.Channel.Id))
            {
                return;
            }

            var emb = FormEmbedBuilder(EventOrigin.Message, "Message deleted");

            emb.AddField("Location", e.Channel.Mention, inline: true);
            emb.AddField("Author", e.Message.Author?.Mention ?? _unknown, inline: true);

            var entry = await e.Guild.GetLatestAuditLogEntryAsync(AuditLogActionType.MessageDelete);

            if (!(entry is null) && entry is DiscordAuditLogMessageEntry mentry)
            {
                var member = await e.Guild.GetMemberAsync(mentry.UserResponsible.Id);

                if (member.IsExempted(shard))
                {
                    return;
                }

                emb.AddField("User responsible", mentry.UserResponsible.Mention, inline: true);

                if (!string.IsNullOrWhiteSpace(mentry.Reason))
                {
                    emb.AddField("Reason", mentry.Reason);
                }
                emb.WithFooter(mentry.CreationTimestamp.ToUtcTimestamp(), mentry.UserResponsible.AvatarUrl);
            }

            if (!string.IsNullOrWhiteSpace(e.Message.Content))
            {
                emb.AddField("Content", $"{Formatter.BlockCode(string.IsNullOrWhiteSpace(e.Message.Content) ? "<empty content>" : FormatterExtensions.StripMarkdown(e.Message.Content.Truncate(1000)))}");

                if (shard.SharedData.MessageContainsFilter(e.Guild.Id, e.Message.Content))
                {
                    emb.WithDescription(Formatter.Italic("Message contained a filter."));
                }
            }

            if (e.Message.Embeds.Any())
            {
                emb.AddField("Embeds", e.Message.Embeds.Count.ToString(), inline: true);
            }
            if (e.Message.Reactions.Any())
            {
                emb.AddField("Reactions", string.Join(" ", e.Message.Reactions.Select(r => r.Emoji.GetDiscordName())), inline: true);
            }
            if (e.Message.Attachments.Any())
            {
                emb.AddField("Attachments", string.Join("\n", e.Message.Attachments.Select(a => a.FileName)), inline: true);
            }
            if (e.Message.CreationTimestamp != null)
            {
                emb.AddField("Message creation time", e.Message.CreationTimestamp.ToUtcTimestamp(), inline: true);
            }

            await logchn.SendMessageAsync(embed : emb.Build());
        }
コード例 #20
0
        private dynamic Echo(dynamic p)
        {
            var json = GetJson(p);

            return(FormatterExtensions.AsText(Response, json, "application/json"));
        }
コード例 #21
0
 public static Response AsPagedList <T>(this IResponseFormatter formatter, PagedList <T> list)
 {
     return(FormatterExtensions.AsJson(formatter, list)
            .WithHeader("X-Total-Count", list.Total.ToString())
            .WithHeader("X-Offset", list.Offset.ToString()));
 }
コード例 #22
0
 private Response ReturnResolvedVariable(VariableCollection variableCollection, dynamic parameters) => FormatterExtensions.AsText(Response, variableCollection.Get(parameters.variable));
コード例 #23
0
ファイル: DomainModule.cs プロジェクト: sebbo176/NancyTest
 public DomainModule(IInMemoryEntityHolder inMemoryEntityHolder)
 {
     Get["domain/"]     = p => !inMemoryEntityHolder.GetAll().Any() ? "No entities at this thime, try posting some!" : Response.AsJson(inMemoryEntityHolder.GetAll());
     Get["domain/{id}"] = p => inMemoryEntityHolder.GetById(p.id) == null ? "Entity not found" : FormatterExtensions.AsJson(Response, inMemoryEntityHolder.GetById(p.id));
     Post["domain/"]    = p => Response.AsJson(inMemoryEntityHolder.Add(this.Bind <DomainEntity>()), HttpStatusCode.Accepted);
 }