Esempio n. 1
0
 private Func <Task> getRegisterUserAction(CommandContext ctx)
 {
     return(new Func <Task>(async() =>
     {
         var discordId = ctx.User.Id.ToString();
         var serverId = ctx.Guild.Id.ToString();
         var users = UserDbService.GetUsers();
         var servers = ServerDbService.GetServers(users);
         var server = servers[serverId];
         var config = LeagueConfigDbService.GetLeagueConfig(server.LeagueConfigId);
         if (!users.ContainsKey(discordId))
         {
             UserDbService.CreateUser(discordId, serverId, config);
         }
         if (!server.Users.Select(x => x.Id).Contains(discordId))
         {
             ServerDbService.AddUserToServer(discordId, serverId, false, false);
         }
         else
         {
             throw new Exception("You are already registered in this server");
         }
         ulong roleId = Convert.ToUInt64(server.LeagueRoleId);
         if (!ctx.Guild.Roles.ContainsKey(roleId))
         {
             throw new Exception("Error: League role not found");
         }
         await ctx.Member.GrantRoleAsync(ctx.Guild.Roles[roleId], "registering for riichi league");
         await ctx.RespondAsync($"<@{ctx.User.Id}> has been registered");
     }));
 }
Esempio n. 2
0
        private Func <Task> getListAction(CommandContext ctx)
        {
            return(new Func <Task>(async() =>
            {
                var users = UserDbService.GetUsers();
                var servers = ServerDbService.GetServers(users);
                var discordId = ctx.User.Id.ToString();
                var serverDiscordId = ctx.Guild.Id.ToString();

                int i = 1;
                StringBuilder sb = new StringBuilder();
                sb.Append($"Users registered in {ctx.Guild.Name}:\n");
                foreach (var user in servers[serverDiscordId].Users)
                {
                    sb.Append($"<@{user.Id}> majsoulName: {user.MahjsoulName} {(user.Id == discordId ? " <<< you" : "")}\n");
                    i++;
                }
                if (ctx != null && ctx.Member == null)
                {
                    await ctx.RespondAsync(sb.ToString());
                }
                else
                {
                    await ctx.Member.SendMessageAsync(sb.ToString());
                }
            }));
        }
Esempio n. 3
0
        private Func <Task> getDisplayLeagueConfigAction(CommandContext ctx, string inputServerId)
        {
            return(new Func <Task>(async() =>
            {
                var serverId = inputServerId;
                if (serverId == null && ctx.Guild == null)
                {
                    return;
                }
                if (serverId == null)
                {
                    serverId = ctx.Guild.Id.ToString();
                }
                var userId = ctx.User.Id.ToString();
                var allUsers = UserDbService.GetUsers();
                if (!allUsers.ContainsKey(userId))
                {
                    throw new Exception("You not registered in any server");
                }
                var allServers = ServerDbService.GetServers(allUsers);
                if (!allServers.ContainsKey(serverId))
                {
                    throw new Exception($"Server with id {serverId} does not exist");
                }
                var server = allServers[serverId];
                var configId = server.LeagueConfigId;
                var config = LeagueConfigDbService.GetLeagueConfig(configId);
                var sb = new StringBuilder();
                sb.AppendLine($"countPoints: {(config.CountPoints ? "Yes" : "No")}");
                sb.AppendLine($"startingPoints: {config.StartingPoints}");
                sb.AppendLine($"allowSanma: {(config.AllowSanma ? "Yes" : "No")}");
                sb.AppendLine($"uma3p1: {config.Uma3p1}");
                sb.AppendLine($"uma3p2: {config.Uma3p2}");
                sb.AppendLine($"uma3p3: {config.Uma3p3}");
                sb.AppendLine($"uma4p1: {config.Uma4p1}");
                sb.AppendLine($"uma4p2: {config.Uma4p2}");
                sb.AppendLine($"uma4p3: {config.Uma4p3}");
                sb.AppendLine($"uma4p4: {config.Uma4p4}");
                sb.AppendLine($"oka: {config.Oka}");
                sb.AppendLine($"penaltyLast: {config.PenaltyLast}");

                sb.AppendLine($"useEloSystem: {(config.UseEloSystem? "Yes" : "No")}");
                sb.AppendLine($"initialElo: {config.InitialElo}");
                sb.AppendLine($"minElo: {config.MinElo}");
                sb.AppendLine($"baseEloChangeDampening: {config.BaseEloChangeDampening}");
                sb.AppendLine($"eloChangeStartRatio: {config.EloChangeStartRatio}");
                sb.AppendLine($"eloChangeEndRatio: {config.EloChangeEndRatio}");
                sb.AppendLine($"trialPeriodDuration: {config.TrialPeriodDuration}");

                if (ctx.Member != null)
                {
                    await ctx.Member.SendMessageAsync(sb.ToString());
                }
                else
                {
                    await ctx.RespondAsync(sb.ToString());
                }
            }));
        }
