public virtual async Task CompetitionInfo()
        {
            using (var db = new Database())
            {
                var comp  = db.GetOrCreateCompetition(Context.Guild.Id);
                var embed = new EmbedBuilder
                {
                    Color = Color.Blue
                };
                embed.AddField("Roles",
                               $"**Register Role:** {(comp.RegisteredRankId == null ? "N/A" : MentionUtils.MentionRole(comp.RegisteredRankId.Value))}\n" +
                               $"**Admin Role:** {(comp.AdminRole == null ? "N/A" : MentionUtils.MentionRole(comp.AdminRole.Value))}\n" +
                               $"**Moderator Role:** {(comp.ModeratorRole == null ? "N/A" : MentionUtils.MentionRole(comp.ModeratorRole.Value))}");
                embed.AddField("Options",
                               $"**Allow Multi-Queuing:** {comp.AllowMultiQueueing}\n" +
                               $"**Allow Negative Score:** {comp.AllowNegativeScore}\n" +
                               $"**Update Nicknames:** {comp.UpdateNames}\n" +
                               $"**Display Error Messages:** {comp.DisplayErrors}\n" +
                               $"**Allow Self Rename:** {comp.AllowSelfRename}\n" +
                               $"**Allow Re-registering:** {comp.AllowReRegister}\n" +
                               $"**Requeue Delay:** {(comp.RequeueDelay.HasValue ? comp.RequeueDelay.Value.GetReadableLength() : "None")}");

                //embed.AddField("Stats",
                //            $"**Registered User Count:** {comp.RegistrationCount}\n" +
                //            $"**Manual Game Count:** {comp.ManualGameCounter}");
                embed.AddField("Formatting", $"**Nickname Format:** {comp.NameFormat}\n" +
                               $"**Registration Message:** {comp.RegisterMessageTemplate}");
                embed.AddField("Rank Info",
                               $"**Default Win Amount:** +{comp.DefaultWinModifier}\n" +
                               $"**Default Loss Amount:** -{comp.DefaultLossModifier}\n" +
                               $"**Default Points On Register:** {comp.DefaultRegisterScore}\n" +
                               $"For rank info use the `ranks` command");
                await ReplyAsync(embed);
            }
        }
        public async Task RemindSelfFeedbackAll()
        {
            //var channels = this.Context.Guild.GetFeedbackCategory().Channels.Select(x => x as ITextChannel);
            //foreach (var channel in channels)
            //{

            var channel = this.Context.Guild.GetChannel(OnlyRaidersId) as ITextChannel;

            var message = $"{MentionUtils.MentionRole(FeedbackCommon.MainRaiderRoleId)} {MentionUtils.MentionRole(FeedbackCommon.TrialRoleId)} With raid complete for the week please take this opportunity to review logs and evaluate your performance. \n" +
                          $"Some things to look for while reviewing your performance: \n" +
                          $"- Things you did well and want to continue doing\n" +
                          $"- Causes of early deaths, and how they can be prevented.\n" +
                          $"- Rotational/CD optimizations.\n" +
                          $"Feel free to submit these items via the feedback tool to show your thought process.\n" +
                          $"Additionally, to help the team get better please: \n" +
                          $"- Post any strategy changes or adjustments that you think would be beneficial for bosses either to the boss channel or directly to an officer.\n" +
                          $"- Post any feedback for others in {MentionUtils.MentionChannel(FeedbackCommon.TeamFeedbackChannelId)}. Remember to @mention the feedback target!\n\n" +
                          $"Remember the goal of this exercise is to improve performance over time, and fix issues, not create excuses or lay blame.";

            var options = new RequestOptions()
            {
                RetryMode = RetryMode.RetryRatelimit
            };
            await channel.SendMessageAsync(message, options : options);
        }
Beispiel #3
0
            public async Task <RuntimeResult> Default
            (
                IRole discordRole,
                string permissionName,
                [OverrideTypeReader(typeof(HumanizerEnumTypeReader <PermissionTarget>))]
                PermissionTarget revokedTarget = PermissionTarget.Self
            )
            {
                var getPermissionResult = _permissionRegistry.GetPermission(permissionName);

                if (!getPermissionResult.IsSuccess)
                {
                    return(getPermissionResult.ToRuntimeResult());
                }

                var permission             = getPermissionResult.Entity;
                var revokePermissionResult = await _permissions.RevokePermissionAsync
                                             (
                    discordRole,
                    permission,
                    revokedTarget
                                             );

                if (!revokePermissionResult.IsSuccess)
                {
                    return(revokePermissionResult.ToRuntimeResult());
                }

                return(RuntimeCommandResult.FromSuccess
                       (
                           $"{permission.FriendlyName} revoked from {MentionUtils.MentionRole(discordRole.Id)}."
                       ));
            }
