Ejemplo n.º 1
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));
        }
Ejemplo n.º 2
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));
        }
Ejemplo n.º 3
0
        async Task Announce_Callback()
        {
            if (!IonicHelper.GetTextChannel(Settings.App.MainGuildId, Settings.ChannelId.Commands, out var channel))
            {
                return;
            }

            await channel.SendEmbedAsync(embeds.Random());
        }
Ejemplo n.º 4
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 ? "включён" : "выключен")}.");
        }
Ejemplo n.º 5
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));
        }
Ejemplo n.º 6
0
        async Task DeleteAsync(DeleteMessageBase message)
        {
            if (!IonicHelper.GetTextChannel(Settings.App.MainGuildId, message.ChannelId, out var channel))
            {
                return;
            }

            try
            {
                var msg = await channel.GetMessageAsync(message.MessageId);

                if (msg is null)
                {
                    return;
                }

                await msg.DeleteAsync().ConfigureAwait(false);
            }
            catch (Exception ex) // fails when message is already deleted, no delete perms or discord outage
            {
                RiftBot.Log.Error(ex, "Message was already deleted or no permissions?");
            }
        }
Ejemplo n.º 7
0
        async Task FinishAsync(RiftActiveEvent expiredEvent)
        {
            var eventLogString = $"ID {expiredEvent.Id.ToString()} \"{expiredEvent.EventName}\"";
            var dbEvent        = await DB.Events.GetAsync(expiredEvent.EventName);

            if (dbEvent is null)
            {
                RiftBot.Log.Error($"Could not finish event {eventLogString}: {nameof(RiftEvent)} is null!");
                return;
            }

            if (!IonicHelper.GetTextChannel(Settings.App.MainGuildId, Settings.ChannelId.Monsters, out var channel))
            {
                RiftBot.Log.Error($"Could not finish event {eventLogString}: Event channel is null!");
                return;
            }

            var message = (IUserMessage)await channel.GetMessageAsync(expiredEvent.ChannelMessageId);

            if (message is null)
            {
                RiftBot.Log.Error($"Could not finish event {eventLogString}: Event message is null! Deleted?");
                return;
            }

            if (!IonicHelper.GetEmote(213672490491314176ul, "smite", out var emote))
            {
                RiftBot.Log.Error($"Could not finish event {eventLogString}: Emote is null! Deleted?");
                return;
            }

            // Reaction amount is limited by discord itself.
            // See https://discordapp.com/developers/docs/resources/channel#get-reactions
            var reactions = await message.GetReactionUsersAsync(emote, 100).FlattenAsync();

            if (reactions is null)
            {
                RiftBot.Log.Error($"Could not finish event {eventLogString}: Unable to get reactions.");
                return;
            }

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

            if (dbReward is null)
            {
                RiftBot.Log.Error($"Could not finish event {eventLogString}: " +
                                  $"Unable to get reward ID {dbEvent.SharedRewardId.ToString()}.");
                return;
            }

            var participants = reactions
                               .Where(x => !x.IsBot && x.Id != IonicHelper.Client.CurrentUser.Id)
                               .Select(x => x.Id)
                               .ToArray();

            if (participants.Length == 0)
            {
                await LogEventAsync(dbEvent.Name, null, "No reward provided ", expiredEvent.StartedBy,
                                    expiredEvent.StartedAt, dbEvent.Duration);

                await DB.ActiveEvents.RemoveAsync(expiredEvent.Id);

                RiftBot.Log.Error($"Could not finish event {eventLogString}: No participants.");
                return;
            }

            RiftReward specialReward   = null;
            var        specialWinnerId = 0ul;

            if (dbEvent.HasSpecialReward)
            {
                specialReward = await DB.Rewards.GetAsync(dbEvent.SpecialRewardId);

                if (specialReward is null)
                {
                    RiftBot.Log.Error($"Could not finish event {eventLogString}: " +
                                      $"Unable to get special reward ID {dbEvent.SharedRewardId.ToString()}.");
                    return;
                }

                specialWinnerId = participants.Random();

                var specReward = specialReward.ToRewardBase();
                await rewardService.DeliverToAsync(specialWinnerId, specReward);
            }

            var reward = dbReward.ToRewardBase();

            foreach (var userId in participants)
            {
                await rewardService.DeliverToAsync(userId, reward);
            }

            await DB.ActiveEvents.RemoveAsync(expiredEvent.Id);

            var eventType = (EventType)dbEvent.Type;

            foreach (var participant in participants)
            {
                switch (eventType)
                {
                case EventType.Normal:
                    NormalMonstersKilled?.Invoke(
                        null, new NormalMonstersKilledEventArgs(participant, 1u));
                    break;

                case EventType.Rare:
                    RareMonstersKilled?.Invoke(
                        null, new RareMonstersKilledEventArgs(participant, 1u));
                    break;

                case EventType.Epic:
                    EpicMonstersKilled?.Invoke(
                        null, new EpicMonstersKilledEventArgs(participant, 1u));
                    break;
                }
            }

            var log = new RiftEventLog
            {
                Name = dbEvent.Name,
                ParticipantsAmount = (uint)participants.Length,
                Reward             = "No reward provided",
                StartedBy          = expiredEvent.StartedBy,
                StartedAt          = expiredEvent.StartedAt,
                Duration           = dbEvent.Duration,
                FinishedAt         = DateTime.UtcNow,
                SpecialWinnerId    = specialWinnerId
            };

            await messageService.SendMessageAsync("event-finished", Settings.ChannelId.Monsters, new FormatData(expiredEvent.StartedBy)
            {
                EventData = new EventData
                {
                    Log    = log,
                    Stored = dbEvent,
                }
            });

            if (dbEvent.HasSpecialReward)
            {
                await messageService.SendMessageAsync("event-finished-special", Settings.ChannelId.Monsters, new FormatData(specialWinnerId)
                {
                    Reward = specialReward.ToRewardBase()
                });
            }

            await LogEventAsync(log).ConfigureAwait(false);
        }
