示例#1
0
        public async Task AddTempRoleAsync(ulong userId, ulong roleId, TimeSpan duration, string reason)
        {
            var role = new RiftTempRole
            {
                UserId         = userId,
                RoleId         = roleId,
                ObtainedFrom   = reason,
                ObtainedTime   = DateTime.UtcNow,
                ExpirationTime = DateTime.UtcNow + duration,
            };

            if (!IonicHelper.GetGuildUserById(Settings.App.MainGuildId, userId, out var sgUser))
            {
                return;
            }

            if (!IonicHelper.GetRole(Settings.App.MainGuildId, roleId, out var serverRole))
            {
                return;
            }

            await sgUser.AddRoleAsync(serverRole);

            await DB.TempRoles.AddAsync(role);
        }
示例#2
0
        public async Task UpdateSummonerAsync(ulong userId)
        {
            RiftBot.Log.Information($"[User|{userId.ToString()}] Getting summoner for the league data update");

            if (!IonicHelper.GetGuildUserById(Settings.App.MainGuildId, userId, out var sgUser))
            {
                RiftBot.Log.Error($"{userId.ToString()} Failed to find guild user.");
                return;
            }

            var leagueData = await DB.LeagueData.GetAsync(userId);

            (var result, var data) = await GetSummonerByEncryptedSummonerIdAsync(leagueData.SummonerRegion, leagueData.SummonerId);

            if (result == RequestResult.Error)
            {
                RiftBot.Log.Error($"{userId.ToString()} League data update failed.");
                return;
            }

            await DB.LeagueData.UpdateAsync(userId, leagueData.SummonerRegion, leagueData.PlayerUUID, leagueData.AccountId,
                                            leagueData.SummonerId, data.Name);

            await UpdateRankRoleAsync(sgUser, leagueData);

            RiftBot.Log.Information($"{userId.ToString()} League data update completed.");
        }