Esempio n. 4
0
        private Func <Task> GetSubmitLogAction(CommandContext ctx, string gameId)
        {
            return(new Func <Task>(async() =>
            {
                var serverId = ctx.Guild.Id.ToString();
                var allUsers = UserDbService.GetUsers();
                var servers = ServerDbService.GetServers(allUsers);
                var server = servers[serverId];
                var serverUsers = server.Users;
                var log = await LogService.Instance.GetLog(gameId, 2);

                var users = await GetUsersFromLog(log, serverUsers, ctx);
                var gameResult = PrintGameResult(log, ctx.Client, users);
                var gameMsg = await ctx.RespondAsync($"I need all players to :o: or :x: to record or cancel this game\n{gameResult}");
                await context.AddPendingGame(ctx, gameMsg, new PendingGame(users.Select(x => x.Id.ToString()).ToArray(), server, log));
            }));
        }
Esempio n. 5
0
        private Func <Task> getSetOwnerAction(CommandContext ctx, DiscordUser targetDiscordUser, bool flag)
        {
            return(new Func <Task>(async() =>
            {
                var allUsers = UserDbService.GetUsers();
                var allServers = ServerDbService.GetServers(allUsers);
                var serverId = ctx.Guild.Id.ToString();
                var server = allServers[serverId];
                var userId = ctx.Member.Id.ToString();
                if (!server.Owners.Contains(allUsers[userId]))
                {
                    throw new Exception("You are not a owner of this bot");
                }
                var targetId = targetDiscordUser.Id.ToString();

                ServerDbService.SetIsOwner(serverId, targetId, flag);
                await Task.FromResult(false);
            }));
        }
Esempio n. 6
0
 private Func <Task> getUnRegisterUserAction(CommandContext ctx)
 {
     return(new Func <Task>(async() =>
     {
         var displayName = ctx.User.Username;
         var discordId = ctx.User.Id.ToString();
         var serverDiscordId = ctx.Guild.Id.ToString();
         var users = UserDbService.GetUsers();
         var servers = ServerDbService.GetServers(users);
         var server = servers[serverDiscordId];
         ServerDbService.RemoveUserFromServer(discordId, serverDiscordId);
         ulong roleId = Convert.ToUInt64(server.LeagueRoleId);
         if (!ctx.Guild.Roles.ContainsKey(roleId))
         {
             throw new Exception("Error: League role not found");
         }
         await ctx.Member.RevokeRoleAsync(ctx.Guild.Roles[roleId], "removing from riichi league");
         await ctx.RespondAsync($"<@{ctx.User.Id}> has been removed from league");
     }));
 }