Beispiel #4
0
        private EmbedBuilder AddGuildUserInfo(EmbedBuilder embed, SocketGuildUser user)
        {
            // add nickname if present
            if (user.Nickname != null)
            {
                embed.AddField("Guild nickname", user.Nickname, true)
                .WithAuthor($"Intel on {user.Nickname}", _client.CurrentUser.GetSafeAvatarUrl());
            }

            // get roles, respecting hierarchy
            IOrderedEnumerable <SocketRole> roles = user.Roles.Where(r => r.Id != user.Guild.EveryoneRole.Id).OrderByDescending(r => r.Position);

            if (roles.Any())
            {
                embed.AddField("Roles", string.Join(", ", roles.Select(r => MentionUtils.MentionRole(r.Id))), true);
            }
            else
            {
                embed.AddField("Roles", "-");
            }
            embed.Color = roles.FirstOrDefault(r => r.Color != Color.Default)?.Color;

            // add joined time
            if (user.JoinedAt != null)
            {
                embed.AddField("Time in this guild", (DateTimeOffset.UtcNow - user.JoinedAt.Value).ToLongFriendlyString(), true);
            }
            return(embed);
        }
        public async Task FreeGameNotificationTestAnnounceAsync([Remainder][Summary("Message to announce.")] string message)
        {
            var clientId = Context.Client.CurrentUser.Id.ToString();
            var guildId  = Context.Guild.Id.ToString();

            var freeGameNotificationModel = await SQLiteService.SQLiteAsyncConnection.Table <FreeGameNotificationModel>().Where(a => a.ClientId == clientId && a.GuildId == guildId).FirstOrDefaultAsync();

            if (freeGameNotificationModel == null)
            {
                return;
            }

            if (!Context.Guild.GetUser(Context.Client.CurrentUser.Id).GuildPermissions.SendMessages)
            {
                return;
            }

            var textChannel = Context.Guild.GetTextChannel(Convert.ToUInt64(freeGameNotificationModel.ChannelId));

            if (freeGameNotificationModel.RoleId == Context.Guild.Id.ToString())
            {
                await textChannel.SendMessageAsync($"@everyone {message}");
            }
            else if (!string.IsNullOrEmpty(freeGameNotificationModel.RoleId))
            {
                await textChannel.SendMessageAsync($"{MentionUtils.MentionRole(Convert.ToUInt64(freeGameNotificationModel.RoleId))} {message}");
            }
            else
            {
                await textChannel.SendMessageAsync(message);
            }
        }
        private async Task <Embed> FormatPromotionNotification(long promotionActionId, PromotionActionCreationData data)
        {
            var promotionAction = await PromotionsService.GetPromotionActionSummaryAsync(promotionActionId);

            var targetCampaign = promotionAction.Campaign ?? promotionAction.NewComment.Campaign;

            var embed = new EmbedBuilder();

            if (promotionAction.Type != PromotionActionType.CampaignClosed)
            {
                return(null);
            }
            if (targetCampaign.Outcome != PromotionCampaignOutcome.Accepted)
            {
                return(null);
            }

            var boldName = $"**{targetCampaign.Subject.Username}#{targetCampaign.Subject.Discriminator}**";
            var boldRole = $"**{MentionUtils.MentionRole(targetCampaign.TargetRole.Id)}**";

            var subject = await UserService.GetUserInformationAsync(data.GuildId, targetCampaign.Subject.Id);

            embed = embed
                    .WithTitle("The campaign is over!")
                    .WithDescription($"Staff accepted the campaign, and {boldName} was promoted to {boldRole}! 🎉")
                    .WithAuthor(subject)
                    .WithFooter("See more at https://mod.gg/promotions");

            return(embed.Build());
        }
        public async Task List()
        {
            var roles = await DesignatedRoleService.GetDesignatedRolesAsync(Context.Guild.Id);

            var builder = new EmbedBuilder()
            {
                Title     = "Assigned Role Designations",
                Url       = "https://mod.gg/config/roles",
                Color     = Color.Gold,
                Timestamp = DateTimeOffset.UtcNow
            };

            foreach (var type in Enum.GetValues(typeof(DesignatedRoleType)).Cast <DesignatedRoleType>())
            {
                var designatedRoles = roles
                                      .Where(x => x.Type == type)
                                      .OrderByDescending(x => x.Role.Position)
                                      .ThenBy(x => x.Role.Id)
                                      .ToArray();

                builder.AddField(new EmbedFieldBuilder()
                {
                    Name  = Format.Bold(_designatedRoleTypeRenderings[type]),
                    Value = (designatedRoles.Length == 0)
                        ? Format.Italics("No roles assigned")
                        : designatedRoles
                            .Select(x => MentionUtils.MentionRole(x.Role.Id))
                            .Aggregate(string.Empty, (x, y) => $"{x}\n{y}"),
                    IsInline = false
                });
            }

            await ReplyAsync(string.Empty, false, builder.Build());
        }