示例#3
0
        static void Main(string[] args)
        {
            //单文件解压缩
            string sourceFile = @"F:\Study\ELK\资料\data\logs.jsonl";

            //string gzipFile = @"F:\Study\ELK\资料\data\zip\logs_gzip.jsonl";
            //string bzipFile = @"F:\Study\ELK\资料\data\zip\logs_bzip.jsonl";

            //string ungzipFile = @"F:\Study\ELK\资料\data\unzip\logs_gzip.jsonl";
            //string unbzipFile = @"F:\Study\ELK\资料\data\unzip\logs_bzip.jsonl";

            //SharpZipLibHelper.ZipFile(sourceFile, gzipFile, ZipEnum.GZIP);
            //SharpZipLibHelper.ZipFile(sourceFile, bzipFile, ZipEnum.BZIP2);

            //SharpZipLibHelper.UnZipFile(gzipFile, ungzipFile, ZipEnum.GZIP);
            //SharpZipLibHelper.UnZipFile(bzipFile, unbzipFile, ZipEnum.BZIP2);

            //多文件解压缩
            //string sourceDir = @"F:\Study\ELK\资料\data";
            //string zipFiles = @"F:\Study\ELK\资料\data\zip\files.zip";
            //string zipDir = @"F:\Study\ELK\资料\data\zip\data\";

            //SharpZipLibHelper.ZipFiles(sourceDir, zipFiles, "*.json", 1, "1234", "this is zip");
            //SharpZipLibHelper.UnZipFiles(zipFiles, zipDir, "1234");

            //Ionic
            string desFile = @"F:\Study\ELK\资料\data\zip\ionic\logs.zip";

            //IonicHelper.ZipOne(sourceFile, desFile, "1234");

            IonicHelper.UnZipUnZipFiles(desFile, @"F:\Study\ELK\资料\data\", "1234");

            Console.Read();
        }
示例#4
0
        async Task StartBotGifts()
        {
            RiftBot.Log.Debug("Gifts are on the way..");

            var users = await DB.Cooldowns.GetBotRespectedUsersAsync();

            if (users.Count == 0)
            {
                RiftBot.Log.Debug("No users with bot respect, rescheduling.");
                InitTimer();
                return;
            }

            foreach (var userId in users)
            {
                if (!IonicHelper.GetGuildUserById(Settings.App.MainGuildId, userId, out var sgUser))
                {
                    continue;
                }

                var reward = AvailableRewards.Random();
                await rewardService.DeliverToAsync(userId, reward);
            }

            await messageService.SendMessageAsync("yasuo-botrespect-success", Settings.ChannelId.Chat, null);

            RiftBot.Log.Debug("Finished sending gifts");

            InitTimer();
        }
示例#5
0
        static async Task RegisterJoinedLeft(SocketGuildUser sgUser, UserState state)
        {
            if (state == UserState.Joined)
            {
                await roleService.RestoreTempRolesAsync(sgUser);

                if (sgUser.Guild.Id == Settings.App.MainGuildId)
                {
                    var msg = await messageService.GetMessageAsync("welcome", null);

                    await(await sgUser.GetOrCreateDMChannelAsync()).SendMessageAsync(embed: msg.Embed);
                }
            }

            if (!IonicHelper.GetTextChannel(Settings.App.MainGuildId, Settings.ChannelId.Logs, out var logsChannel))
            {
                return;
            }

            var eb = new RiftEmbed()
                     .WithColor(state == UserState.Joined
                                    ? new Color(46, 204, 113)
                                    : new Color(231, 76, 60))
                     .WithAuthor("Призыватель " + (state == UserState.Joined ? "присоединился" : "вышел"),
                                 sgUser.GetAvatarUrl())
                     .WithDescription($"Никнейм: {sgUser.Mention} ({sgUser.Username}#{sgUser.Discriminator})")
                     .WithFooter($"ID: {sgUser.Id.ToString()}")
                     .WithCurrentTimestamp();

            await logsChannel.SendIonicMessageAsync(new IonicMessage(eb));
        }
示例#6
0
        public async Task RestoreTempRolesAsync(SocketGuildUser sgUser)
        {
            RiftBot.Log.Information($"User {sgUser.ToLogString()} joined, checking temp roles");

            var tempRoles = await DB.TempRoles.GetAsync(sgUser.Id);

            if (tempRoles is null || tempRoles.Count == 0)
            {
                RiftBot.Log.Debug($"No temp roles for user {sgUser}");
                return;
            }

            var remainingRoles = tempRoles.Select(x => x.RoleId).Except(sgUser.Roles.Select(x => x.Id));

            foreach (var id in remainingRoles)
            {
                if (!IonicHelper.GetRole(Settings.App.MainGuildId, id, out var role))
                {
                    RiftBot.Log.Error($"Applying role {id.ToString()}: FAILED");
                    continue;
                }

                await sgUser.AddRoleAsync(role);

                RiftBot.Log.Debug($"Successfully added temp role \"{role.Name}\" for user {sgUser}");
            }
        }
示例#7
0
        public async Task <IUserMessage> SendMessageAsync(IonicMessage message, ulong channelId)
        {
            if (!IonicHelper.GetTextChannel(Settings.App.MainGuildId, channelId, out var channel))
            {
                return(null);
            }

            return(await channel.SendIonicMessageAsync(message));
        }
示例#8
0
        async Task Announce_Callback()
        {
            if (!IonicHelper.GetTextChannel(Settings.App.MainGuildId, Settings.ChannelId.Commands, out var channel))
            {
                return;
            }

            await channel.SendEmbedAsync(embeds.Random());
        }
示例#9
0
        public override Task <RiftMessage> ApplyAsync(RiftMessage message, FormatData data)
        {
            if (!IonicHelper.GetGuildUserById(Settings.App.MainGuildId, data.Moderation.ModeratorId, out var sgUser))
            {
                TemplateError("No user data found.");
                return(Task.FromResult(message));
            }

            return(ReplaceDataAsync(message, sgUser.Username));
        }
示例#10
0
        public override Task <RiftMessage> ApplyAsync(RiftMessage message, FormatData data)
        {
            if (!IonicHelper.GetGuild(Settings.App.MainGuildId, out var guild))
            {
                TemplateError($"No guild found.");
                return(Task.FromResult(message));
            }

            return(ReplaceDataAsync(message, guild.Name));
        }
示例#11
0
        public override Task <RiftMessage> ApplyAsync(RiftMessage message, FormatData data)
        {
            if (!IonicHelper.GetGuildUserById(Settings.App.MainGuildId, data.Moderation.TargetId, out var sgUser))
            {
                TemplateError("No user data found.");
                return(null);
            }

            return(ReplaceDataAsync(message, sgUser.ToString()));
        }
示例#12
0
        public override Task <RiftMessage> ApplyAsync(RiftMessage message, FormatData data)
        {
            if (!IonicHelper.GetGuildUserById(Settings.App.MainGuildId, data.Giveaway.TicketGiveaway.WinnerId, out var sgUser))
            {
                TemplateError("No user data found.");
                return(null);
            }

            return(ReplaceDataAsync(message, sgUser.Username));
        }
示例#13
0
        public override async Task <RiftMessage> ApplyAsync(RiftMessage message, FormatData data)
        {
            if (!IonicHelper.GetGuildUserById(Settings.App.MainGuildId, data.UserId, out var sgUser))
            {
                TemplateError("No user data found.");
                return(message);
            }

            return(await ReplaceDataAsync(message, sgUser.GetAvatarUrl()));
        }
示例#14
0
        public override async Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            var role = await DB.Roles.GetAsync(173);

            if (IonicHelper.HasRolesAny(Settings.App.MainGuildId, context.User.Id, role.RoleId) || RiftBot.IsAdmin(context.User))
            {
                return(PreconditionResult.FromSuccess());
            }

            return(PreconditionResult.FromError(RiftBot.CommandDenyMessage));
        }
