public async Task Mute(IGuildUser user, TimeSpan duration, [Remainder] string reason) { var mute = await Database.UNSAFE_GetMute(user.Id); if (mute != null) { throw new Exception("User is already muted."); } if (user.IsStaff()) { throw new Exception("User is staff."); } var res = await MuteUser(Context.User, user, DateTimeOffset.UtcNow + duration, reason, false, false); await ReplyAsync($"{MentionUtils.MentionUser(user.Id)} muted until {res.ExpiryDate}."); }
public override bool Validate(ICommandContext context, IServiceProvider services) { string content = context.Message.Content; if (string.IsNullOrEmpty(content) || content.Length < 4 || content[0] != '<' || content[1] != '@' || content[^ 1] != '>') { return(false); } if (!MentionUtils.TryParseUser(content, out ulong userId)) { return(false); } if (userId == context.Client.CurrentUser.Id) { return(true); } return(false); }
public async Task TopListenersAsync() { var users = _db.Listens.Where(x => x.GuildId == Context.Guild.Id).ToList() .GroupBy(x => x.UserId) .OrderByDescending(x => x.Count()) .Take(10); var builder = new StringBuilder(); foreach (var item in users) { builder.AppendLine($"{MentionUtils.MentionUser(item.Key)} with **{item.Count()}** listens over **{item.GroupBy(x => x.TrackId).Count()}** tracks"); } await ReplyEmbedAsync(new EmbedBuilder() .WithTitle("Top 10 Listeners") .WithDescription(builder.ToString())); }
public async Task BuildGametestEmbed() { bool hasLink = _fields["link"] != "-" && _fields["link"] != "\"-\""; IMessageChannel channel = _client.GetGuild(_data.Configuration.GuildID).GetChannel(_data.Configuration.GametestChannelId) as IMessageChannel; Embed embed = new EmbedBuilder().WithTitle(_fields["projectName"]) .WithDescription(_fields["description"]) .WithAuthor(_message.Author) .WithColor(Color.Orange) .WithThumbnailUrl(_message.Author.EnsureAvatarUrl()) .AddField("Platforms", _fields["platforms"], true) .AddFieldConditional(hasLink, "Download Link", _fields["link"], true) .AddField("Contact via DM", MentionUtils.MentionUser(_message.Author.Id)) .Build(); await channel.SendMessageAsync(text : $"Submitted by {_message.Author.Mention}:", embed : embed); }
public static bool HasMentionPrefix(string content, ref int argPos, out ulong mentionId) { mentionId = 0; // Roughly ported from Discord.Commands.MessageExtensions.HasMentionPrefix if (string.IsNullOrEmpty(content) || content.Length <= 3 || (content[0] != '<' || content[1] != '@')) { return(false); } int num = content.IndexOf('>'); if (num == -1 || content.Length < num + 2 || content[num + 1] != ' ' || !MentionUtils.TryParseUser(content.Substring(0, num + 1), out mentionId)) { return(false); } argPos = num + 2; return(true); }
public async Task ListSonarr() { var s = "Channels:"; foreach (var chnl in SonarrService.Channels.Where(x => x.Channel.GuildId == Context.Guild.Id)) { s += $"\r\n {chnl.Channel.Id}, {MentionUtils.MentionChannel(chnl.Channel.Id)}"; if (chnl.ShowsPrivate) { s += " (private)"; } if (chnl.TagRequired.Count > 0) { s += " [" + string.Join(',', chnl.TagRequired) + "]"; } } await ReplyAsync(s); }
public virtual async Task UndoGameAsync(int gameNumber, ISocketMessageChannel lobbyChannel = null) { if (lobbyChannel == null) { lobbyChannel = Context.Channel as ISocketMessageChannel; } using (var db = new Database()) { var competition = db.GetOrCreateCompetition(Context.Guild.Id); var lobby = db.GetLobby(lobbyChannel); if (lobby == null) { await SimpleEmbedAsync("Channel is not a lobby.", Color.Red); return; } var game = db.GameResults.Where(x => x.GuildId == Context.Guild.Id && x.LobbyId == lobbyChannel.Id && x.GameId == gameNumber).FirstOrDefault(); if (game == null) { await SimpleEmbedAsync($"Game not found. Most recent game is {db.GetLatestGame(lobby)?.GameId}", Color.DarkBlue); return; } if (game.GameState != GameState.Decided) { await SimpleEmbedAsync("Game result is not decided and therefore cannot be undone.", Color.Red); return; } if (game.GameState == GameState.Draw) { await SimpleEmbedAsync("Cannot undo a draw.", Color.Red); return; } await UndoScoreUpdatesAsync(game, competition, db); await SimpleEmbedAsync($"Game #{gameNumber} in {MentionUtils.MentionChannel(lobbyChannel.Id)} Undone."); } }
public static EmbedBuilder printLeaderboard(SocketCommandContext Context, Color color) { var guildId = Context.Guild.Id; EmbedBuilder builder = new EmbedBuilder(); builder.Title = "\uD83C\uDFC6 Minigame Leaderboard"; builder.Color = color; DBC db = new DBC(); string query = $"SELECT * " + $" FROM {DBM_User_Data_Minigame.tableName} " + $" WHERE {DBM_User_Data_Minigame.Columns.id_guild}=@{DBM_User_Data_Minigame.Columns.id_guild} " + $" ORDER BY {DBM_User_Data_Minigame.Columns.score} desc " + $" LIMIT 10 "; Dictionary <string, object> colSelect = new Dictionary <string, object>(); colSelect[DBM_User_Data_Minigame.Columns.id_guild] = guildId.ToString(); DataTable dt = db.selectAll(query, colSelect); if (dt.Rows.Count >= 1) { string finalText = ""; int ctrRank = 1; builder.Description = "Here are the top 10 player with the highest score points:"; foreach (DataRow row in dt.Rows) { finalText += $"{ctrRank}. " + $"{MentionUtils.MentionUser(Convert.ToUInt64(row[DBM_User_Data_Minigame.Columns.id_user]))} : " + $"{row[DBM_User_Data_Minigame.Columns.score]} \n"; ctrRank++; } builder.AddField("[Rank]. Name & Score", finalText); } else { builder.Description = "Currently there are no leaderboard yet."; } return(builder); }
public async Task <RuntimeResult> ShowAutoroleAsync(AutoroleConfiguration autorole) { var paginatedEmbed = new PaginatedEmbed(_feedback, _interactivity, this.Context.User) { Appearance = PaginatedAppearanceOptions.Default }; var baseEmbed = paginatedEmbed.Appearance.CreateEmbedBase() .WithTitle("Autorole Configuration") .WithDescription(MentionUtils.MentionRole((ulong)autorole.DiscordRoleID)) .AddField("Requires confirmation", autorole.RequiresConfirmation, true) .AddField("Is enabled", autorole.IsEnabled, true); if (!autorole.Conditions.Any()) { baseEmbed.AddField("Conditions", "No conditions"); baseEmbed.Footer = null; await _feedback.SendEmbedAsync(this.Context.Channel, baseEmbed.Build()); return(RuntimeCommandResult.FromSuccess()); } var conditionFields = autorole.Conditions.Select ( c => new EmbedFieldBuilder() .WithName($"Condition #{autorole.Conditions.IndexOf(c)} (ID {c.ID})") .WithValue(c.GetDescriptiveUIText()) ); var pages = PageFactory.FromFields(conditionFields, pageBase: baseEmbed); paginatedEmbed.WithPages(pages); await _interactivity.SendInteractiveMessageAndDeleteAsync ( this.Context.Channel, paginatedEmbed, TimeSpan.FromMinutes(5) ); return(RuntimeCommandResult.FromSuccess()); }
public async Task LoggingChannel(IChannel channel) { var modelResult = await CheckStaffAndRetrieveModel(); if (modelResult.IsFailure()) { return; } var model = modelResult.Get(); model = model with { LogChannel = channel.Id }; await _repo.StoreGuildConfig(model); _logging.Info("Successfully updated Log Channel!"); await SendChannelMessage( $"Successfully update Log Channel to {MentionUtils.MentionChannel(model.LogChannel)}!"); }
public async Task BuildMentorEmbed() { string title = _hiring == HiringStatus.Hiring ? "Looking for a mentor" : "Looking to mentor"; Color color = _hiring == HiringStatus.Hiring ? Color.Green : Color.Blue; IMessageChannel channel = _client.GetGuild(_data.Configuration.GuildID).GetChannel(_data.Configuration.MentorChannelId) as IMessageChannel; Embed embed = new EmbedBuilder().WithTitle(title) .WithDescription(_fields["description"]) .WithAuthor(_message.Author) .WithColor(color) .WithThumbnailUrl(_message.Author.EnsureAvatarUrl()) .AddField("Areas of Interest", _fields["areasOfInterest"], true) .AddField("Rates", _fields["compensation"], true) .AddField("Contact via DM", MentionUtils.MentionUser(_message.Author.Id)) .Build(); await channel.SendMessageAsync(text : $"Submitted by {_message.Author.Mention}:", embed : embed); }
private async Task <SocketUser> GetMentionedUser(string mention, string usage, bool outputError = true, bool checkHistory = true) { if (Context.Message.MentionedUsers.Any()) { var socketUser = Context.Message.MentionedUsers.First(); var guildUser = Context.Guild.GetUser(socketUser.Id); if (guildUser != null) { return(guildUser); } else { return(socketUser); } } if (!MentionUtils.TryParseUser(mention, out ulong userId)) { if (outputError && usage is { })
public async Task PostToLogChannel(IMessage original, IEnumerable <IRole> mentionedRoles, IGuild guild) { ulong moderationLogChannelID = _data.Configuration.ModerationLogChannelID; if (moderationLogChannelID == 0) { throw new Exception("Invalid moderation log channel ID."); } ITextChannel channel = await guild.GetTextChannelAsync(moderationLogChannelID); string roleDisplay = string.Join(", ", mentionedRoles.Select(r => MentionUtils.MentionRole(r.Id).Envelop("**"))); await channel.SendMessageAsync(string.Empty, false, new EmbedBuilder() .WithTitle("Role Mention") .WithColor(Color.Orange) .WithDescription($"{original.Author.Mention} mentioned {roleDisplay} in their [message]({original.GetJumpUrl()}).") .Build()); }
public override async Task <TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services) { input = input.Trim(',', '.'); var baseResult = await base.ReadAsync(context, input, services); if (baseResult.IsSuccess) { return(TypeReaderResult.FromSuccess(new DiscordUserOrMessageAuthorEntity(((IUser)baseResult.BestMatch).Id))); } if (MentionUtils.TryParseUser(input, out var userId)) { return(SnowflakeUtilities.IsValidSnowflake(userId) ? GetUserResult(userId) : GetInvalidSnowflakeResult()); } // The base class covers users that are in the guild, and the previous condition covers mentioning users that are not in the guild. // At this point, it's one of the following: // - A snowflake for a message in the guild. // - A snowflake for a user not in the guild. // - Something we can't handle. if (ulong.TryParse(input, out var snowflake)) { if (!SnowflakeUtilities.IsValidSnowflake(snowflake)) { return(GetInvalidSnowflakeResult()); } var messageService = services.GetRequiredService <IMessageService>(); if (await messageService.FindMessageAsync(context.Guild.Id, snowflake) is { } message) { return(GetMessageAuthorResult(message.Author.Id, message.Channel.Id, message.Id)); } // At this point, our best guess is that the snowflake is for a user who is not in the guild. return(GetUserResult(snowflake)); } return(GetBadInputResult()); }
public async Task ClubStats(string teamName, string league) { //var options = new RequestOptions { Timeout = 2 }; //await Context.Message.DeleteAsync(options); EmbedBuilder embed = new EmbedBuilder(); if (Context.Channel.Id == Convert.ToUInt64(Environment.GetEnvironmentVariable("stats_channel"))) { TeamInfo.ClubInfo(league, teamName, ref embed); await ReplyAsync("", embed : embed.Build()); } else { await ReplyAsync( $"{Context.User.Mention} you are using the command in the wrong channel, try again in " + $"{MentionUtils.MentionChannel(Convert.ToUInt64(Environment.GetEnvironmentVariable("stats_channel")))}"); } }
public BotStatus() { arrPlayingWith.Add(new List <object> { "with Doremi", $"I'm playing with {MentionUtils.MentionUser(Doremi.Id)} right now.", UserStatus.Online }); arrPlayingWith.Add(new List <object> { "with Hazuki", $"I'm playing with {MentionUtils.MentionUser(Hazuki.Id)} right now.", UserStatus.Online }); arrPlayingWith.Add(new List <object> { "with Aiko", $"I'm playing with {MentionUtils.MentionUser(Aiko.Id)} right now. " + "Please come and join us to make takoyaki together, will you?", UserStatus.Online }); arrPlayingWith.Add(new List <object> { "with Onpu", $"I'm playing with {MentionUtils.MentionUser(Onpu.Id)} right now.", UserStatus.Online }); arrPlayingWith.Add(new List <object> { "with Momoko", $"I'm playing with {MentionUtils.MentionUser(Momoko.Id)} right now.", UserStatus.Online }); }
public async Task MonitorList() { int pageSize = 5; Expression <Func <StreamSubscription, bool> > streamSubscriptionPredicate = (i => i.DiscordGuild.DiscordId == Context.Guild.Id ); int pageCount = await _work.SubscriptionRepository.GetPageCountAsync(streamSubscriptionPredicate, pageSize); List <EmbedFieldBuilder> subscriptions = new List <EmbedFieldBuilder>(); for (int i = 1; i < pageCount + 1; i++) { var streamSubscriptions = await _work.SubscriptionRepository.FindAsync(streamSubscriptionPredicate, i, pageSize); if (streamSubscriptions.Count() == 0) { continue; } foreach (StreamSubscription streamSubscription in streamSubscriptions) { string fieldValue = ""; fieldValue += $"Channel: {MentionUtils.MentionChannel(streamSubscription.DiscordChannel.DiscordId)}\n"; fieldValue += $"Role: {streamSubscription.DiscordRole?.Name?.Replace("@everyone", "everyone") ?? "none"}\n"; fieldValue += $"Message: {streamSubscription.Message}"; EmbedFieldBuilder fieldBuilder = new EmbedFieldBuilder() .WithIsInline(false) .WithName(streamSubscription.User.ProfileURL) .WithValue(fieldValue); subscriptions.Add(fieldBuilder); } } PaginatedMessage paginatedMessage = new PaginatedMessage { Color = Color.LightGrey, Title = "Stream Subscriptions", Pages = subscriptions }; await PagedReplyAsync(paginatedMessage); }
private string CreateDeclarationDataMessage(ClanData clanData) { var reservationDataList = new MySQLReservationController().LoadBossLapReservationData(clanData); var reservationIDList = reservationDataList .OrderBy(d => d.CreateDateTime) .Select(d => d.PlayerData.UserID) .ToList(); var messageData = ""; foreach (var reservationID in reservationIDList) { messageData += MentionUtils.MentionUser(reservationID); messageData += " "; } return(messageData); }
public async Task PlayersInGameLobby() { if (PendingGameService.PendingGames.Count == 0) { await ReplyAsync(ErrorView.NotFound()); } else { PendingGame game = PendingGameService.PendingGames.FirstOrDefault(); if (game.Users.Any()) { string message = string.Join(", ", game.Users.Select(u => MentionUtils.MentionUser(u.Id))); await ReplyAsync(message); } else { await ReplyAsync("Game lobby is empty."); } } }
protected async Task <IUserMessage> GetSuggestionFromUserAsync(IMessageChannel channel, IUser author) { var tempMsg = await channel.SendMessageAsync(MentionUtils.MentionUser(Context.User.Id) + " Type your suggestion here..."); var result = await NextMessageAsync(GetCriteria(channel), TimeSpan.FromMinutes(5)); await tempMsg.DeleteAsync(); await(result?.DeleteAsync() ?? Task.CompletedTask); if (result == null) { return(null); } var suggestion = result.Content; return(await ConfirmSuggestionFromUserAsync(channel, author, suggestion)); }
public override async ValueTask <TypeParserResult <RestUser> > ParseAsync( Parameter parameter, string value, CommandContext context) { var ctx = context.Cast <VolteContext>(); RestUser user = default; if (ulong.TryParse(value, out var id) || MentionUtils.TryParseUser(value, out id)) { user = await ctx.Client.Shards.First().Rest.GetUserAsync(id); } return(user is null ? TypeParserResult <RestUser> .Failed("User not found.") : TypeParserResult <RestUser> .Successful(user)); }
public static IEnumerable <SocketUser> ParseUsers(DiscordSocketClient discord, string text, SocketGuild guild) { if (guild != null) { ulong roleId; if (MentionUtils.TryParseRole(text, out roleId)) { return(guild.Users.Where(u => u.Roles.Any(r => r.Id == roleId))); } } ulong channelId; if (MentionUtils.TryParseChannel(text, out channelId)) { return(discord.GetChannel(channelId).Users); } var user = ParseUser(discord, text); return(user != null ? new[] { user } : null); }
private string GetAuthorText(SocketCommandContext context) { ulong id = _einherjiOptions.AuthorID; if (!context.IsPrivate) { SocketGuildUser guildUser = context.Guild.GetUser(id); if (guildUser != null) { return(MentionUtils.MentionUser(id)); } } SocketUser user = context.Client.GetUser(id); if (user != null) { return($"{user.Username}#{user.Discriminator}"); } return("TehGM"); }
public async Task AppendGuildParticipationAsync(StringBuilder stringBuilder, SocketGuild guild) { var weekTotal = await MessageRepository.GetTotalMessageCountAsync(guild.Id, TimeSpan.FromDays(7)); var monthTotal = await MessageRepository.GetTotalMessageCountAsync(guild.Id, TimeSpan.FromDays(30)); var channelCounts = await MessageRepository.GetTotalMessageCountByChannelAsync(guild.Id, TimeSpan.FromDays(30)); var orderedChannelCounts = channelCounts.OrderByDescending(x => x.Value); var mostActiveChannel = orderedChannelCounts.First(); var leastActiveChannel = orderedChannelCounts.Last(); stringBuilder .AppendLine(Format.Bold("\u276F Guild Participation")) .AppendLine($"Last 7 days: {"message".ToQuantity(weekTotal, "n0")}") .AppendLine($"Last 30 days: {"message".ToQuantity(monthTotal, "n0")}") .AppendLine($"Avg. per day: {"message".ToQuantity(monthTotal / 30, "n0")}") .AppendLine($"Most active channel: {MentionUtils.MentionChannel(mostActiveChannel.Key)} ({"message".ToQuantity(mostActiveChannel.Value, "n0")} in 30 days)") .AppendLine(); }
public static Task <Channel> MatchChannel(this Context ctx) { if (!MentionUtils.TryParseChannel(ctx.PeekArgument(), out var id)) { return(Task.FromResult <Channel>(null)); } if (!ctx.Cache.TryGetChannel(id, out var channel)) { return(Task.FromResult <Channel>(null)); } if (!DiscordUtils.IsValidGuildChannel(channel)) { return(Task.FromResult <Channel>(null)); } ctx.PopArgument(); return(Task.FromResult(channel)); }
private string GetUserInfo(string userid) { if (!MentionUtils.TryParseUser(userid, out var id)) { return("I don't know who that is"); } var users = (from g in _client.Guilds let gu = g.GetUser(id) select gu).ToArray(); if (users.Length == 1) { return(GetUserInfo(users.Single())); } else { return(GetUserInfo(_client.GetUser(id))); } }
public async Task TimeBanAsync(string user, int day, int hour, int minutes, int seconds) { var id = MentionUtils.ParseUser(user); var ban = Context.Guild.GetUser(id); await Context.Message.AddReactionAsync(new Emoji("✅")); var ts = new TimeSpan(day, hour, minutes, seconds); await Task.Run(async() => { try { await Task.Delay((int)ts.TotalMilliseconds); } catch (Exception e) { await ReplyAsync(e.Message); } await ReplyAsync("DONE"); }); }
public async Task BuildHobbyNotHiringEmbed() { IMessageChannel channel = _client.GetGuild(_data.Configuration.GuildID).GetChannel(_data.Configuration.HobbyChannelId) as IMessageChannel; _fields["portfolio"] = MoveLinksToNewline(); Embed embed = new EmbedBuilder().WithTitle("Looking for work") .WithDescription(_fields["description"]) .WithAuthor(_message.Author) .WithColor(Color.Blue) .WithThumbnailUrl(_message.Author.EnsureAvatarUrl()) .AddField("My Role(s)", _fields["roles"], true) .AddField("My Skills", _fields["skills"], true) .AddField("Previous Projects/Portfolio", _fields["portfolio"], false) .AddField("Experience in the field", _fields["experience"], true) .AddField("Contact via DM", MentionUtils.MentionUser(_message.Author.Id)) .Build(); await channel.SendMessageAsync(text : $"Submitted by {_message.Author.Mention}:", embed : embed); }
public async Task Bans() { var players = Service.GetPlayers(x => x.GuildId == Context.Guild.Id && x.IsBanned); if (players.Length == 0) { await SimpleEmbedAsync("There aren't any banned players.", Color.Blue); return; } var pages = players.OrderBy(x => x.CurrentBan.RemainingTime).SplitList(20).Select(x => { var page = new ReactivePage(); page.Description = string.Join("\n", x.Select(p => $"{MentionUtils.MentionUser(p.UserId)} - {p.CurrentBan.ExpiryTime.ToString("dd MMM yyyy")} {p.CurrentBan.ExpiryTime.ToShortTimeString()} in {p.CurrentBan.RemainingTime.GetReadableLength()}")); return(page); }); var pager = new ReactivePager(pages); await PagedReplyAsync(pager.ToCallBack().WithDefaultPagerCallbacks()); }
public static async Task <Channel> MatchChannel(this Context ctx) { if (!MentionUtils.TryParseChannel(ctx.PeekArgument(), out var id)) { return(null); } if (!ctx.Cache.TryGetChannel(id, out var channel)) { return(null); } if (!(channel.Type == Channel.ChannelType.GuildText || channel.Type == Channel.ChannelType.GuildText)) { return(null); } ctx.PopArgument(); return(channel); }