public DiscordSink(params Tuple <ulong, string>[] webhooks) { _webhookClient = new DiscordWebhookClient(); foreach (var webhook in webhooks) { _webhookClient.AddWebhookAsync(webhook.Item1, webhook.Item2).Wait(); } }
public async Task StartAsync(CancellationToken cancellationToken) { _client.DebugLogger.LogMessageReceived += DebugLogger_LogMessageReceived; _client.ChannelPinsUpdated += Client_ChannelPinsUpdated; _commands.CommandExecuted += Commands_CommandExecuted; _commands.CommandErrored += Commands_CommandErrored; _commands.RegisterCommands <PinsCommands>(); await _client.ConnectAsync(); var db = _services.GetService <PinsDbContext>(); await db.Database.MigrateAsync(); _logger.LogInformation("Loading Guild webhooks"); var info = db.Guilds .Include(p => p.PinnedMessages); await info.LoadAsync(); var failedGuilds = new List <GuildInfo>(); foreach (var guild in info) { try { var server = await _client.GetGuildAsync((ulong)guild.Id); var hook = await _webhookClient.AddWebhookAsync((ulong)guild.WebhookId, guild.WebhookToken); _logger.LogInformation("Got Webhook! Guild: {0} Hook: {1}", server.Name, hook.Name); } catch (Exception ex) { _logger.LogError(ex, "Unable to get Webhook for Guild {0}!", guild.Id); failedGuilds.Add(guild); } } foreach (var guild in failedGuilds) { guild.PinnedMessages.Clear(); db.Guilds.Remove(guild); } await db.SaveChangesAsync(); _logger.LogInformation("Loaded {0} Webhooks for {1} guilds with {2} errors!", _webhookClient.Webhooks.Count, await db.Guilds.CountAsync(), failedGuilds.Count); }
public async Task Bug(CommandContext ctx, [Description("The bug explained in detail.")][RemainingText] string bug) { var client = new DiscordWebhookClient(); var webhook = await client.AddWebhookAsync(new Uri("https://discord.com/api/webhooks/852610216922054716/-n7TPmqRYjY_iok0hyHte8AkK4luspZwAZcvunS9yHdzIiXrfEE6PdPou4ypRO_B03Kb")); await new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder() { Title = "🐛 Bug", Description = string.Join(" ", bug), Author = new DiscordEmbedBuilder.EmbedAuthor() { IconUrl = ctx.User.AvatarUrl, Name = ctx.User.Username + "#" + ctx.User.Discriminator }, Color = DiscordColor.Green }).SendAsync(webhook); await ctx.Channel.SendMessageAsync(MessageUtils.BuildSuccess("Sent the bug !\nAny abuse will be punished...")); }
/// <summary> /// Initialises and starts the Discord bot. /// </summary> /// <returns>The task representing the bot's execution status.</returns> public async Task RunBotAsync() { this.Running = true; stopClientTokenSource = new CancellationTokenSource(); var json = ""; using (var fs = File.OpenRead("botconfig.json")) using (var sr = new StreamReader(fs, new UTF8Encoding(false))) json = await sr.ReadToEndAsync(); this.botConfig = JsonConvert.DeserializeObject <BotConfig>(json); this.UseServerLogo = this.botConfig.UseServerLogo; this.StreamRole = this.botConfig.StreamRole; this.AdminRole = this.botConfig.AdminRole; this.StreamName = this.botConfig.StreamName; if (!string.IsNullOrEmpty(this.botConfig.ShortServerName)) { ShortServerName = this.botConfig.ShortServerName; } var cfg = new DiscordConfiguration { Token = this.botConfig.Token, TokenType = TokenType.Bot, AutoReconnect = true, MinimumLogLevel = LogLevel.Debug }; MessageHandler = new MessageHandler(new MessageHandlerConfig { ApiUrl = this.botConfig.ApiUrl, ChannelId = this.botConfig.ChannelId, HmacKey = this.botConfig.HmacKey, // Login token generator TokenKey = this.botConfig.TokenKey, TokenPassword = this.botConfig.TokenPassword, StreamRole = this.botConfig.StreamRole, // Reference to this Client = this }); Uri.TryCreate(this.botConfig.WebhookUrl, UriKind.Absolute, out Uri WebhookUri); GuildId = this.botConfig.GuildId; ChannelId = this.botConfig.ChannelId; this.discordClient = new DiscordClient(cfg); this.discordClient.Ready += this.Client_Ready; this.discordClient.GuildAvailable += this.Client_GuildAvailable; this.discordClient.GuildUnavailable += this.Client_GuildUnavailable; this.discordClient.ClientErrored += this.Client_ClientError; this.discordClient.ChannelUpdated += this.Client_ChannelUpdated; this.discordClient.MessageCreated += MessageHandler.Created; this.discordClient.MessageUpdated += MessageHandler.Edited; this.discordClient.MessageDeleted += MessageHandler.Deleted; this.discordClient.TypingStarted += MessageHandler.Typing; webhookClient = new DiscordWebhookClient(); await webhookClient.AddWebhookAsync(WebhookUri); foreach (DiscordWebhook webhook in webhookClient.Webhooks) { if (webhook.ChannelId == botConfig.ChannelId) { WebhookChannelMatch = true; } } await this.discordClient.ConnectAsync(); try { await Task.Delay(-1, stopClientTokenSource.Token); } finally { // Cancellation requested or the client crashed, perform cleanup. this.Ready = false; this.discordClient.Dispose(); this.Running = false; stopClientTokenSource.Dispose(); } }
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 DiscordSink(ulong id, string token) { _webhookClient = new DiscordWebhookClient(); _webhookClient.AddWebhookAsync(id, token).Wait(); }