示例#15
0
        public override async Task <RiftMessage> ApplyAsync(RiftMessage message, FormatData data)
        {
            if (!IonicHelper.GetGuildUserById(Settings.App.MainGuildId, data.UserId, out var sgUser) ||
                sgUser?.JoinedAt is null)
            {
                TemplateError("No user data found.");
                return(message);
            }

            return(await ReplaceDataAsync(message, sgUser.JoinedAt.Value.UtcDateTime.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture)));
        }
示例#16
0
        public async Task WhoIs(ulong userId)
        {
            if (!IonicHelper.GetGuildUserById(Settings.App.MainGuildId, userId, out var sgUser))
            {
                await ReplyAsync($"Пользователя с таким ID нет на сервере.");

                return;
            }

            await ReplyAsync($"Пользователь найден: {sgUser.Mention} ({sgUser})");
        }
示例#17
0
        public async Task <List <ulong> > GetNitroBoostersAsync()
        {
            var nitro = await DB.Roles.GetAsync(91);

            if (!IonicHelper.GetRole(Settings.App.MainGuildId, nitro.RoleId, out var role) ||
                !(role is SocketRole sgRole))
            {
                return(null);
            }

            return(sgRole.Members.Select(x => x.Id).ToList());
        }
示例#18
0
        public static async Task SendMessageToDevelopers(string msg)
        {
            foreach (var userId in developersIds)
            {
                if (!IonicHelper.GetGuildUserById(Settings.App.MainGuildId, userId, out var sgUser))
                {
                    return;
                }

                await sgUser.SendMessageAsync(msg);
            }
        }
示例#19
0
        static async Task RunAsync()
        {
            Log = new LoggerConfiguration()
                  .MinimumLevel.Information()
                  .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                  .Enrich.FromLogContext()
                  .WriteTo.Async(x => x.File("logs/rift-.log", rollingInterval: RollingInterval.Day))
                  .CreateLogger();

            DiscordLogger = new LoggerConfiguration()
                            .MinimumLevel.Information()
                            .Enrich.FromLogContext()
                            .WriteTo.Async(x => x.File("logs/discord-.log", rollingInterval: RollingInterval.Day))
                            .CreateLogger();

            ChatLogger = new LoggerConfiguration()
                         .MinimumLevel.Information()
                         .Enrich.FromLogContext()
                         .WriteTo.Async(x => x.File("logs/chat-.log", rollingInterval: RollingInterval.Day))
                         .CreateLogger();

            var serviceProvider = SetupServices();

            handler = new CommandHandler(serviceProvider);
            await handler.ConfigureAsync();

            try
            {
                await Task.Delay(-1, IonicHelper.GetCancellationTokenSource().Token);
            }
            catch (TaskCanceledException)
            {
                await IonicHelper.Client.StopAsync().ContinueWith(x =>
                {
                    if (!ShouldReboot)
                    {
                        Console.WriteLine("Shutting down");
                        Serilog.Log.CloseAndFlush();
                    }
                    else
                    {
                        Console.WriteLine("Restarting...");
                        Serilog.Log.CloseAndFlush();
                        Environment.Exit(4); //anything higher than zero is a restart
                    }
                });
            }
            catch (Exception ex)
            {
                Log.Error(ex, "An error occured while shutting down");
            }
        }
示例#20
0
        public async Task URL()
        {
            if (!IonicHelper.GetTextChannel(Settings.App.MainGuildId, Settings.ChannelId.Commands, out var channel))
            {
                return;
            }

            Settings.Chat.UrlFilterEnabled = !Settings.Chat.UrlFilterEnabled;
            await Settings.SaveChatAsync();

            await channel.SendMessageAsync(
                $"Фильтр ссылок {(Settings.Chat.UrlFilterEnabled ? "включён" : "выключен")}.");
        }