Beispiel #8
0
        /// <summary>
        /// Formats a notification string with the necessary parameters
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static string GetNotificationMessage(ILiveBotStream stream, StreamSubscription subscription, ILiveBotUser user = null, ILiveBotGame game = null)
        {
            string RoleMention = "";

            if (subscription.DiscordRole != null)
            {
                if (subscription.DiscordRole.Name == "@everyone")
                {
                    RoleMention = "@everyone";
                }
                else
                {
                    RoleMention = MentionUtils.MentionRole(subscription.DiscordRole.DiscordId);
                }
            }

            var tempUser = user ?? stream.User;
            var tempGame = game ?? stream.Game;

            return(subscription.Message
                   .Replace("{Name}", EscapeSpecialDiscordCharacters(tempUser.DisplayName), ignoreCase: true, culture: CultureInfo.CurrentCulture)
                   .Replace("{Username}", EscapeSpecialDiscordCharacters(tempUser.DisplayName), ignoreCase: true, culture: CultureInfo.CurrentCulture)
                   .Replace("{Game}", EscapeSpecialDiscordCharacters(tempGame.Name), ignoreCase: true, culture: CultureInfo.CurrentCulture)
                   .Replace("{Title}", EscapeSpecialDiscordCharacters(stream.Title), ignoreCase: true, culture: CultureInfo.CurrentCulture)
                   .Replace("{URL}", stream.StreamURL ?? "", ignoreCase: true, culture: CultureInfo.CurrentCulture)
                   .Replace("{Role}", RoleMention, ignoreCase: true, culture: CultureInfo.CurrentCulture)
                   .Trim());
        }
Beispiel #9
0
        private async Task NotifySubscriber(TuckContext context, Subscription subscription)
        {
            var channel = Context.Client.GetChannel(subscription.ChannelId) as ISocketMessageChannel;
            var message = await channel.SendMessageAsync(string.Format(
                                                             "{0}World buff list has been updated. ({1})",
                                                             // SubscriberAlert can never be null here either.. So fallback is just to cast to int(64)
                                                             MentionUtils.MentionRole(subscription.SubscriberAlert ?? 0) + ": ",
                                                             // CultureInfo param should be refactored to EU/NA/etc when multi-realm support is added.
                                                             DateTime.Now.ToString("HH:mm", new System.Globalization.CultureInfo("fr-FR"))
                                                             ));

            // If a previous alert exists, delete it.
            ulong lastAlert = subscription.LastAlert ?? 0;

            if (lastAlert != 0)
            {
                var lastMsg = await channel.GetMessageAsync(lastAlert);

                if (lastMsg != null)
                {
                    await lastMsg.DeleteAsync();
                }
            }

            // Store the new message Id.
            subscription.LastAlert = message.Id;
            context.Update(subscription);
            await context.SaveChangesAsync();
        }
        private Embed BuildSetupEmbed()
        {
            var setupPayload = new StringBuilder();

            setupPayload.AppendLine($"{new Emoji("0️⃣✅")} Command prefix (current: `{_behaviourConfigurationService.GetPrefix()}`)");

            var staffRole = _behaviourConfigurationService.GetStaffRoleId();

            setupPayload.AppendLine(staffRole is null
                ? $"{new Emoji("1️⃣🟥")} Staff role"
                : $"{new Emoji("1️⃣✅")} Staff role ({MentionUtils.MentionRole(staffRole.Value)})");

            var categoryId = _behaviourConfigurationService.GetCategoryId();

            setupPayload.AppendLine(categoryId is null
                ? $"{new Emoji("2️⃣🟥")} Category"
                : $"{new Emoji("2️⃣✅")} Category ({MentionUtils.MentionChannel(categoryId.Value)})");

            var logChannelId = _behaviourConfigurationService.GetLogChannelId();

            setupPayload.AppendLine(logChannelId is null
                ? $"{new Emoji("3️⃣🟥")} Log channel"
                : $"{new Emoji("3️⃣✅")} Log channel ({MentionUtils.MentionChannel(logChannelId.Value)})");

            var setupEmbed = new EmbedBuilder()
                             .WithTitle("D2M Setup")
                             .WithDescription(setupPayload.ToString());

            return(setupEmbed.Build());
        }
        public async Task Run(DateTime time, [Remainder] string location)
        {
            ulong roleId;
            List <EmbedFieldBuilder> fields = new List <EmbedFieldBuilder>();

            fields.Add(new EmbedFieldBuilder
            {
                Name     = "Location",
                Value    = location,
                IsInline = true
            });

            fields.Add(new EmbedFieldBuilder
            {
                Name     = "Time",
                Value    = time.ToShortTimeString(),
                IsInline = true
            });

            EmbedBuilder embed = new EmbedBuilder
            {
                Title        = "Calling all fat cunts",
                Description  = "Meet at maccas to eat maccas.",
                Fields       = fields,
                Color        = Color.Red,
                ThumbnailUrl = "https://cdn.discordapp.com/attachments/559700127275679762/762252098263449600/McDonalds-Logo.png"
            };

            roleId = CreateRoleIfRequired(Context).Result.Id;

            await Context.Channel.SendMessageAsync(embed : embed.Build());

            await Context.Channel.SendMessageAsync($"{MentionUtils.MentionRole(roleId)} ^^");
        }