Ejemplo n.º 8
0
        public async Task SelfTest()
        {
            var skipChecks = false;

            var errors     = new List <string>();
            var fixedRoles = 0u;

            var eb = new RiftEmbed().WithTitle("Self-test");

            if (!IonicHelper.GetGuild(Settings.App.MainGuildId, out var guild))
            {
                errors.Add($"Guild is null: {nameof(Settings.App.MainGuildId)}");
                skipChecks = true;
            }

            var channelNames = Settings.ChannelId.GetNames();

            foreach (var field in Settings.ChannelId.GetType().GetProperties())
            {
                if (skipChecks)
                {
                    break;
                }

                if (field.GetValue(Settings.ChannelId, null) is ulong value)
                {
                    if (value == 0ul)
                    {
                        if (channelNames.ContainsKey(field.Name))
                        {
                            var channelName = channelNames[field.Name];

                            var guildChannel = guild.Channels.FirstOrDefault(
                                x => x.Name.Equals(channelName, StringComparison.InvariantCultureIgnoreCase));

                            if (guildChannel is null)
                            {
                                errors.Add($"Channel ID remains undefined: {field.Name} {channelName}");
                                continue;
                            }

                            Settings.ChannelId.SetValue(field.Name, guildChannel.Id);
                            fixedRoles++;
                        }
                        else
                        {
                            errors.Add($"Channel ID remains undefined: {field.Name}");
                            continue;
                        }
                    }
                    else if (!IonicHelper.GetTextChannel(Settings.App.MainGuildId, value, out var textChannel) &&
                             !IonicHelper.GetVoiceChannel(Settings.App.MainGuildId, value, out var voiceChannel))
                    {
                        errors.Add($"No channel on server: {field.Name}");
                    }
                }
            }

            foreach (var field in Settings.Chat.GetType().GetProperties())
            {
                if (skipChecks)
                {
                    break;
                }

                var obj = field.GetValue(Settings.Chat);

                if (obj is ulong ulongValue)
                {
                    if (ulongValue == 0ul)
                    {
                        errors.Add($"Chat parameter undefined: {field.Name}");
                    }
                }
                else if (obj is uint uintValue)
                {
                    if (uintValue == 0u)
                    {
                        errors.Add($"Chat parameter undefined: {field.Name}");
                    }
                }
            }

            foreach (var field in Settings.Economy.GetType().GetProperties())
            {
                if (skipChecks)
                {
                    break;
                }

                try
                {
                    var obj = field.GetValue(Settings.Economy);

                    if (obj is ulong ulongValue)
                    {
                        if (ulongValue == 0ul)
                        {
                            errors.Add($"Economy parameter undefined: {field.Name}");
                        }
                    }
                    else if (obj is uint uintValue)
                    {
                        if (uintValue == 0u)
                        {
                            errors.Add($"Economy parameter undefined: {field.Name}");
                        }
                    }
                }
                catch (TargetInvocationException ex)
                {
                    errors.Add($"\"{field.Name}\" invokation failed: {ex.Message}");
                }
                catch (Exception ex)
                {
                    errors.Add($"Economy object exception failed: {ex.Message}");
                }
            }

            var serverRoles = Context.Guild.Roles.ToList();
            var roles       = await DB.Roles.GetAllAsync();

            foreach (var role in serverRoles)
            {
                if (skipChecks)
                {
                    break;
                }

                var matchedRole = roles.FirstOrDefault(x => x.Name.Equals(role.Name));

                if (matchedRole is null)
                {
                    await DB.Roles.AddAsync(role);

                    fixedRoles++;
                    continue;
                }

                if (matchedRole.RoleId.Equals(role.Id))
                {
                    continue;
                }

                matchedRole.RoleId = role.Id;
                await DB.Roles.UpdateAsync(matchedRole);

                fixedRoles++;
            }

            if (errors.Count == 0)
            {
                eb.WithColor(0, 255, 0);
                eb.WithDescription("OK 👌");
            }
            else
            {
                eb.WithColor(255, 0, 0);

                var errorList = string.Join('\n', errors);

                if (errorList.Length >= 2048)
                {
                    errorList = string.Join('\n', errors.Take(10));
                    eb.WithDescription($"**{errors.Count.ToString()} error(s), showing first 10**\n\n{errorList}");
                }
                else
                {
                    eb.WithDescription($"**{errors.Count.ToString()} error(s)**\n\n{errorList}");
                }
            }

            await Context.Channel.SendIonicMessageAsync(new IonicMessage(eb));

            if (fixedRoles > 0u)
            {
                var embedMsg = new RiftEmbed()
                               .WithColor(255, 255, 0)
                               .WithAuthor("Self-test")
                               .WithDescription($"Fixed {fixedRoles.ToString()} roles.");

                await Context.Channel.SendIonicMessageAsync(new IonicMessage(embedMsg));
            }
        }