Esempio n. 7
0
        private Func <Task> getChangeLeagueConfigAction(CommandContext ctx, string serverId, string paramName, string value)
        {
            return(new Func <Task>(async() =>
            {
                CfgPrm property = CfgPrm.UNKNOWN;
                try
                {
                    property = (CfgPrm)Enum.Parse(typeof(CfgPrm), paramName);
                } catch {
                    throw new Exception("This is not an existing property");
                }
                var userId = ctx.User.Id.ToString();
                var allUsers = UserDbService.GetUsers();
                var allServers = ServerDbService.GetServers(allUsers);
                if (!allServers.ContainsKey(serverId))
                {
                    throw new Exception($"Server with id {serverId} does not exist");
                }
                var server = allServers[serverId];
                if (!server.Admins.Select(x => x.Id).Contains(userId))
                {
                    throw new Exception("You must be admin of this server to change a league config");
                }
                var configId = server.LeagueConfigId;

                switch (property)
                {
                case CfgPrm.name: LeagueConfigDbService.SetConfigValue(paramName, configId, value); break;

                case CfgPrm.description: LeagueConfigDbService.SetConfigValue(paramName, configId, value); break;

                case CfgPrm.countPoints: LeagueConfigDbService.SetConfigValue(paramName, configId, value.ToLower() == "yes"); break;

                case CfgPrm.allowSanma: LeagueConfigDbService.SetConfigValue(paramName, configId, value.ToLower() == "yes"); break;

                case CfgPrm.startingPoints: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.uma3p1: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.uma3p2: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.uma3p3: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.uma4p1: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.uma4p2: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.uma4p3: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.uma4p4: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.oka: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.penaltyLast: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.useEloSystem: LeagueConfigDbService.SetConfigValue(paramName, configId, value.ToLower() == "yes"); break;

                case CfgPrm.initialElo: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.minElo: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.baseEloChangeDampening: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.eloChangeStartRatio: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.eloChangeEndRatio: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                case CfgPrm.trialPeriodDuration: LeagueConfigDbService.SetConfigValue(paramName, configId, float.Parse(value)); break;

                default: throw new Exception($"You cannot change {paramName}");
                }
                await ctx.RespondAsync($"Changed param: {paramName}={value}");
            }));
        }
Esempio n. 8
0
        public async static Task OnPendingGameReaction(DiscordClient sender, DiscordMessage msg, DiscordEmoji emoji, DiscordUser user, bool added)
        {
            var  kanContext = KandoraContext.Instance;
            var  msgId      = msg.Id;
            var  userId     = user.Id.ToString();
            var  game       = kanContext.PendingGames[msgId];
            bool result     = false;
            var  okEmoji    = DiscordEmoji.FromName(sender, Reactions.OK);
            var  noEmoji    = DiscordEmoji.FromName(sender, Reactions.NO);

            if (emoji.Id == okEmoji.Id)
            {
                result = game.TryChangeUserOk(userId, isAdd: added);
            }
            else if (emoji.Id == noEmoji.Id)
            {
                result = game.TryChangeUserNo(userId, isAdd: added);
            }
            if (!result && added)
            {
                await msg.DeleteReactionAsync(emoji, user);
            }
            if (game.IsCancelled)
            {
                await msg.ModifyAsync($"All players have voted {noEmoji}, this log won't be recorded");

                kanContext.PendingGames.Remove(msgId);
            }
            if (game.IsValidated)
            {
                DbService.Begin("recordgame");
                try
                {
                    var serverId     = msg.Channel.GuildId.ToString();
                    var users        = UserDbService.GetUsers();
                    var servers      = ServerDbService.GetServers(users);
                    var server       = servers[serverId];
                    var leagueConfig = LeagueConfigDbService.GetLeagueConfig(server.LeagueConfigId);

                    if (game.Log == null)
                    {
                        ScoreDbService.RecordIRLGame(game.UserIds, game.Scores, server, leagueConfig);
                    }
                    else
                    {
                        ScoreDbService.RecordOnlineGame(game.Log, server);
                    }
                    kanContext.PendingGames.Remove(msgId);
                    await msg.RespondAsync($"All players have voted {okEmoji}, this log has been recorded!");

                    await msg.DeleteReactionsEmojiAsync(okEmoji);

                    await msg.DeleteReactionsEmojiAsync(noEmoji);

                    DbService.Commit("recordgame");
                }
                catch (Exception e)
                {
                    DbService.Rollback("recordgame");
                    await msg.RespondAsync(e.Message);
                }
            }
        }
