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; }
// , // /| __ // / | ,-~ / // Y :| // / // | jj /( .^ // >-"~"-v" // / Y // jo o | // ( ~T~j // >._-' _./ // / "~" | // Y _, | // /| ;-"~ _ l /// l/ ,-"~ \ //\//\/ .- \ // Y / Y -Row // l I ! // ]\ _\ /"\ //(" ~----( ~ Y. ) #endregion bunny public async Task <DiscordMessage> SendWebhookMessage(string content = null, DiscordEmbed[] embeds = null, FileStream fileStream = null, string fileName = null) { var dwb = new DiscordWebhookBuilder(); if (!(embeds is null)) { if (embeds.Length > 10) { throw new ArgumentException("More than 10 embeds provided."); } dwb.AddEmbeds(embeds); } if (!(content is null)) { dwb.WithContent(content); } if (!(fileStream is null) && !(fileName is null)) { dwb.AddFile(Path.GetFileName(fileName), fileStream); } if (embeds is null && content is null && fileStream is null) { throw new ArgumentException("Cannot send an empty message."); } return(await webhook.ExecuteAsync(dwb)); }
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); }
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); } }
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!"); } }
/// <summary> /// Sends embeds via a <see cref="DiscordWebhook"/> /// </summary> public async Task SendEmbed(string message = null, params DiscordEmbed[] embeds) { await _webhook.ExecuteAsync(content : message, username : _username, embeds : embeds, avatar_url : _avatarUrl?.ToString() ?? null).ConfigureAwait(false); }