private async Task CreateWebhookAsync(CommandContext ctx, DiscordChannel channel, string name, Uri?avatarUrl, string?reason) { // TODO what about other channel types? news, store etc? if (channel?.Type != ChannelType.Text) { throw new InvalidCommandUsageException(ctx, "cmd-err-chn-type-text"); } if (string.IsNullOrWhiteSpace(name) || name.Length > DiscordLimits.NameLimit) { throw new CommandFailedException(ctx, "cmd-err-name", DiscordLimits.NameLimit); } DiscordWebhook wh; if (avatarUrl is null) { wh = await channel.CreateWebhookAsync(name, reason : ctx.BuildInvocationDetailsString(reason)); } else { (_, HttpContentHeaders headers) = await HttpService.HeadAsync(avatarUrl); if (!headers.ContentTypeHeaderIsImage() || headers.ContentLength.GetValueOrDefault() > 8 * 1024 * 1024) { throw new CommandFailedException(ctx, "err-url-image-8mb"); } try { using MemoryStream ms = await HttpService.GetMemoryStreamAsync(avatarUrl); wh = await channel.CreateWebhookAsync(name, ms, reason : ctx.BuildInvocationDetailsString(reason)); } catch (WebException e) { throw new CommandFailedException(ctx, "err-url-image-fail", e); } } if (await ctx.WaitForBoolReplyAsync("q-send-token")) { try { DiscordDmChannel?dm = await ctx.Client.CreateDmChannelAsync(ctx.User.Id); if (dm is { }) { var emb = new LocalizedEmbedBuilder(this.Localization, ctx.Guild.Id); emb.WithLocalizedTitle("fmt-wh-add", Formatter.Bold(Formatter.Strip(wh.Name)), channel.Mention); emb.WithDescription($"||{wh.BuildUrlString()}||"); emb.WithColor(this.ModuleColor); emb.WithThumbnail(wh.AvatarUrl); emb.AddLocalizedTitleField("str-id", wh.Id, inline: true); emb.AddLocalizedTitleField("str-name", wh.Name, inline: true); emb.AddLocalizedTitleField("str-token", $"||{wh.Token}||"); await dm.SendMessageAsync(embed : emb.Build()); } else { await ctx.FailAsync("err-dm-fail"); } } catch {
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 ApplyWebhookData(DevelopmentStressTestChannel dev, DiscordChannel c) { DiscordWebhook?hook = await c.CreateWebhookAsync("Partner Test Sender", reason : "Partner Test Server Setup"); dev.WebhookId = hook.Id; dev.WebhookToken = hook.Token; }
public async Task CreateAsync(CommandContext ctx, [Description("Channel to list webhooks for.")] DiscordChannel channel, [Description("Name.")] string name, [Description("Avatar URL.")] Uri avatarUrl = null, [RemainingText, Description("Reason.")] string reason = null) { DiscordWebhook wh; if (avatarUrl is null) { wh = await channel.CreateWebhookAsync(name, reason : ctx.BuildInvocationDetailsString(reason)); } else { try { using (Stream stream = await _http.GetStreamAsync(avatarUrl)) using (var ms = new MemoryStream()) { await stream.CopyToAsync(ms); ms.Seek(0, SeekOrigin.Begin); wh = await channel.CreateWebhookAsync(name, ms, reason : ctx.BuildInvocationDetailsString(reason)); } } catch (WebException e) { throw new CommandFailedException("Failed to fetch the image!", e); } } await this.InformAsync(ctx, "Created a new webhook! Sending you the token in private...", important : false); try { DiscordDmChannel dm = await ctx.Client.CreateDmChannelAsync(ctx.User.Id); if (dm is null) { throw new CommandFailedException("I failed to send you the token in private."); } await dm.SendMessageAsync($"Token for webhook {Formatter.Bold(wh.Name)} in {Formatter.Bold(ctx.Guild.ToString())}, {Formatter.Bold(channel.ToString())}: {Formatter.BlockCode(wh.Token)}\nWebhook URL: {wh.BuildUrlString()}"); } catch { // Failed to create DM or insufficient perms to send } }
/// <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(); }
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!"); } }
private async Task Discord_Ready(DiscordClient sender, ReadyEventArgs e) { Logger.LogDebug($"{_client.CurrentUser.Username} ready in {_client.Guilds.Count} guild(s)!"); _ = Task.Run(async() => { if (_config.ChatSync.UseWebhooks) { if (_webhook.WebhookId == 0) { DiscordChannel channel = await _client.GetChannelAsync(_config.ChatSync.ChannelId); _webhook.Webhook = await channel.CreateWebhookAsync("ObsidianDiscord_Webhook"); _webhook.WebhookId = _webhook.Webhook.Id; await _configManager.SaveConfig(_webhook); } else { _webhook.Webhook = await _client.GetWebhookAsync(_webhook.WebhookId); } } }); await Task.CompletedTask; }
private Task <DiscordWebhook> DoCreateWebhook(DiscordChannel channel) { _logger.Information("Creating new webhook for channel {Channel}", channel.Id); return(channel.CreateWebhookAsync(WebhookName)); }
public async Task SetupAsync(CommandContext ctx, [Description("Channel to direct pinned messages to")] DiscordChannel channel, [Description("The URL of the webhook to use, including a token (optional)")] Uri webhookUrl = null) { if (!ctx.Guild.Channels.ContainsKey(channel.Id)) { await ctx.RespondAsync("Are you trying to migrate pins across servers?? That ain't gonna fly, kid."); return; } var info = await _database.FindAsync <GuildInfo>((long)ctx.Guild.Id); if (info != null) { // TODO: prompt to reconfigure/setup _logger.LogError("Unable to setup pins in {0} because it is already setup.", ctx.Guild); await ctx.RespondAsync("Pinned message redireciton is already enabled in this server!"); return; } var perms = channel.PermissionsFor(ctx.Guild.CurrentMember); if (!perms.HasPermission(Permissions.ManageWebhooks) && webhookUrl == null) { _logger.LogError("Unable to setup pins in {0} due to lack of permissions.", ctx.Guild); await ctx.RespondAsync("I can't setup pins without a Webhook URL or permission to manage webhooks! Sorry!"); return; } DiscordWebhook hook; if (webhookUrl != null) { try { hook = await _webhookClient.AddWebhookAsync(webhookUrl); } catch (Exception ex) { _logger.LogError(ex, "Failed to fetch webhook from URL."); await ctx.RespondAsync("The Webhook URL you specified was invalid!"); return; } } else { hook = await channel.CreateWebhookAsync("GAiA Pins", reason : $"Pinned Message redirection setup by @{ctx.User.Username}#{ctx.User.Discriminator} ({ctx.User.Id})"); _webhookClient.AddWebhook(hook); } var guild = new GuildInfo() { Id = (long)ctx.Guild.Id, WebhookId = (long)hook.Id, WebhookToken = hook.Token, PinsChannelId = (long)channel.Id }; _database.Add(guild); await _database.SaveChangesAsync(); await ctx.RespondAsync( "Pinned messages are now setup for this server!\n" + "To migrate pins, use `p;migrate`, and to configure further, use `p;configure`.\n" + "Disable at any time with `p;disable`."); }
public async Task RegisterRelayCommandAsync( [Description("Discord channel to link to.")] DiscordChannel discordChannel, [Description("IRC channel to link to.")] string ircChannel) { ircChannel = GetIrcChannelName(ircChannel); if (Context.Channel.GuildId == null) { await RespondBasicError("Can only use relay command in a guild channel"); return; } var cfg = _database.Find <RelayConfiguration>(Context.Channel.GuildId); if (cfg is null) { cfg = new RelayConfiguration() { DiscordServer = Context.Channel.GuildId.Value }; await _database.AddAsync(cfg); await _database.SaveChangesAsync(); } // TODO: Some check to see if the IRC channel is available. if (cfg.DiscordToIRCLinks.ContainsKey(discordChannel.Id)) { await RespondBasicError("A relay already exists for this Discord channel."); } var activeHooks = await discordChannel.GetWebhooksAsync(); if (cfg.Webhooks.TryGetValue(ircChannel, out var hook)) { if (activeHooks.Any(x => x.Id == hook.Id)) { await RespondBasicError("A relay for this IRC channel is already in that Discord channel!"); } else { _database.Update(cfg); var discordHook = await Context.Client.GetWebhookAsync(hook.Id); await discordHook.ModifyAsync(channelId : discordChannel.Id); await _database.SaveChangesAsync(); await RespondBasicSuccess($"Moved the relay for IRC channel `{ircChannel}` to {discordChannel.Name}"); } return; } var newHook = await discordChannel.CreateWebhookAsync($"Dostya-{ircChannel}", reason : "Dostya Relay Creation"); if (await _relay.AddRelayAsync(Context.Channel.GuildId.Value, newHook, ircChannel)) { await RespondBasicSuccess($"Relay bridge added ({discordChannel.Name} <-> {ircChannel})"); } else { await RespondBasicError("Failed to add new relay."); } }