示例#21
0
        public async Task StartAsync(RiftEvent dbEvent, ulong startedById)
        {
            if (dbEvent is null)
            {
                RiftBot.Log.Warning("Wrong event name, skipping execution.");
                return;
            }

            var msg = await messageService.GetMessageFromApi(dbEvent.MessageId);

            if (msg is null)
            {
                RiftBot.Log.Warning("Wrong event message ID, skipping execution.");
                return;
            }

            var dbSharedReward = await DB.Rewards.GetAsync(dbEvent.SharedRewardId);

            if (dbSharedReward is null)
            {
                RiftBot.Log.Warning("Wrong event reward ID, skipping execution.");
                return;
            }

            if (!IonicHelper.GetEmote(213672490491314176, "smite", out var smite))
            {
                RiftBot.Log.Warning("No event emote, skipping execution.");
                return;
            }

            var activeGiveaway = new RiftActiveEvent
            {
                EventName = dbEvent.Name,
                MessageId = dbEvent.MessageId,
                StartedBy = startedById == 0u ? IonicHelper.Client.CurrentUser.Id : startedById,
                StartedAt = DateTime.UtcNow,
                DueTime   = DateTime.UtcNow + dbEvent.Duration,
            };

            var formattedMsg = await messageService.FormatMessageAsync(msg, new FormatData(startedById));

            var eventMessage = await messageService.SendMessageAsync(formattedMsg, Settings.ChannelId.Monsters).ConfigureAwait(false);

            activeGiveaway.ChannelMessageId = eventMessage.Id;

            await DB.ActiveEvents.AddAsync(activeGiveaway).ConfigureAwait(false);

            await eventMessage.AddReactionAsync(smite);

            await ScheduleTimerToClosestActiveAsync().ConfigureAwait(false);
        }
示例#22
0
        async Task PostValidateAsync(RiftPendingUser pendingUser)
        {
            if (!IonicHelper.GetGuildUserById(Settings.App.MainGuildId, pendingUser.UserId, out var sgUser))
            {
                return;
            }

            await DB.PendingUsers.RemoveAsync(pendingUser.UserId);

            await AssignRoleFromRankAsync(sgUser, pendingUser);

            await DB.Inventory.AddAsync(sgUser.Id, new InventoryData { Chests = 2u });

            await messageService.SendMessageAsync("register-success", Settings.ChannelId.Commands, new FormatData(pendingUser.UserId));
        }
示例#23
0
        public async Task <(bool, IonicMessage)> RemovePermanentRoleAsync(ulong userId, ulong roleId)
        {
            if (!IonicHelper.GetGuildUserById(Settings.App.MainGuildId, userId, out var sgUser))
            {
                return(false, MessageService.UserNotFound);
            }

            if (!IonicHelper.GetRole(Settings.App.MainGuildId, roleId, out var role))
            {
                return(false, MessageService.RoleNotFound);
            }

            await sgUser.RemoveRoleAsync(role);

            return(true, null);
        }
示例#24
0
        public async Task <IUserMessage> SendMessageAsync(string identifier, ulong channelId, FormatData data)
        {
            if (!IonicHelper.GetTextChannel(Settings.App.MainGuildId, channelId, out var channel))
            {
                return(null);
            }

            var msg = await GetMessageAsync(identifier, data);

            if (msg is null)
            {
                return(null);
            }

            return(await channel.SendIonicMessageAsync(msg).ConfigureAwait(false));
        }
示例#25
0
        public async Task <(bool, Embed)> RemoveTempRoleAsync(ulong userId, ulong roleId)
        {
            await DB.TempRoles.RemoveAsync(userId, roleId);

            IonicHelper.GetGuildUserById(Settings.App.MainGuildId, userId, out var sgUser);

            var role = sgUser?.Roles.FirstOrDefault(x => x.Id == roleId);

            if (role != null)
            {
                await sgUser.RemoveRoleAsync(role);
            }

            RiftBot.Log.Information($"Removed role {roleId.ToString()} from {sgUser} {userId.ToString()}");

            return(true, null);
        }
示例#26
0
        static async Task <(bool, RestVoiceChannel)> CreateRoomForUser(IUser user)
        {
            if (!IonicHelper.GetCategory(Settings.App.MainGuildId, VoiceCategoryId, out var category))
            {
                return(false, null);
            }

            var channel = await category.Guild.CreateVoiceChannelAsync(user.Username, x =>
            {
                x.UserLimit  = 5;
                x.CategoryId = VoiceCategoryId;
            });

            await channel.AddPermissionOverwriteAsync(user, new OverwritePermissions(manageChannel : PermValue.Allow));

            return(true, channel);
        }