Ejemplo n.º 9
0
        async Task DeliverAsync(SendMessageBase message)
        {
            switch (message.DestinationType)
            {
            case DestinationType.DM:

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

                var userChannel = await sgUser.GetOrCreateDMChannelAsync();

                switch (message.MessageType)
                {
                case MessageType.PlainText:

                    await userChannel.SendMessageAsync(message.Text).ConfigureAwait(false);

                    break;

                case MessageType.Embed:

                    await userChannel.SendEmbedAsync(message.Embed).ConfigureAwait(false);

                    break;

                case MessageType.Mixed:

                    await userChannel.SendMessageAsync(message.Text, embed : message.Embed)
                    .ConfigureAwait(false);

                    break;
                }

                break;

            case DestinationType.GuildChannel:

                if (!IonicHelper.GetTextChannel(Settings.App.MainGuildId, message.DestinationId, out var channel))
                {
                    return;
                }

                switch (message.MessageType)
                {
                case MessageType.PlainText:

                    await channel.SendMessageAsync(message.Text).ConfigureAwait(false);

                    break;

                case MessageType.Embed:

                    await channel.SendEmbedAsync(message.Embed).ConfigureAwait(false);

                    break;

                case MessageType.Mixed:

                    await channel.SendMessageAsync(message.Text, embed : message.Embed).ConfigureAwait(false);

                    break;
                }

                break;
            }
        }
