private async Task GetUpdateForGuildAsync(BattlefieldUpdate latestBattlefieldUpdate, DiscordGuild guild) { GuildConfig cfg = await _guildService.GetOrCreateConfigAsync(guild.Id); if (cfg == null || !cfg.BattlefieldUpdatesEnabled) { return; } DiscordChannel channel = guild.GetChannel(cfg.BattlefieldUpdatesChannel); if (channel == null) { _logger.LogError($"Battlefield Updates enabled for {guild.Name} but channel {cfg.BattlefieldUpdatesChannel} is invalid"); return; } DateTime lastUpdateUTC = cfg.LastBattlefieldUpdate ?? DateTime.MinValue; if (lastUpdateUTC >= latestBattlefieldUpdate.UpdateDate) { return; } var builder = new DiscordEmbedBuilder() .WithColor(new DiscordColor(21, 26, 35)) .WithTitle(latestBattlefieldUpdate.Title) .WithUrl(latestBattlefieldUpdate.UpdateUrl) .WithDescription(latestBattlefieldUpdate.Description) .WithImageUrl(latestBattlefieldUpdate.ImgUrl) .WithFooter(latestBattlefieldUpdate.UpdateDate.ToString()); await(channel?.SendMessageAsync(builder.Build())); cfg.LastBattlefieldUpdate = latestBattlefieldUpdate.UpdateDate; await _guildService.UpdateConfigAsync(cfg); }
protected async Task TryAgain(DiscordChannel channel, string problem) { var embedBuilder = new DiscordEmbedBuilder { Title = "Please Try Again", Color = DiscordColor.Red, }; embedBuilder.AddField("There was a problem with your previous input", problem); var embed = await channel.SendMessageAsync(embed: embedBuilder).ConfigureAwait(false); OnMessageAdded(embed); }
private static void IrcIncomingMessage(IrcController controller, IrcMessage message) { ChannelMappingConfig channelMapping = _config.ChannelMappings.FirstOrDefault(mapping => mapping.IrcChannel.ToIrcLower() == message.Parameters[0].ToIrcLower()); if (channelMapping != null) { DiscordChannel channel = _discord.GetChannelAsync(channelMapping.DiscordChannel).GetAwaiter().GetResult(); if (channel != null) { channel.SendMessageAsync($"**[IRC]** <*{message.SourceNick}*> {message.Parameters[1]}"); } } }
private async Task Paginate(DiscordChannel channel, int pageNum) { if (pageNum < 1) { pageNum = 1; } else if (pageNum > Pages) { pageNum = Pages; } var msg = RenderPage(pageNum); await Initialize(await channel.SendMessageAsync(embed: msg), pageNum); }
protected async Task TryAgain(DiscordChannel channel, string problem) { var embed = new DiscordEmbedBuilder { Title = "Something went wrong, try again", Color = DiscordColor.IndianRed }; embed.AddField("Error", problem); var embedResult = await channel.SendMessageAsync(embed : embed).ConfigureAwait(false); OnMessageAdded(embedResult); }
public override async Task <bool> ProcessStep(DiscordClient client, DiscordChannel channel, DiscordUser user) { var embedBuilder = new DiscordEmbedBuilder { Title = $"Пожалуйста введите сообщение", Description = $"{user.Mention},{_content}", }; embedBuilder.AddField("Чтобы остановить диалог", "используйте команду -cancle"); if (_minLenght.HasValue) { embedBuilder.AddField("Минимальная длина:", $"{_minLenght.Value} символа"); } if (_maxLenght.HasValue) { embedBuilder.AddField("Максимальная длина:", $"{_maxLenght.Value} символа"); } var iteractivity = client.GetInteractivity(); while (true) { var embed = await channel.SendMessageAsync(embed : embedBuilder).ConfigureAwait(false); OnMessageAdded(embed); var messageResult = await iteractivity.WaitForMessageAsync(x => x.ChannelId == channel.Id && x.Author.Id == user.Id).ConfigureAwait(false); OnMessageAdded(messageResult.Result); if (messageResult.Result.Content.Equals("-cancel", StringComparison.OrdinalIgnoreCase)) { return(true); } if (_minLenght.HasValue) { if (messageResult.Result.Content.Length < _minLenght.Value) { await TryAgain(channel, $"Ваше сообщение слишком короткое, содержит {_minLenght.Value - messageResult.Result.Content.Length} символ").ConfigureAwait(false); continue; } } OnValidResult(messageResult.Result.Content); return(false); } }
public static async Task <DiscordMessage> SendAsync(DiscordChannel channel, string textContent, DiscordEmbed embedContent = null) { try { if (!ChannelHasPermission(channel, Permissions.SendMessages)) { return(null); } if (embedContent == null) { return(await channel.SendMessageAsync(textContent, false)); } else { // Either make sure we have permission to use embeds or convert the embed to text if (ChannelHasPermission(channel, Permissions.EmbedLinks)) { return(await channel.SendMessageAsync(textContent, false, embedContent)); } else { return(await channel.SendMessageAsync(MessageBuilder.EmbedToText(textContent, embedContent))); } } } catch (Newtonsoft.Json.JsonReaderException e) { Logger.Debug(e.ToString()); return(null); } catch (Exception e) { Logger.Error("Error occurred while attempting to send Discord message. Error message: " + e); return(null); } }
public async Task ExecuteGroupAsync(CommandContext ctx, [Description("Enable?")] bool enable, [Description("Sensitivity (number of users allowed to join within a given timespan).")] short sensitivity, [Description("Action type.")] PunishmentActionType action = PunishmentActionType.Kick, [Description("Cooldown.")] TimeSpan?cooldown = null) { if (sensitivity < 2 || sensitivity > 20) { throw new CommandFailedException("The sensitivity is not in the valid range ([2, 20])."); } if (cooldown?.TotalSeconds < 5 || cooldown?.TotalSeconds > 60) { throw new CommandFailedException("The cooldown timespan is not in the valid range ([5, 60] seconds)."); } var settings = new AntifloodSettings() { Action = action, Cooldown = (short?)cooldown?.TotalSeconds ?? 10, Enabled = enable, Sensitivity = sensitivity }; await this.Database.SetAntifloodSettingsAsync(ctx.Guild.Id, settings); DiscordChannel logchn = this.Shared.GetLogChannelForGuild((DiscordClientImpl)ctx.Client, ctx.Guild); if (logchn != null) { var emb = new DiscordEmbedBuilder() { Title = "Guild config changed", Description = $"Antiflood {(enable ? "enabled" : "disabled")}", Color = this.ModuleColor }; emb.AddField("User responsible", ctx.User.Mention, inline: true); emb.AddField("Invoked in", ctx.Channel.Mention, inline: true); if (enable) { emb.AddField("Antiflood sensitivity", settings.Sensitivity.ToString(), inline: true); emb.AddField("Antiflood cooldown", settings.Cooldown.ToString(), inline: true); emb.AddField("Antiflood action", settings.Action.ToTypeString(), inline: true); } await logchn.SendMessageAsync(embed : emb.Build()); } await this.InformAsync(ctx, $"{Formatter.Bold(enable ? "Enabled" : "Disabled")} antiflood actions.", important : false); }
public static async Task MessageFilterEventHandlerAsync(TheGodfatherShard 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; } CachedGuildConfig gcfg = shard.SharedData.GetGuildConfig(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("_gf: Filter hit"); DiscordChannel logchn = shard.SharedData.GetLogChannelForGuild(shard.Client, e.Guild); if (logchn == null) { return; } DiscordEmbedBuilder emb = FormEmbedBuilder(EventOrigin.Message, $"Filter triggered"); emb.AddField("User responsible", e.Message.Author.Mention); emb.AddField("Channel", e.Channel.Mention); emb.AddField("Content", Formatter.BlockCode(Formatter.Sanitize(e.Message.Content.Truncate(1020)))); await logchn.SendMessageAsync(embed : emb.Build()); }
public override async Task <eDialogueType> ProcessStep(DiscordClient client, DiscordChannel channel, DiscordUser user) { var embedBuilder = new DiscordEmbedBuilder { Title = $"Please Respond Below", Description = $"{user.Mention}, {_content}" }; embedBuilder.AddField("To Stop The Dialogue", "Use the ?cancel command"); var interactivity = client.GetInteractivity(); var embed = await channel.SendMessageAsync(embed : embedBuilder).ConfigureAwait(false); var pollDescription = string.Empty; while (true) { //OnMessageAdded(embed); var messageResult = await interactivity.WaitForMessageAsync(x => x.ChannelId == channel.Id && x.Author.Id == user.Id, TimeSpan.FromMinutes(1)).ConfigureAwait(false); OnMessageAdded(messageResult.Result); if (messageResult.TimedOut == true) { return(eDialogueType.Timeout); } if (messageResult.Result.Content.Equals("?cancel", StringComparison.OrdinalIgnoreCase)) { await embed.DeleteAsync(); return(eDialogueType.Cancel); } if (messageResult.Result.Content.Equals("?start", StringComparison.OrdinalIgnoreCase)) { return(eDialogueType.Continue); } pollDescription += (messageResult.Result.Content + Environment.NewLine); _pollEmbed.WithDescription(pollDescription); await _pollMessage.ModifyAsync(embed : _pollEmbed.Build()); OnValidResult(messageResult.Result.Content); } }
static public async Task DoCrawling_ThisIsGame(DiscordChannel pChannel) { IWebDriver pDriver = new ChromeDriver(); pDriver.Url = const_strThisIsGame; IWebElement pElement_ListParents = pDriver.FindElement(By.ClassName("side-comp-body")); var arrElementRanking = pElement_ListParents.FindElements(By.TagName("a")); var pEmbedBuilder = Program.DoGenerateEmbedBuilder(DiscordColor.Green, arrElementRanking, "디스이스게임 많이본 기사 리스트입니다.", const_strThisIsGame, false); await pChannel.SendMessageAsync(null, false, pEmbedBuilder); pDriver.Close(); }
public static async Task SendFeedResultsAsync(DiscordChannel channel, IEnumerable<SyndicationItem> results) { if (results is null) return; var emb = new DiscordEmbedBuilder { Title = "Topics active recently", Color = DiscordColor.White }; foreach (SyndicationItem res in results) emb.AddField(res.Title.Text.Truncate(255), res.Links.First().Uri.ToString()); await channel.SendMessageAsync(embed: emb.Build()); }
async Task <LavalinkGuildConnection> Join(DiscordGuild guild, DiscordChannel channel, DiscordMember member) { if (discordUrie.LavalinkNode.GetGuildConnection(guild) != null) { await channel.SendMessageAsync("Already connected."); return(null); } if (member.VoiceState.Channel == null) { await channel.SendMessageAsync("You need to be in a voice channel first."); return(null); } var conn = await discordUrie.LavalinkNode.ConnectAsync(member.VoiceState.Channel); conn.PlaybackFinished += PlaybackFinished; if (this.musicData.Any(xr => xr.GuildId == guild.Id)) { this.musicData.RemoveAll(xr => xr.GuildId == guild.Id); } this.musicData.Add(new GuildMusicData(guild, conn.Channel, channel)); return(conn); }
private async Task <DiscordMessage> GetPublicStatusMessage() { var pinnedMessages = await _publicStatusChannel.GetPinnedMessagesAsync(); if (pinnedMessages.Count > 0) { return(pinnedMessages[0]); } var statusMessage = await _publicStatusChannel.SendMessageAsync("**Placeholder**"); await statusMessage.PinAsync(); return(statusMessage); }
/// <summary> /// Sends a paginated message. /// </summary> /// <param name="c">Channel to send paginated message in.</param> /// <param name="u">User to give control.</param> /// <param name="pages">Pages.</param> /// <param name="emojis">Pagination emojis (emojis set to null get disabled).</param> /// <param name="behaviour">Pagination behaviour (when hitting max and min indices).</param> /// <param name="deletion">Deletion behaviour.</param> /// <param name="timeoutoverride">Override timeout period.</param> /// <returns></returns> public async Task SendPaginatedMessageAsync(DiscordChannel c, DiscordUser u, IEnumerable <Page> pages, PaginationEmojis emojis = null, PaginationBehaviour behaviour = PaginationBehaviour.Default, PaginationDeletion deletion = PaginationDeletion.Default, TimeSpan?timeoutoverride = null) { var m = await c.SendMessageAsync(pages.First().Content, false, pages.First().Embed); var timeout = timeoutoverride ?? Config.Timeout; var bhv = behaviour == PaginationBehaviour.Default ? this.Config.PaginationBehaviour : behaviour; var del = deletion == PaginationDeletion.Default ? this.Config.PaginationDeletion : deletion; var ems = emojis ?? this.Config.PaginationEmojis; var prequest = new PaginationRequest(m, u, bhv, del, ems, timeout, pages.ToArray()); await Paginator.DoPaginationAsync(prequest); }
public static async Task SendEmbed(DiscordChannel channel, string title, string description, string footer = "", int color = -1) { DiscordEmbedBuilder embedErr = new DiscordEmbedBuilder(); embedErr.Title = title; embedErr.Description = description.Length > 2040 ? description.Substring(0, 2040) : description; embedErr.Color = color >= 0 ? new DiscordColor(color) : DiscordColor.Magenta; if (footer != "") { embedErr.WithFooter(footer); } await channel.SendMessageAsync(embed : embedErr); return; }
public static async Task VoiceServerUpdateEventHandlerAsync(TheGodfatherShard shard, VoiceServerUpdateEventArgs e) { DiscordChannel logchn = shard.SharedData.GetLogChannelForGuild(shard.Client, e.Guild); if (logchn == null) { return; } DiscordEmbedBuilder emb = FormEmbedBuilder(EventOrigin.Guild, "Voice server updated"); emb.AddField("Endpoint", Formatter.Bold(e.Endpoint)); await logchn.SendMessageAsync(embed : emb.Build()); }
protected Task LogConfigChangeAsync(CommandContext ctx, string module, bool value) { DiscordChannel logchn = this.Shared.GetLogChannelForGuild(ctx.Client, ctx.Guild); if (!(logchn is null)) { var emb = new DiscordEmbedBuilder { Title = "Guild config changed", Color = this.ModuleColor }; emb.AddField("User responsible", ctx.User.Mention, inline: true); emb.AddField("Invoked in", ctx.Channel.Mention, inline: true); emb.AddField(module, value ? "on" : "off", inline: true); return(logchn.SendMessageAsync(embed: emb.Build())); }
private async Task LogLinkfilterMatchAsync(MessageCreateEventArgs e, string desc) { DiscordChannel logchn = this.shard.SharedData.GetLogChannelForGuild(this.shard.Client, e.Guild); if (logchn is null) { return; } DiscordEmbedBuilder emb = Listeners.FormEmbedBuilder(EventOrigin.Linkfilter, "Linkfilter action triggered", desc); emb.AddField("User responsible", e.Author.Mention); await logchn.SendMessageAsync(embed : emb.Build()); }
public async Task MuteUser(CommandContext commandContext, [Description("User which should be muted")] DiscordMember discordMember, [Description("Reason"), RemainingText] string reason) { DiscordRole muteRole = commandContext.Guild.Roles.FirstOrDefault(x => x.Value.Name == "Muted").Value; await discordMember.GrantRoleAsync(muteRole, reason); await commandContext.RespondAsync("", embed : new DiscordEmbedBuilder().WithAuthor(discordMember.DisplayName, iconUrl : discordMember.AvatarUrl) .WithTitle("**MUTED**") .WithDescription($"Reason: {(reason != string.Empty ? reason : "not stated")}") .Build()); await LogChannel.SendMessageAsync( embed : new DiscordEmbedBuilder().WithAuthor(name : commandContext.Message.Author.Username, iconUrl : commandContext.Message.Author.AvatarUrl) .AddField("**Action**:", "muted", true) .AddField("**Target**:", discordMember.ToString(), true) .AddField("**Reason**:", (reason != string.Empty ? reason : "not stated"), true) .WithFooter() .Build()); }
private async Task <DiscordMessage> UpdateRaidLobbyMessage(RaidLobby lobby, DiscordChannel raidLobbyChannel, DiscordEmbed raidMessage) { _logger.Trace($"FilterBot::UpdateRaidLobbyMessage [RaidLobby={lobby.LobbyMessageId}, DiscordChannel={raidLobbyChannel.Name}, DiscordMessage={raidMessage.Title}]"); var coming = await GetUsernames(lobby.UsersComing); var ready = await GetUsernames(lobby.UsersReady); var msg = $"**Trainers on the way:**{Environment.NewLine}```{string.Join(Environment.NewLine, coming)} ```{Environment.NewLine}**Trainers at the raid:**{Environment.NewLine}```{string.Join(Environment.NewLine, ready)} ```"; var lobbyMessage = await raidLobbyChannel.GetMessage(lobby.LobbyMessageId); if (lobbyMessage != null) { var coordinates = Utils.GetLastLine(raidMessage.Description); var latitude = double.Parse(coordinates.Split(',')[0]); var longitude = double.Parse(coordinates.Split(',')[1]); var city = "Unknown"; var loc = _geofenceSvc.GetGeofence(new Location(latitude, longitude)); if (loc == null) { _logger.Error($"Failed to lookup city for coordinates {latitude},{longitude}..."); } city = loc.Name; msg = $"**City:** {city}\r\n{msg}"; await lobbyMessage.DeleteAsync(); lobbyMessage = null; } if (lobbyMessage == null) { lobbyMessage = await raidLobbyChannel.SendMessageAsync(msg, false, raidMessage); lobby.LobbyMessageId = lobbyMessage.Id; } _config.Save(); if (lobbyMessage == null) { _logger.Error($"Failed to set default raid reactions to message {lobby.LobbyMessageId}, couldn't find message..."); return(null); } lobby.LobbyMessageId = lobbyMessage.Id; return(lobbyMessage); }
public async Task Execute() { Log.Information("Checking YouTube for new videos.."); YouTubeVideo video = await this.youTubeService.GetLatestAsync(); // Unable to fetch the latest post from youtube if (video == null) { this.bloonLog.Error($"Something went wrong fetching the latest youtube video! Check Log File"); return; } else if (!await this.youTubeService.TryStoreNewAsync(video)) { Log.Information("Finished Youtube checks early"); return; } DiscordChannel sbgGen = await this.dClient.GetChannelAsync(SBGChannels.General); DiscordEmbed ytEmbed = new DiscordEmbedBuilder { Author = new DiscordEmbedBuilder.EmbedAuthor { IconUrl = DiscordEmoji.FromGuildEmote(this.dClient, SBGEmojis.Superboss).Url, Name = "Superboss Games", Url = "https://www.youtube.com/user/SuperbossGames", }, Footer = new DiscordEmbedBuilder.EmbedFooter { IconUrl = DiscordEmoji.FromGuildEmote(this.dClient, PlatformEmojis.YouTube).Url, Text = "YouTube", }, Color = new DiscordColor(255, 0, 0), Timestamp = video.Timestamp, Title = video.Title, Description = video.Description, Url = $"https://www.youtube.com/watch?v={video.UID}", Thumbnail = new DiscordEmbedBuilder.EmbedThumbnail { Url = video.ThumbnailUrl, }, }; await sbgGen.SendMessageAsync(embed : ytEmbed); Log.Information("Finished YouTube Scraping"); }
public async Task SayCommand(CommandContext ctx, [Description("Channel to send the message in")] DiscordChannel channel, [Description("Text to send")][RemainingText] string text) { if (channel.GuildId != ctx.Guild.Id) { return; } if (!(channel.PermissionsFor(ctx.Member).HasPermission(Permissions.ManageMessages) || ctx.Member.Id.ToString() == Configuration["Owner"])) { throw new UserError("You don't have permission to do that"); } await channel.SendMessageAsync(text); try { await ctx.Message.DeleteAsync(); } catch { } }
public static async Task LogActionNoMsg(DiscordGuild guild, string functionName, string description, string message, DiscordColor color) { DiscordChannel channel = guild.GetChannel(GuildsList[guild.Id].ChannelConfig.LogChannelID); DiscordEmbedBuilder builder = new DiscordEmbedBuilder(); builder.WithTitle("Changelog"); builder.WithThumbnailUrl("https://media.discordapp.net/attachments/496417444613586984/496671867109769216/logthumbnail.png"); builder.WithDescription("Logged user/bot action"); builder.AddField(name: "Function", value: $"{functionName}"); builder.AddField(name: "Description", value: $"{description}"); builder.AddField(name: "Message", value: $"{message}"); builder.WithFooter("Copyright 2018 Lala Sabathil"); await channel.SendMessageAsync(content : null, tts : false, embed : builder.Build()); }
async Task Client_Heartbeated(HeartbeatEventArgs e) { if (DateTime.Now.DayOfWeek == DayOfWeek.Saturday && DateTime.Now.Hour > 9) { DiscordChannel channel = await Client.GetChannelAsync(214523379766525963); if (channel != null && !weekend) { #if DEBUG #else await channel.SendMessageAsync("Yay it\'s finally the weekend! Hope everyone is having an amazing Saturday so far!\r\nhttp://i.imgur.com/VKDm9Pj.png"); #endif weekend = true; } } }
public async Task AnnounceEvent(CommandContext ctx, DateTime scheduledDate, DiscordMessage msg) { DiscordChannel channel = await ctx.Client.GetChannelAsync(UInt64.Parse(pugAnnouncementsChannel_ID)); DiscordMessage message = await channel.SendMessageAsync($"New Pug Event scheduled on {scheduledDate.ToShortDateString()} at {scheduledDate.ToShortTimeString()}!"); PugEvent e = new PugEvent(); e.Scheduled_Date = scheduledDate; e.Discord_Message_ID = message.Id.ToString(); await db.CreateEvent(e); await msg.ModifyAsync("The event has been scheduled!").ConfigureAwait(false); }
public async Task Say(CommandContext ctx, [Description("O canal para enviar a mensagem")] DiscordChannel channel, [Description("O texto á dizer"), RemainingText] string text) { if (ctx.Member.PermissionsIn(channel).HasFlag(Permissions.SendMessages)) { _ = ctx.Message.DeleteAsync(); await channel.TriggerTypingAsync(); await channel.SendMessageAsync(text); } else { await ctx.RespondAsync("Você não tem permissão para enviar mensagens neste canal"); } }
public async Task ProfanityClear(DiscordChannel channel, DiscordMessage userMsg) { var profanityEmbed = new DiscordEmbedBuilder() .WithTitle("Profanity found") .WithDescription("Your message contained profanity, couldn't send it") .WithColor(DiscordColor.Red) .Build(); var errSent = await channel.SendMessageAsync(profanityEmbed); await Task.Delay(1000); await channel.DeleteMessageAsync(errSent).ConfigureAwait(false); await channel.DeleteMessageAsync(userMsg).ConfigureAwait(false); }
public static async Task Greet(ulong greetingsChannelId, DiscordClient client, string name, string guildName) { if (greetingsChannelId > 0) { DiscordChannel channel = await client.GetChannelAsync(greetingsChannelId); if (channel != null) { string msg = "Yay! We have a new member :smile:\n\n"; msg += $"***Greetings {name}!***\nWelcome to {guildName}. "; msg += "I am the droid that coordinates operation events and I hope you have a great time here.\n\n"; msg += $"You can find out how to command me at <{Constants.InstrucionUrl}>"; await channel.SendMessageAsync(msg); } } }
private async Task Discord_GuildMemberAdded(DiscordClient client, DSharpPlus.EventArgs.GuildMemberAddEventArgs e) { try { DiscordChannel test = Bot.Discord.Guilds .First(x => x.Value.Name.ToLower().Contains("devry")).Value.Channels .FirstOrDefault(x => x.Value.Name.ToLower().Contains("welcome")) .Value; await test.SendMessageAsync(embed : GenerateWelcomeMessage(e.Member)); } catch (Exception ex) { Logger?.LogError($"An error occurred while trying to welcome '{e.Member.DisplayName}'\n\t{ex.Message}"); } }