Beispiel #12
0
        private async Task SendMessageToDestination(Embed embed, SocketGuildChannel targetChannel, ulong?roleId = null, bool removeIvDetails = true, string pokemonName = "")
        {
            var newDescription = embed.Description;

            if (removeIvDetails)
            {
                string[] descriptionLines = newDescription.Split("\n");
                if (descriptionLines.Length == 3)
                {
                    newDescription = String.Format("{0}{1}{2}{1}{3}",
                                                   descriptionLines[2],
                                                   Environment.NewLine,
                                                   "For IV and Moveset Info, sign",
                                                   "up for the Livemap in #livemap"
                                                   );
                }
                else
                {
                    newDescription = String.Empty; //something bad happened, or something changed
                }
            }
            else
            {
                newDescription = String.Format("{0}",
                                               newDescription);
            }

            EmbedBuilder eb = new EmbedBuilder()
                              .WithTitle(embed.Title)
                              .WithDescription(newDescription)
                              .WithUrl(embed.Url);

            if (embed.Color.HasValue)
            {
                eb.WithColor(embed.Color.Value);
            }
            if (embed.Thumbnail.HasValue)
            {
                eb.WithThumbnailUrl(embed.Thumbnail.Value.Url);
            }
            if (embed.Image.HasValue)
            {
                eb.WithImageUrl(embed.Image.Value.Url);
            }

            //Mentions
            if (roleId.HasValue)
            {
                var message = MentionUtils.MentionRole(roleId.Value);
                if (!String.IsNullOrEmpty(pokemonName))
                {
                    message += String.Format(" {0}", pokemonName);
                }

                await(targetChannel as ISocketMessageChannel).SendMessageAsync(message);
            }

            //Send Main Message
            await(targetChannel as ISocketMessageChannel).SendMessageAsync(String.Empty, embed: eb);
        }