Ejemplo n.º 10
0
        async Task FinishGiveawayAsync(RiftActiveGiveaway expiredGiveaway)
        {
            var dbGiveaway = await DB.Giveaways.GetAsync(expiredGiveaway.GiveawayName);

            var giveawayData = $"ID {expiredGiveaway.Id.ToString()} \"{expiredGiveaway.GiveawayName}\"";

            if (dbGiveaway is null)
            {
                RiftBot.Log.Error($"Could not finish giveaway {giveawayData}: {nameof(RiftGiveaway)} is null!");
                return;
            }

            if (!IonicHelper.GetTextChannel(Settings.App.MainGuildId, Settings.ChannelId.Chat, out var channel))
            {
                RiftBot.Log.Error($"Could not finish giveaway {giveawayData}: Giveaway channel is null!");
                return;
            }

            var message = (IUserMessage)await channel.GetMessageAsync(expiredGiveaway.ChannelMessageId);

            if (message is null)
            {
                RiftBot.Log.Error($"Could not finish giveaway {giveawayData}: Giveaway message is null! Deleted?");
                return;
            }

            if (!IonicHelper.GetEmote(403616665603932162, "giveaway", out var emote))
            {
                RiftBot.Log.Error($"Could not finish giveaway {giveawayData}: Emote is null! Deleted?");
                return;
            }

            // Reaction amount is limited by discord itself.
            // See https://discordapp.com/developers/docs/resources/channel#get-reactions
            var reactions = await message.GetReactionUsersAsync(emote, 100).FlattenAsync();

            if (reactions is null)
            {
                RiftBot.Log.Error($"Could not finish giveaway {giveawayData}: Unable to get reactions.");
                return;
            }

            var dbReward = await DB.Rewards.GetAsync(dbGiveaway.RewardId);

            if (dbReward is null)
            {
                RiftBot.Log.Error($"Could not finish giveaway {giveawayData}: " +
                                  $"Unable to get reward ID {dbGiveaway.RewardId.ToString()}.");
                return;
            }

            var reward = dbReward.ToRewardBase();

            var participants = reactions
                               .Where(x => !x.IsBot && x.Id != IonicHelper.Client.CurrentUser.Id)
                               .Select(x => x.Id)
                               .ToArray();

            if (participants.Length == 0)
            {
                await LogGiveawayAsync(dbGiveaway.Name, null, null,
                                       "No reward provided", expiredGiveaway.StartedBy, expiredGiveaway.StartedAt,
                                       dbGiveaway.Duration);

                await DB.ActiveGiveaways.RemoveAsync(expiredGiveaway.Id);

                RiftBot.Log.Error($"Could not finish giveaway {giveawayData}: No participants.");
                return;
            }

            var winners = new ulong[dbGiveaway.WinnersAmount];

            if (participants.Length < dbGiveaway.WinnersAmount)
            {
                RiftBot.Log.Error($"Could not finish giveaway {giveawayData}: " +
                                  $"Not enough participants: only {participants.Length.ToString()} of minimum {dbGiveaway.WinnersAmount.ToString()}");
                return;
            }

            if (participants.Length == dbGiveaway.WinnersAmount)
            {
                Array.Copy(participants, winners, dbGiveaway.WinnersAmount);
            }
            else
            {
                ulong winnerId;

                for (var i = 0; i < dbGiveaway.WinnersAmount; i++)
                {
                    do
                    {
                        winnerId = participants.Random();
                    } while (winners.Contains(winnerId));

                    winners[i] = winnerId;
                }
            }

            foreach (var winner in winners)
            {
                await rewardService.DeliverToAsync(winner, reward);
            }

            await DB.ActiveGiveaways.RemoveAsync(expiredGiveaway.Id);

            foreach (var participant in participants)
            {
                GiveawaysParticipated?.Invoke(null, new GiveawaysParticipatedEventArgs(participant));
            }

            var log = new RiftGiveawayLog
            {
                Name         = dbGiveaway.Name,
                Winners      = winners,
                Participants = participants,
                Reward       = "No reward provided",
                StartedBy    = expiredGiveaway.StartedBy,
                StartedAt    = expiredGiveaway.StartedAt,
                Duration     = dbGiveaway.Duration,
                FinishedAt   = DateTime.UtcNow,
            };

            await messageService.SendMessageAsync("giveaway-finished", Settings.ChannelId.Chat,
                                                  new FormatData(expiredGiveaway.StartedBy)
            {
                Giveaway = new GiveawayData
                {
                    Log    = log,
                    Stored = dbGiveaway,
                },
                Reward = reward
            });

            await LogGiveawayAsync(log).ConfigureAwait(false);
        }