示例#27
0
        async Task UpdateRankRoleAsync(IGuildUser sgUser, RiftLeagueData leagueData)
        {
            (var rankResult, var rankData) =
                await GetLeaguePositionsByEncryptedSummonerIdAsync(leagueData.SummonerRegion, leagueData.SummonerId);

            if (rankResult != RequestResult.Success)
            {
                return;
            }

            var newRank = GetRankFromEntry(rankData.FirstOrDefault(x => x.QueueType == "RANKED_SOLO_5x5"));

            var currentRank = await GetCurrentRank(sgUser);

            if (currentRank == newRank)
            {
                RiftBot.Log.Information($"{sgUser.ToLogString()} Same rank, nothing to update.");
                return;
            }

            await RemoveRankedRole(sgUser, currentRank);

            var roleId = await GetRoleByLeagueRank(newRank);

            if (roleId is null || roleId.RoleId == 0ul)
            {
                return;
            }

            if (!IonicHelper.GetRole(Settings.App.MainGuildId, roleId.RoleId, out var role))
            {
                return;
            }

            await messageService.SendMessageAsync("rank-updated", Settings.ChannelId.Chat, new FormatData(sgUser.Id)
            {
                RankData = new RankData
                {
                    PreviousRank = GetStatStringFromRank(currentRank),
                    CurrentRank  = GetStatStringFromRank(newRank)
                }
            });

            await sgUser.AddRoleAsync(role);
        }
示例#28
0
        public async Task BanAsync(IUser target, string reason, IUser moderator)
        {
            (var passed, var sgTarget) = await ValidateAsync(target, reason, moderator);

            if (!passed)
            {
                return;
            }

            if (RiftBot.IsAdmin(sgTarget) || await RiftBot.IsModeratorAsync(sgTarget))
            {
                await messageService.SendMessageAsync("mod-friendly-fire", Settings.ChannelId.Commands, new FormatData(moderator.Id));

                return;
            }

            if (!IonicHelper.GetGuild(Settings.App.MainGuildId, out var guild))
            {
                return;
            }

            await DB.ModerationLogs.AddAsync(sgTarget.Id, moderator.Id, "Ban", reason, DateTime.UtcNow, TimeSpan.Zero);

            (var oldToxicity, var newToxicity) = await GetNewToxicityAsync(sgTarget.Id, ToxicitySource.Ban);

            await DB.Toxicity.UpdatePercentAsync(sgTarget.Id, newToxicity.Percent);

            var data = new FormatData(target.Id)
            {
                Moderation = new ModerationData
                {
                    ModeratorId = moderator.Id,
                    TargetId    = sgTarget.Id,
                    Reason      = reason,
                }
            };

            await messageService.SendMessageAsync("mod-ban-success", Settings.ChannelId.Chat, data);

            await guild.AddBanAsync(sgTarget, 1, $"Banned by {moderator}: {reason}");
        }
示例#29
0
        public async Task <string> FormatAsync(RoleReward reward)
        {
            var text = "роль";

            var dbRole = await DB.Roles.GetAsync(reward.RoleId);

            if (dbRole is null || !IonicHelper.GetRole(Settings.App.MainGuildId, dbRole.RoleId, out var role))
            {
                text += " не найдена";
                return(text);
            }

            text += $" {role.Name}";

            if (reward.Duration != null)
            {
                text += $" на {reward.Duration.Value.Humanize(culture: RiftBot.Culture)}";
            }

            return(text);
        }
示例#30
0
        public async Task <IonicMessage> GetUserActionLogsAsync(IUser user)
        {
            if (user is null)
            {
                return(MessageService.UserNotFound);
            }

            var list = await DB.ModerationLogs.GetAsync(user.Id);

            var toxicity = await DB.Toxicity.GetAsync(user.Id);

            var actions = string.Join('\n', list.Select(x =>
            {
                var action = FormatAction(x.Action);

                if (x.Duration != TimeSpan.Zero)
                {
                    action += $"({x.Duration.Humanize()})";
                }

                return(action);
            }));

            var datetime = string.Join('\n', list.Select(x =>
                                                         x.CreatedAt.Humanize()));

            var moderator = string.Join('\n', list.Select(x =>
            {
                IonicHelper.GetGuildUserById(Settings.App.MainGuildId, x.ModeratorId, out var sgUser);
                return(sgUser is null ? "-" : sgUser.Username);
            }));

            var embed = new RiftEmbed()
                        .WithDescription($"Досье товарища {user.Username}\nУровень токсичности: {FormatToxicityLevel(toxicity.Level)}")
                        .AddField("Действие", actions, true)
                        .AddField("Дата и время", datetime, true)
                        .AddField("Модератор", moderator, true);

            return(new IonicMessage(embed));
        }