Beispiel #13
0
        private async void SongTimerOnElapsed(object sender, ElapsedEventArgs e)
        {
            if (notifierIsInProgress)
            {
                return;
            }

            notifierIsInProgress = true;
            try
            {
                string song = await GetUriAsync(songInfoUri);

                SongResponseDto resp = JsonConvert.DeserializeObject <SongResponseDto>(song);


                string title = resp.CurrentSong.Split('/').Last();
                if (title.Contains("&title="))
                {
                    title = title.Split(new String[] { "&title=" }, StringSplitOptions.None).Last();
                }

                if (lastResponse != title)
                {
                    await _client.SetGameAsync(title, "https://www.twitch.tv/ascalot1", ActivityType.Streaming);

                    lastResponse = title;
                }

                string mentionString = "";
                triggersList.ForEach(async itm =>
                {
                    if (resp.CurrentSong.ToLower().Contains(itm.ToLower()) || resp.Tags.ToLower().Contains(itm.ToLower()))
                    {
                        var role = _guild.Roles.FirstOrDefault(role => role.Name == itm);
                        if (role != null)
                        {
                            mentionString += MentionUtils.MentionRole(role.Id) + " ";
                        }
                    }
                });

                if (mentionString != "")
                {
                    string msg = $"{mentionString} на канале играет: {title}";
                    if (msg != lastAnnounceMsg)
                    {
                        lastAnnounceMsg = msg;
                        await _announceChannel.SendMessageAsync(msg);
                    }
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }

            notifierIsInProgress = false;
        }
        public static string GetRoleMentions(this IEnumerable <IRole> roles)
        {
            var enumerable = roles.ToList();

            if (!enumerable.Any())
            {
                return("-");
            }
            return(enumerable.Select(x => MentionUtils.MentionRole(x.Id)).Aggregate((acc, elem) => $"{acc}, {elem}"));
        }
Beispiel #15
0
        public void WS_CovidStatsReady(COVID stats)
        {
            Task.Run(async() => {
                DateTime dateTime    = stats.date;
                DateTime yesterday   = dateTime.AddDays(-1);
                COVID yesterdayStats = await Data.APIHttpRequest <COVID>($"https://api.anastarawneh.tech/v1/covid-19/{yesterday.Year}/{yesterday.Month}/{yesterday.Day}", "GET");
                EmbedBuilder embed   = new EmbedBuilder();
                embed.WithTitle($"COVID-19 stats for {dateTime:dd/MM/yyyy}");
                embed.WithColor(Constants.IColors.Blurple);
                embed.WithDescription($"{stats.localCases} new local cases, {stats.deaths} casualties and {stats.recoveries} recoveries.");
                if (stats.cities.Total() != 0)
                {
                    embed.AddField("Amman", stats.cities.amman, true);
                    embed.AddField("Irbid", stats.cities.irbid, true);
                    embed.AddField("Zarqa", stats.cities.zarqa, true);
                    embed.AddField("Mafraq", stats.cities.mafraq, true);
                    embed.AddField("Ajloun", stats.cities.ajloun, true);
                    embed.AddField("Jerash", stats.cities.jerash, true);
                    embed.AddField("Madaba", stats.cities.madaba, true);
                    embed.AddField("Balqa", stats.cities.balqa, true);
                    embed.AddField("Karak", stats.cities.karak, true);
                    embed.AddField("Tafileh", stats.cities.tafileh, true);
                    embed.AddField("Ma'an", stats.cities.maan, true);
                    embed.AddField("Aqaba", stats.cities.aqaba, true);
                }
                decimal percentage = (decimal)stats.cases / (decimal)stats.tests * 100m;
                string moreStats   =
                    $"Total cases: {stats.totalCases}\n" +
                    $"Total casualties: {stats.totalDeaths}\n" +
                    $"Total recoveries: {stats.totalRecoveries}\n" +
                    $"Foreign cases: {stats.cases - stats.localCases}\n" +
                    $"Hospitalized cases today: {stats.hospitalized}, total: {stats.totalHospitalized}\n" +
                    $"Recovery distribution: {stats.homeRecoveries} at home, {stats.hospitalRecoveries} from hospitals\n" +
                    $"Tests today: {stats.tests}, total: {stats.totalTests}\n" +
                    $"Positive test percentage: {Math.Round(percentage, 2)}%\n" +
                    $"Active cases: {stats.active}";
                if (yesterdayStats.critical != 0)
                {
                    moreStats += $"\nYesterday's critical cases: {yesterdayStats.critical}";
                }
                if (stats.vaxRegistered != 0)
                {
                    moreStats +=
                        $"\nvaccine.jo registrants: {stats.vaxRegistered}\n" +
                        $"Vaccinated - First dose: {stats.vaxFirstDose}\n" +
                        $"Vaccinated - Second dose: {stats.vaxSecondDose}";
                }
                embed.AddField("More stats", moreStats);

                SocketTextChannel channel = Constants.IGuilds.Jordan(_client).GetTextChannel(Data.GetChnlId("covid-19-stats"));
                RestUserMessage msg       = await channel.SendMessageAsync(MentionUtils.MentionRole(773576613605933087), false, embed.Build());
                await msg.CrosspostAsync();
            });
        }
Beispiel #16
0
        public async Task DisplayRaidboss()
        {
            ulong id   = 794883940111351808;                        // 3
            var   chnl = _client.GetChannel(id) as IMessageChannel; // 4

            var eb = new EmbedBuilder();

            eb.WithTitle(currentraidboss.Name + "\n Stats:");
            eb.WithDescription(currentraidboss.Description + "\n" + DisplayCurrentRaidBossStats());
            eb.WithThumbnailUrl(currentraidboss.ImageURL);
            eb.Color = Color.Magenta;

            await chnl.SendMessageAsync(MentionUtils.MentionRole(794883416498634763), false, eb.Build());
        }
Beispiel #17
0
        public override async Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context,
                                                                              ParameterInfo parameter, object value, IServiceProvider services)
        {
            var guild = await context.Client.GetGuildAsync(DiscordSettings.GuildId);

            var guildUser = await guild.GetUserAsync(((IUser)value).Id);

            if (guildUser.RoleIds.Contains(RoleId))
            {
                return(PreconditionResult.FromSuccess());
            }

            return(PreconditionResult.FromError($"This command can only target a {MentionUtils.MentionRole(RoleId)}."));
        }