Esempio n. 9
0
        private Func <Task> getDisplayMeAction(CommandContext ctx)
        {
            return(new Func <Task>(async() =>
            {
                var userId = ctx.User.Id.ToString();
                var allUsers = UserDbService.GetUsers();
                if (!allUsers.ContainsKey(userId))
                {
                    throw new Exception("You are not registered in any server");
                }
                var user = allUsers[userId];
                var allServers = ServerDbService.GetServers(allUsers);
                var servers = allServers.Values.Where(x => x.Users.Contains(user));
                var sb = new StringBuilder();

                sb.AppendLine("Mahjsoul info:");
                sb.AppendLine($"\t{UserProperty.MahjsoulName}: {(user.MahjsoulName == null ? "N/A" : user.MahjsoulName)} (can be changed)");
                sb.AppendLine($"\t{UserProperty.MahjsoulFriendId}: {(user.MahjsoulFriendId == null ? "N/A" : user.MahjsoulFriendId)} (can be changed)");
                sb.AppendLine($"\tMahjsoulInternalUserId: {(user.MahjsoulUserId == null ? "N/A" : user.MahjsoulUserId)}");
                sb.AppendLine($"\tLast known rank: N/A"); // TODO
                sb.AppendLine("Tenhou info:");
                sb.AppendLine($"\t{UserProperty.TenhouName}: {(user.TenhouName == null ? "N/A" : user.TenhouName)} (can be changed)");
                sb.AppendLine($"\tLast known rank: N/A"); // TODO
                sb.AppendLine($"DiscordId: {user.Id}");
                sb.AppendLine($"Leagues you are registered in:");
                foreach (var server in servers)
                {
                    var rankings = RankingDbService.GetServerRankings(server.Id);
                    var playersRank = new Dictionary <string, float>();
                    var playersTime = new Dictionary <string, DateTime>();
                    //Get the last ranking for each player by iterating through the whole list
                    foreach (var ranking in rankings)
                    {
                        var playerId = ranking.UserId;
                        float rank;
                        DateTime time;
                        if (!playersRank.TryGetValue(playerId, out rank) || !playersTime.TryGetValue(playerId, out time))
                        {
                            playersRank.Add(playerId, ranking.NewRank);
                            playersTime.Add(playerId, ranking.Timestamp);
                        }
                        else
                        {
                            if (ranking.Timestamp.CompareTo(time) > 0)
                            {
                                playersRank[playerId] = ranking.NewRank;
                                playersTime[playerId] = ranking.Timestamp;
                            }
                        }
                    }

                    //Sort the list and compute the user's rank and ELO
                    List <KeyValuePair <string, float> > flatRanksSorted = playersRank.ToList();
                    flatRanksSorted.Sort((pair1, pair2) => pair2.Value.CompareTo(pair1.Value));
                    var nbPlayers = server.Users.Count;
                    var userRank = 1;
                    float userElo = -1;
                    foreach (var rank in flatRanksSorted)
                    {
                        if (rank.Key == userId)
                        {
                            userElo = rank.Value;
                            break;
                        }
                        else
                        {
                            userRank++;
                        }
                    }
                    sb.AppendLine($"\t{server.LeagueName}({server.DisplayName}): {userRank}/{nbPlayers} (R{userElo})");
                }
                if (ctx != null && ctx.Member == null)
                {
                    await ctx.RespondAsync(sb.ToString());
                }
                else
                {
                    await ctx.Member.SendMessageAsync(sb.ToString());
                }
            }));
        }