Beispiel #18
0
        private async Task ProcessRaidMessage(SocketUserMessage msg)
        {
            var disableMessages = false;

            if (Convert.ToBoolean(_config["debug:DisableRaid"]))
            {
                disableMessages = true;
            }

            var embed            = (msg.Embeds as IReadOnlyList <Embed>)[0];
            var descriptionLines = embed.Description.Split("\n");

            var             pattern = @"\*\*Level:\*\*\s(?<Level>\d+)";
            Regex           rgx     = new Regex(pattern, RegexOptions.IgnoreCase);
            MatchCollection matches = rgx.Matches(descriptionLines[0]);

            if (matches.Count != 1)
            {
                Console.WriteLine("Regex Failed for Raid: " + descriptionLines[0]);
                return;// Task.CompletedTask; //Regex failed
            }

            var raidLevel     = Convert.ToInt32(matches[0].Groups["Level"].Value);
            var raidChannelId = _raidMap[raidLevel];

            var targetChannel = (msg.Channel as SocketGuildChannel).Guild.GetChannel(raidChannelId);

            if (targetChannel == null)
            {
                return;
            }

            var pokemonName = embed.Title.Substring(0, embed.Title.IndexOf(" "));
            var roleName    = String.Format("{0}-r", pokemonName);
            var raidRoleId  = GetRole((msg.Channel as SocketGuildChannel).Guild.Roles, roleName);

            if (raidRoleId.HasValue && !disableMessages)
            {
                await(targetChannel as ISocketMessageChannel).SendMessageAsync(MentionUtils.MentionRole(raidRoleId.Value));
            }

            if (!disableMessages)
            {
                await(targetChannel as ISocketMessageChannel).SendMessageAsync(String.Empty, embed: embed);
            }

            //range
            await _rangeRouter.RoutePokemon(msg, embed, pokemonName);
        }
        // Override the CheckPermissions method
        public override async Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context,
                                                                              CommandInfo command, IServiceProvider services)
        {
            var guild = await context.Client.GetGuildAsync(DiscordSettings.GuildId);

            var guildUser = await guild.GetUserAsync(context.User.Id);

            if (guildUser.RoleIds.Contains(RoleId))
            {
                return(PreconditionResult.FromSuccess());
            }

            return(PreconditionResult.FromError(
                       $"This command can only be run by a {MentionUtils.MentionRole(RoleId)}."));
        }
Beispiel #20
0
        private void AddPromotionsToEmbed(StringBuilder builder, IReadOnlyCollection <PromotionCampaignSummary> promotions)
        {
            if (promotions.Count == 0)
            {
                return;
            }

            builder.AppendLine();
            builder.AppendLine(Format.Bold("\u276F Promotion History"));

            foreach (var promotion in promotions.OrderByDescending(x => x.CloseAction.Id).Take(5))
            {
                builder.AppendLine($"• {MentionUtils.MentionRole(promotion.TargetRole.Id)} {FormatUtilities.FormatTimeAgo(_utcNow, promotion.CloseAction.Created)}");
            }
        }
Beispiel #21
0
        public async Task ShowRanksAsync()
        {
            var comp = Service.GetOrCreateCompetition(Context.Guild.Id);

            if (!comp.Ranks.Any())
            {
                await SimpleEmbedAsync("There are currently no ranks set up.", Color.Blue);

                return;
            }

            var msg = comp.Ranks.OrderByDescending(x => x.Points).Select(x => $"{MentionUtils.MentionRole(x.RoleId)} - ({x.Points}) W: (+{x.WinModifier ?? comp.DefaultWinModifier}) L: (-{x.LossModifier ?? comp.DefaultLossModifier})").ToArray();

            await SimpleEmbedAsync(string.Join("\n", msg), Color.Blue);
        }
Beispiel #22
0
        public async Task InfoAsync(SocketGuildUser user = null)
        {
            if (user == null)
            {
                user = Context.User as SocketGuildUser;
            }

            var player = Service.GetPlayer(Context.Guild.Id, user.Id);

            if (player == null)
            {
                if (user.Id == Context.User.Id)
                {
                    await SimpleEmbedAsync("You are not registered.", Color.DarkBlue);
                }
                else
                {
                    await SimpleEmbedAsync("That user is not registered.", Color.Red);
                }
                return;
            }

            var    competition = Service.GetOrCreateCompetition(Context.Guild.Id);
            var    rank        = competition.MaxRank(player.Points);
            string rankStr     = null;

            if (rank != null)
            {
                rankStr = $"Rank: {MentionUtils.MentionRole(rank.RoleId)} ({rank.Points})\n";
            }

            var response = $"{player.GetDisplayNameSafe()} Stats\n" + // Use Title?
                           $"Points: {player.Points}\n" +
                           rankStr +
                           $"Wins: {player.Wins}\n" +
                           $"Losses: {player.Losses}\n" +
                           $"Draws: {player.Draws}\n" +
                           $"Games: {player.Games}\n" +
                           $"Registered At: {player.RegistrationDate.ToString("dd MMM yyyy")} {player.RegistrationDate.ToShortTimeString()}\n" +
                           $"{string.Join("\n", player.AdditionalProperties.Select(x => $"{x.Key}: {x.Value}"))}";

            //TODO: Add game history (last 5) to this response
            //+ if they were on the winning team?
            //maybe only games with a decided result should be shown?

            await SimpleEmbedAsync(response, Color.Blue);
        }
Beispiel #23
0
        public async Task BeginSignups([Remainder] int Players)
        {
            if (Context.Channel.Name != "mafia") // Ignore command if not typed in mafia channel
            {
                return;
            }

            bool gameRunning = false;

            foreach (Mafia.Game game in Startup.Games) // Make sure a game is not running on this server
            {
                if (game.Server == Context.Guild as SocketGuild)
                {
                    await ReplyAsync("A game is currently running!");

                    gameRunning = true;
                }
                if ((game.Mod.Username + game.Mod.Discriminator.ToString()) == (Context.User.Username + Context.User.Discriminator.ToString())) // For now, only allow a user to start a game on one server at a time
                {
                    await Context.User.SendMessageAsync($"You have already started a mafia game on {Context.Guild.Name}!");

                    return;
                }
            }
            if (!gameRunning)
            {
                // Only mafia mods should be able to start games
                if (CheckRole(Context.User as SocketGuildUser, "Mafia Mod"))
                {
                    Startup.Games.Add(new Game(Context.Guild, Context.User, Players)); // Instantiate a new game object for this server

                    string Mention = string.Empty;

                    if (GetRoleID(Context.Guild, "Mafia Player") != 0)
                    {
                        Mention = $"{MentionUtils.MentionRole(GetRoleID(Context.Guild, "Mafia Player"))} ";
                    }

                    await ReplyAsync($"{Mention}__**Signups have begun for a new mafia game hosted by {Context.User.Username}! Number of players: {Players}**__");
                    await ReplyAsync("Please use the ##sign command to sign up for this game!");
                }
                else
                {
                    await Context.User.SendMessageAsync("You need to have the Mafia Mod role in order to use this command!");
                }
            }
        }
Beispiel #24
0
        public virtual async Task ShowRanksAsync()
        {
            using (var db = new Database())
            {
                var comp  = db.GetOrCreateCompetition(Context.Guild.Id);
                var ranks = db.Ranks.Where(x => x.GuildId == Context.Guild.Id).ToList();
                if (ranks.Count == 0)
                {
                    await SimpleEmbedAsync("There are currently no ranks set up.", Color.Blue);

                    return;
                }

                var msg = ranks.OrderByDescending(x => x.Points).Select(x => $"{MentionUtils.MentionRole(x.RoleId)} - ({x.Points}) W: (+{x.WinModifier ?? comp.DefaultWinModifier}) L: (-{x.LossModifier ?? comp.DefaultLossModifier})").ToArray();
                await SimpleEmbedAsync(string.Join("\n", msg), Color.Blue);
            }
        }
Beispiel #25
0
        private async Task AddPromotionsToEmbedAsync(ulong userId, StringBuilder builder)
        {
            var promotions = await PromotionsService.GetPromotionsForUserAsync(Context.Guild.Id, userId);

            if (promotions.Count == 0)
            {
                return;
            }

            builder.AppendLine();
            builder.AppendLine(Format.Bold("\u276F Promotion History"));

            foreach (var promotion in promotions.OrderByDescending(x => x.CloseAction.Id).Take(5))
            {
                builder.AppendLine($"• {MentionUtils.MentionRole(promotion.TargetRole.Id)} {FormatUtilities.FormatTimeAgo(_utcNow, promotion.CloseAction.Created)}");
            }
        }
Beispiel #26
0
        public virtual async Task InfoAsync(SocketGuildUser user = null)
        {
            if (user == null)
            {
                user = Context.User as SocketGuildUser;
            }

            using (var db = new Database())
            {
                var player = db.Players.Find(Context.Guild.Id, user.Id);
                if (player == null)
                {
                    if (user.Id == Context.User.Id)
                    {
                        await SimpleEmbedAsync("You are not registered.", Color.DarkBlue);
                    }
                    else
                    {
                        await SimpleEmbedAsync("That user is not registered.", Color.Red);
                    }
                    return;
                }

                var    ranks   = db.Ranks.Where(x => x.GuildId == Context.Guild.Id).ToList();
                var    maxRank = ranks.Where(x => x.Points < player.Points).OrderByDescending(x => x.Points).FirstOrDefault();
                string rankStr = null;
                if (maxRank != null)
                {
                    rankStr = $"Rank: {MentionUtils.MentionRole(maxRank.RoleId)} ({maxRank.Points})\n";
                }

                await SimpleEmbedAsync($"{player.GetDisplayNameSafe()} Stats\n" + // Use Title?
                                       $"Points: {player.Points}\n" +
                                       rankStr +
                                       $"Wins: {player.Wins}\n" +
                                       $"Losses: {player.Losses}\n" +
                                       $"Draws: {player.Draws}\n" +
                                       $"Games: {player.Games}\n" +
                                       $"Registered At: {player.RegistrationDate.ToString("dd MMM yyyy")} {player.RegistrationDate.ToShortTimeString()}", Color.Blue);
            }

            //TODO: Add game history (last 5) to this response
            //+ if they were on the winning team?
            //maybe only games with a decided result should be shown?
        }
Beispiel #27
0
        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 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());
        }
Beispiel #29
0
        private async Task AddAlert(TuckContext context, Subscription subscription, ulong role)
        {
            if (subscription.SubscriberAlert != null)
            {
                await ReplyAsync(string.Format(
                                     "Replacing alerts for {0} with {1}.",
                                     MentionUtils.MentionRole(subscription.SubscriberAlert ?? 0),
                                     MentionUtils.MentionRole(role)
                                     ));
            }
            else
            {
                await ReplyAsync(string.Format(
                                     "Enabled alerts for {0}.",
                                     MentionUtils.MentionRole(role)
                                     ));
            }

            subscription.SubscriberAlert = role;
            context.Update(subscription);
            await context.SaveChangesAsync();
        }
            public async Task Default
            (
                [NotNull] IRole discordRole,
                string permissionName,
                [OverrideTypeReader(typeof(HumanizerEnumTypeReader <PermissionTarget>))]
                PermissionTarget revokedTarget = PermissionTarget.Self
            )
            {
                var getPermissionResult = _permissionRegistry.GetPermission(permissionName);

                if (!getPermissionResult.IsSuccess)
                {
                    await _feedback.SendErrorAsync(this.Context, getPermissionResult.ErrorReason);

                    return;
                }

                var permission             = getPermissionResult.Entity;
                var revokePermissionResult = await _permissions.RevokePermissionAsync
                                             (
                    discordRole,
                    permission,
                    revokedTarget
                                             );

                if (!revokePermissionResult.IsSuccess)
                {
                    await _feedback.SendErrorAsync(this.Context, revokePermissionResult.ErrorReason);

                    return;
                }

                await _feedback.SendConfirmationAsync
                (
                    this.Context,
                    $"{permission.FriendlyName} revoked from {MentionUtils.MentionRole(discordRole.Id)}."
                );
            }