Пример #1
0
        private static StringBuilder BuildListResponse(PickupQueue queue)
        {
            var sb = new StringBuilder();

            sb.AppendLine($"`!add \"{queue.Name}\"` to join!")
            .AppendLine("")
            .AppendLine($"Created by _{queue.OwnerName}_ {(queue.IsCoop ? "(_coop_)" : "")}")
            .AppendLine("```")
            .AppendLine($"[{queue.Subscribers.Count}/{queue.MaxInQueue}] - {PickupHelpers.ParseSubscribers(queue)}")
            .AppendLine("```");

            if (!queue.WaitingList.IsNullOrEmpty())
            {
                sb.AppendLine($"In waitlist: **{queue.WaitingList.Count}**");
            }
            if (!queue.Games.IsNullOrEmpty())
            {
                sb.AppendLine($"**Game(s): ** _{string.Join(", ", queue.Games)}_");
            }
            if (!string.IsNullOrWhiteSpace(queue.Host))
            {
                sb.AppendLine($"**Server**: _{queue.Host ?? "ra3.se"}:{(queue.Port > 0 ? queue.Port : 27960)}_");
            }
            return(sb);
        }
Пример #2
0
        public static async Task NotifyUsers(PickupQueue queue, string serverName, IUser guildUser, params SocketGuildUser[] users)
        {
            var usersList = string.Join(Environment.NewLine, queue.Subscribers.Where(u => u.Id != guildUser.Id).Select(u => $@"  - {u.Name}"));
            var header    = $"**Contact your teammates on the \"{serverName}\" server and glhf!**";
            var remember  = $"**Remember** {Environment.NewLine}" +
                            $"Remember to do `!leave {queue.Name}` if/when you leave the game to make room for those in the waiting list!";

            var embed = new EmbedBuilder
            {
                Title       = $"Queue {queue.Name} is ready to go!",
                Description = $@"{header}{Environment.NewLine}{usersList}{Environment.NewLine}{remember}",
                Footer      = new EmbedFooterBuilder {
                    Text = $"Provided by pickup-bot - {serverName}"
                },
                Color = Color.Orange
            }.Build();

            foreach (var user in users)
            {
                try
                {
                    await user.SendMessageAsync(embed : embed);

                    await Task.Delay(500);
                }
                catch (Exception)
                {
                    //_logger.LogError($"Failed to send DM to {PickupHelpers.GetNickname(user)}", ex);
                }
            }
        }
Пример #3
0
        public async Task Promote([Name("Queue name"), Summary("Queue name"), Remainder] string queueName = "")
        {
            if (!PickupHelpers.IsInPickupChannel((IGuildChannel)Context.Channel))
            {
                return;
            }

            queueName = queueName.Trim(' ', '"').Trim();

            PickupQueue queue = null;

            if (!string.IsNullOrWhiteSpace(queueName))
            {
                queue = await _queueRepository.FindQueue(queueName, Context.Guild.Id.ToString());

                if (queue == null)
                {
                    await Context.Channel.SendMessageAsync($"`Queue with the name '{queueName}' doesn't exists!`").AutoRemoveMessage(10);

                    return;
                }

                if (queue.MaxInQueue <= queue.Subscribers.Count)
                {
                    await ReplyAsync("Queue is full, why the spam?").AutoRemoveMessage(10);

                    return;
                }
            }

            await _listCommandService.Promote(queue, (ITextChannel)Context.Channel, (IGuildUser)Context.User);
        }
Пример #4
0
        public async Task <PickupQueue> Leave(PickupQueue queue, ISocketMessageChannel channel, IGuildUser user, bool notify = true)
        {
            var guild      = (SocketGuild)user.Guild;
            var subscriber = queue.Subscribers.FirstOrDefault(s => s.Id == user.Id);

            if (subscriber != null)
            {
                queue.Updated = DateTime.UtcNow;
                queue.Subscribers.Remove(subscriber);

                await MoveUserFromWaitingListToSubscribers(queue, subscriber, channel, guild);

                if (!queue.Subscribers.Any() && !queue.WaitingList.Any())
                {
                    notify = await _listCommandService.DeleteEmptyQueue(queue, guild, channel, notify);
                }
                else
                {
                    queue = await _listCommandService.SaveStaticQueueMessage(queue, guild);

                    await _queueRepository.UpdateQueue(queue);

                    queue = await _queueRepository.FindQueue(queue.Name, queue.GuildId);
                }
            }

            if (notify)
            {
                await channel.SendMessageAsync($"`{queue.Name} - {PickupHelpers.ParseSubscribers(queue)}`").AutoRemoveMessage(10);
            }

            return(queue);
        }
Пример #5
0
        private static async Task MoveUserFromWaitingListToSubscribers(PickupQueue queue, Subscriber subscriber, ISocketMessageChannel channel, SocketGuild guild)
        {
            if (queue.WaitingList.Any())
            {
                var next = queue.WaitingList.First();
                queue.WaitingList.RemoveAt(0);

                queue.Subscribers.Add(next);

                var nextUser = guild.GetUser(next.Id);
                if (nextUser != null)
                {
                    await channel.SendMessageAsync($"{PickupHelpers.GetMention(nextUser)} - you have been added to '{queue.Name}' since {subscriber.Name} has left.").AutoRemoveMessage();

                    if (queue.Started)
                    {
                        var team = queue.Teams.FirstOrDefault(w => w.Subscribers.Exists(s => s.Id == subscriber.Id));
                        if (team != null)
                        {
                            team.Subscribers.Remove(team.Subscribers.Find(s => s.Id == subscriber.Id));
                            team.Subscribers.Add(new Subscriber {
                                Name = PickupHelpers.GetNickname(nextUser), Id = nextUser.Id
                            });
                            await channel.SendMessageAsync($"{PickupHelpers.GetMention(nextUser)} - you are on the {team.Name}")
                            .AutoRemoveMessage()
                            ;
                        }
                    }

                    await PickupHelpers.NotifyUsers(queue, guild.Name, nextUser);
                }
            }
        }
Пример #6
0
        public async Task PrintTeams(PickupQueue queue, ISocketMessageChannel channel, IGuild guild)
        {
            if (!queue.Started || queue.Teams.IsNullOrEmpty())
            {
                return;
            }

            foreach (var team in queue.Teams)
            {
                var sb = new StringBuilder()
                         .AppendLine("**Teammates:**")
                         .AppendLine($"{string.Join(Environment.NewLine, team.Subscribers.Select(w => w.Name))}")
                         .AppendLine("")
                         .AppendLine("Your designated voice channel:")
                         .AppendLine($"[<#{team.VoiceChannel.Value}>](https://discordapp.com/channels/{guild.Id}/{team.VoiceChannel.Value})");

                await channel.SendMessageAsync(embed : new EmbedBuilder
                {
                    Title       = team.Name,
                    Description = sb.ToString(),
                    Color       = Color.Red
                }.Build())
                .AutoRemoveMessage(120);
            }
        }
        public void TriggerDelayedRconNotification(PickupQueue queue)
        {
            // 2 minute delay message
            AsyncUtilities.DelayAction(TimeSpan.FromMinutes(2), async t => { await TriggerRconNotification(queue); });

            // 4 minute delay message
            AsyncUtilities.DelayAction(TimeSpan.FromMinutes(4), async t => { await TriggerRconNotification(queue); });
        }
Пример #8
0
        public virtual BlockEvent Pickup()
        {
            var pickup = new BlockEvent(World.Environment, TriggerDropoff, CancelPick);

            PickupQueue.AddLast(pickup);
            TriggerPickup();
            return(pickup);
        }
 // Token: 0x0600379C RID: 14236
 public static void FoundPickup(RandomizerAction action, int coords)
 {
     try {
         Pickup pickup = new Pickup(action, coords);
         PickupQueue.Enqueue(pickup);
     } catch (Exception e) {
         Randomizer.LogError("FoundPickup: " + e.Message);
     }
 }
Пример #10
0
        private void CancelPick(Event e)
        {
            var se = e as StackingEvent;

            if (se == null)
            {
                return;
            }
            PickupQueue.Remove(se);
        }
        public async Task <bool> UpdateQueue(PickupQueue queue)
        {
            var key = $"{queue.Name.ToLowerInvariant()}-{queue.GuildId}";

            _queueCache.TryGetValue(key, out var oldQueue);

            var result = _queueCache.TryUpdate(key, queue, oldQueue);

            return(await Task.FromResult(result));
        }
Пример #12
0
        public virtual StackEvent Pickup(int size)
        {
            var pickup = new StackEvent(World.Environment, TriggerDropoff, CancelPick)
            {
                Size = size
            };

            PickupQueue.AddLast(pickup);
            TriggerPickup();
            return(pickup);
        }
        public async Task <bool> AddQueue(PickupQueue queue)
        {
            var key = $"{queue.Name.ToLowerInvariant()}-{queue.GuildId}";

            if (!_queueCache.ContainsKey(key))
            {
                return(_queueCache.TryAdd(key, queue));
            }

            return(await Task.FromResult(false));
        }
Пример #14
0
        private static string ParseSubscribers(PickupQueue queue)
        {
            var subscribers = queue.Subscribers.Select(w => w.Name).ToList();

            if ((queue.MaxInQueue) - queue.Subscribers.Count > 0)
            {
                subscribers.AddRange(Enumerable.Repeat("[?]", (queue.MaxInQueue) - queue.Subscribers.Count));
            }

            //if queue found and user is in queue
            return(string.Join(", ", subscribers));
        }
        public async Task <bool> RemoveQueue(PickupQueue queue)
        {
            if (queue == null)
            {
                return(false);
            }
            if (string.IsNullOrWhiteSpace(queue.PartitionKey) || string.IsNullOrWhiteSpace(queue.RowKey))
            {
                return(false);
            }
            var result = await _client.Delete(queue);

            return(result);
        }
Пример #16
0
        private static EmbedBuilder CreateStaticQueueMessageEmbed(PickupQueue queue, IUser user)
        {
            var embed = new EmbedBuilder
            {
                Title  = queue.Name,
                Author = new EmbedAuthorBuilder {
                    Name = PickupHelpers.GetNickname(user), IconUrl = user.GetAvatarUrl() ?? user.GetDefaultAvatarUrl()
                },
                Color  = Color.Gold,
                Fields = new List <EmbedFieldBuilder>
                {
                    new EmbedFieldBuilder {
                        Name = "**Created by**", Value = PickupHelpers.GetNickname(user), IsInline = true
                    },
                    new EmbedFieldBuilder
                    {
                        Name     = "**Game(s)**",
                        Value    = string.Join(", ", queue.Games.IsNullOrEmpty() ? new[] { "No game defined" } : queue.Games),
                        IsInline = true
                    },
                    new EmbedFieldBuilder {
                        Name = "**Started**", Value = queue.Started ? "Yes" : "No", IsInline = true
                    },
                    new EmbedFieldBuilder {
                        Name = "**Host**", Value = queue.Host ?? "No host defined", IsInline = true
                    },
                    new EmbedFieldBuilder
                    {
                        Name     = "**Port**",
                        Value    = queue.Port == 0 ? "No port defined" : queue.Port.ToString(),
                        IsInline = true
                    },
                    new EmbedFieldBuilder {
                        Name = "**Team size**", Value = queue.TeamSize, IsInline = true
                    },
                    new EmbedFieldBuilder {
                        Name = "**Coop**", Value = queue.IsCoop ? "Yes" : "No", IsInline = true
                    },
                    new EmbedFieldBuilder {
                        Name = "**Created**", Value = queue.Created.ToString("yyyy-MM-dd\r\nHH:mm:ss 'UTC'"), IsInline = true
                    },
                    new EmbedFieldBuilder {
                        Name = "**Last updated**", Value = queue.Updated.ToString("yyyy-MM-dd\r\nHH:mm:ss 'UTC'"), IsInline = true
                    }
                }
            };

            return(embed);
        }
Пример #17
0
        private static void AddWaitingListFieldsToStaticQueueMessageFields(PickupQueue queue, EmbedBuilder embed)
        {
            var sb = new StringBuilder();

            queue.WaitingList.Select((p, i) => $"{i}. {p.Name}").ToList().ForEach(p => sb.AppendLine(p));

            embed.WithFields(new EmbedFieldBuilder
            {
                Name     = $"**Players in waiting list [{queue.WaitingList.Count}]**",
                Value    = queue.WaitingList.IsNullOrEmpty() ? "No players in waiting list" : sb.ToString(),
                IsInline = true
            });

            sb.Clear();
        }
Пример #18
0
        private static void AddSubscriberFieldsToStaticQueueMessageFields(PickupQueue queue, EmbedBuilder embed)
        {
            var sb = new StringBuilder();

            queue.Subscribers.ForEach(p => sb.AppendLine(p.Name));

            embed.WithFields(new EmbedFieldBuilder
            {
                Name     = $"**Players in queue [{queue.Subscribers.Count}/{queue.MaxInQueue}]**",
                Value    = queue.Subscribers.IsNullOrEmpty() ? "No players in queue" : sb.ToString(),
                IsInline = true
            });

            sb.Clear();
        }
Пример #19
0
        public async Task TriggerRconNotification(PickupQueue queue)
        {
            if (!queue.Rcon)
            {
                return;
            }

            var rconPassword = "";
            var rconPort     = 0;
            var rconHost     = "";

            var server = await _serverRepository.Find(Convert.ToUInt64(queue.GuildId), queue.Host);

            if (server != null)
            {
                rconPort     = server.Port;
                rconHost     = server.Host;
                rconPassword = !string.IsNullOrWhiteSpace(server.RconPassword) ?
                               EncryptionProvider.AESDecrypt(server.RconPassword, _encryptionSettings.Key, _encryptionSettings.IV) :
                               string.Empty;
            }

            if (string.IsNullOrWhiteSpace(rconPassword) || string.IsNullOrWhiteSpace(rconHost) || rconPort == 0)
            {
                return;
            }

            try
            {
                var redTeam  = queue.Teams.FirstOrDefault();
                var blueTeam = queue.Teams.LastOrDefault();

                var command = $"say \"^2Pickup '^3{queue.Name}^2' has started! " +
                              $"^1RED TEAM: ^5{string.Join(", ", redTeam.Subscribers.Select(w => w.Name))} ^7- " +
                              $"^4BLUE TEAM: ^5{string.Join(", ", blueTeam.Subscribers.Select(w => w.Name))}\"";

                await RCON.UDPSendCommand(command, rconHost, rconPassword, rconPort, true);
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
            }
        }
Пример #20
0
        public async Task <PickupQueue> Create(string queueName, int?teamSize, string operators, SocketGuildUser user)
        {
            var ops         = OperatorParser.Parse(operators);
            var rconEnabled = ops?.ContainsKey("-rcon") ?? true;

            if (ops?.ContainsKey("-norcon") == true)
            {
                rconEnabled = false;
            }

            var queue = new PickupQueue(user.Guild.Id.ToString(), queueName)
            {
                Name        = queueName,
                GuildId     = user.Guild.Id.ToString(),
                OwnerName   = PickupHelpers.GetNickname(user),
                OwnerId     = user.Id.ToString(),
                Created     = DateTime.UtcNow,
                Updated     = DateTime.UtcNow,
                TeamSize    = teamSize ?? 4,
                IsCoop      = ops?.ContainsKey("-coop") ?? false,
                Rcon        = rconEnabled,
                Subscribers = new List <Subscriber>
                {
                    new Subscriber {
                        Id = user.Id, Name = PickupHelpers.GetNickname(user)
                    }
                },
                Host  = ops?.ContainsKey("-host") ?? false ? ops["-host"]?.FirstOrDefault() : null,
                Port  = int.Parse((ops?.ContainsKey("-port") ?? false ? ops["-port"]?.FirstOrDefault() : null) ?? "0"),
                Games = ops?.ContainsKey("-game") ?? false ? ops["-game"] : Enumerable.Empty <string>(),
            };

            await _queueRepository.AddQueue(queue);

            queue = await _queueRepository.FindQueue(queue.Name, user.Guild.Id.ToString());

            queue = await SaveStaticQueueMessage(queue, user.Guild);

            await _queueRepository.UpdateQueue(queue);

            return(queue);
        }
Пример #21
0
        public async Task <PickupQueue> SaveStaticQueueMessage(PickupQueue queue, SocketGuild guild)
        {
            var queuesChannel = await PickupHelpers.GetPickupQueuesChannel(guild);

            var user = guild.GetUser(Convert.ToUInt64(queue.OwnerId));

            var embed = CreateStaticQueueMessageEmbed(queue, user);

            AddSubscriberFieldsToStaticQueueMessageFields(queue, embed);
            AddWaitingListFieldsToStaticQueueMessageFields(queue, embed);

            embed.WithFields(
                new EmbedFieldBuilder {
                Name = "\u200b", Value = "\u200b"
            },
                new EmbedFieldBuilder
            {
                Name  = "**Available actions**",
                Value = $"\u2705 - Add to pickup / remove from pickup\r\n" +
                        $"\uD83D\uDCE2 - Promote pickup"
            }
                );

            if (string.IsNullOrEmpty(queue.StaticMessageId))
            {
                var message = await queuesChannel.SendMessageAsync(embed : embed.Build());

                await message.AddReactionsAsync(new IEmote[] { new Emoji("\u2705"), new Emoji("\uD83D\uDCE2") }); // timer , new Emoji("\u23F2")

                queue.StaticMessageId = message.Id.ToString();
            }
            else
            {
                if (await queuesChannel.GetMessageAsync(Convert.ToUInt64(queue.StaticMessageId)) is IUserMessage message)
                {
                    await message.ModifyAsync(m => { m.Embed = embed.Build(); });
                }
            }

            return(queue);
        }
Пример #22
0
 protected virtual void TriggerPickup(Event @event = null)
 {
     while (PickupQueue.Count > 0)
     {
         var get = PickupQueue.First.Value;
         DoPickup(get);
         if (get.IsTriggered)
         {
             PickupQueue.RemoveFirst();
             TriggerWhenEmpty();
             TriggerWhenChange();
         }
         else
         {
             break;
         }
     }
     Utilization?.UpdateTo(Location.Height / (double)Location.MaxHeight);
     WIP?.UpdateTo(Location.Height + DropoffQueue.Count + PickupQueue.Count);
     PickupQueueLength?.UpdateTo(PickupQueue.Count);
 }
Пример #23
0
        private async Task <PickupQueue> LeaveInternal(PickupQueue queue, bool notify = true)
        {
            var subscriber = queue.Subscribers.FirstOrDefault(s => s.Id == Context.User.Id);

            if (subscriber != null)
            {
                queue.Updated = DateTime.UtcNow;
                queue.Subscribers.Remove(subscriber);

                if (queue.WaitingList.Any())
                {
                    var next = queue.WaitingList.First();
                    queue.WaitingList.RemoveAt(0);

                    queue.Subscribers.Add(next);

                    var user = Context.Guild.GetUser(next.Id);
                    if (user != null)
                    {
                        await ReplyAsync($"{GetMention(user)} - you have been added to '{queue.Name}' since {subscriber.Name} has left.");
                        await NotifyUsers(queue, Context.Guild.Name, user);
                    }
                }
                if (!queue.Subscribers.Any() && !queue.WaitingList.Any())
                {
                    await _queueRepository.RemoveQueue(Context.User, queue.Name, queue.GuildId); //Try to remove queue if its empty and its the owner leaving.
                }
                else
                {
                    await _queueRepository.UpdateQueue(queue);

                    if (notify)
                    {
                        await Context.Channel.SendMessageAsync($"`{queue.Name} - {ParseSubscribers(queue)}`");
                    }
                }
            }

            return(queue);
        }
 // Token: 0x06003794 RID: 14228
 public static void Update()
 {
     try
     {
         if (SendingPickup == null && PickupQueue.Count > 0 && !webClient.IsBusy)
         {
             SendingPickup = PickupQueue.Dequeue();
             webClient.DownloadStringAsync(SendingPickup.GetURL());
         }
         else if (Randomizer.SyncId != "" && !SeedSent)
         {
             UploadSeed();
         }
         Countdown--;
         ChaosTimeoutCounter--;
         if (ChaosTimeoutCounter < 0)
         {
             RandomizerChaosManager.ClearEffects();
             ChaosTimeoutCounter = 216000;
         }
         if (Countdown <= 0 && !getClient.IsBusy)
         {
             Countdown = 60 * PERIOD;
             NameValueCollection nvc = new NameValueCollection();
             Vector3             pos = Characters.Sein.Position;
             nvc["x"] = pos.x.ToString();
             nvc["y"] = pos.y.ToString();
             for (int i = 0; i < 8; i++)
             {
                 nvc["seen_" + i.ToString()] = fixInt(Characters.Sein.Inventory.GetRandomizerItem(1560 + i));
                 nvc["have_" + i.ToString()] = fixInt(Characters.Sein.Inventory.GetRandomizerItem(930 + i));
             }
             Uri uri = new Uri(RootUrl + "/tick/");
             getClient.UploadValuesAsync(uri, nvc);
         }
     } catch (Exception e) {
         Randomizer.LogError("RSM.Update: " + e.Message);
     }
 }
Пример #25
0
        public async Task <bool> DeleteEmptyQueue(PickupQueue queue, SocketGuild guild, ISocketMessageChannel channel, bool notify)
        {
            var result = await _queueRepository.RemoveQueue(queue.Name, queue.GuildId); //Try to remove queue if its empty

            if (result)
            {
                var queuesChannel = await PickupHelpers.GetPickupQueuesChannel(guild);

                if (!string.IsNullOrEmpty(queue.StaticMessageId))
                {
                    await queuesChannel.DeleteMessageAsync(Convert.ToUInt64(queue.StaticMessageId));
                }
            }

            if (!notify)
            {
                return(false);
            }

            await channel.SendMessageAsync($"`{queue.Name} has been removed since everyone left.`").AutoRemoveMessage(10);

            return(false);
        }
Пример #26
0
        private async Task NotifyUsers(PickupQueue queue, string serverName, params SocketGuildUser[] users)
        {
            var usersList = string.Join(Environment.NewLine, queue.Subscribers.Where(u => u.Id != Context.User.Id).Select(u => $@"  - {u.Name}"));
            var header    = $"**Contact your teammates on the \"{serverName}\" server and glhf!**";
            var remember  = "**Remember**" +
                            $"{Environment.NewLine}" +
                            $"Remember to do `!leave {queue.Name}` if/when you leave the game to make room for those in the waiting list!";

            var embed = new EmbedBuilder
            {
                Title       = $"Queue {queue.Name} is ready to go!",
                Description = $@"{header}{Environment.NewLine}{usersList}{Environment.NewLine}{remember}",
                Footer      = new EmbedFooterBuilder {
                    Text = $"Provided by pickup-bot - {serverName}"
                },
                Color = Color.Orange
            }.Build();

            foreach (var user in users)
            {
                await user.SendMessageAsync(embed : embed);
            }
        }
Пример #27
0
        private static StringBuilder BuildPromoteMessage(PickupQueue queue, IGuildChannel pickupChannel)
        {
            var sb = new StringBuilder()
                     .AppendLine("**Current queue**")
                     .AppendLine($"`{PickupHelpers.ParseSubscribers(queue)}`")
                     .AppendLine("")
                     .AppendLine($"**Spots left**: {queue.MaxInQueue - queue.Subscribers.Count}")
                     .AppendLine($"**Team size**: {queue.TeamSize}")
                     .AppendLine("")
                     .AppendLine($"Just run `!add \"{queue.Name}\"` in channel <#{pickupChannel.Id}> on the **{pickupChannel.Guild.Name}** server to join!")
                     .AppendLine("");

            if (!queue.Games.IsNullOrEmpty())
            {
                sb.AppendLine($"**Game(s): ** _{string.Join(", ", queue.Games)}_");
            }

            if (!string.IsNullOrWhiteSpace(queue.Host))
            {
                sb.AppendLine($"**Server**: _{queue.Host ?? "ra3.se"}:{(queue.Port > 0 ? queue.Port : 27960)}_");
            }

            return(sb);
        }
Пример #28
0
        public async Task Promote(PickupQueue queue, ITextChannel pickupChannel, IGuildUser user)
        {
            var guild    = (SocketGuild)user.Guild;
            var activity = await _activitiesRepository.Find(user);

            activity.PickupPromote += 1;
            await _activitiesRepository.Update(activity);

            if (queue?.MaxInQueue <= queue?.Subscribers.Count)
            {
                await pickupChannel.SendMessageAsync("Queue is full, why the spam?").AutoRemoveMessage(10);

                return;
            }

            var role = guild.Roles.FirstOrDefault(w => w.Name == RoleNames.PickupPromote);

            if (role == null)
            {
                return;               //Failed to get role;
            }
            var users = guild.Users.Where(w => w.Roles.Any(r => r.Id == role.Id)).ToList();

            if (!users.Any())
            {
                await pickupChannel.SendMessageAsync("No users have subscribed using the `!subscribe` command.")
                .AutoRemoveMessage(10);

                return;
            }

            using (pickupChannel.EnterTypingState())
            {
                if (queue == null)
                {
                    var queues = await _queueRepository.AllQueues(user.GuildId.ToString());

                    var filtered = queues.Where(q => q.MaxInQueue > q.Subscribers.Count).ToArray();
                    if (filtered.Any())
                    {
                        await pickupChannel.SendMessageAsync($"There are {filtered.Length} pickup queues with spots left, check out the `!list`! - {role.Mention}")
                        .AutoRemoveMessage();
                    }
                }
                else
                {
                    var sb    = BuildPromoteMessage(queue, pickupChannel);
                    var embed = new EmbedBuilder
                    {
                        Title       = $"Pickup queue {queue.Name} needs more players",
                        Description = sb.ToString(),
                        Author      = new EmbedAuthorBuilder {
                            Name = "pickup-bot"
                        },
                        Color = Color.Orange
                    }.Build();

                    foreach (var u in users)
                    {
                        await u.SendMessageAsync(embed : embed);

                        await Task.Delay(TimeSpan.FromMilliseconds(200));
                    }
                }
            }
        }
Пример #29
0
        public async Task Promote([Name("Queue name"), Summary("Queue name"), Remainder] string queueName = "")
        {
            PickupQueue queue = null;

            if (!string.IsNullOrWhiteSpace(queueName))
            {
                queue = await _queueRepository.FindQueue(queueName, Context.Guild.Id.ToString());

                if (queue == null)
                {
                    await Context.Channel.SendMessageAsync($"`Queue with the name '{queueName}' doesn't exists!`");

                    return;
                }

                if (queue.MaxInQueue <= queue.Subscribers.Count)
                {
                    await ReplyAsync("Queue is full, why the spam?");

                    return;
                }
            }

            var role = Context.Guild.Roles.FirstOrDefault(w => w.Name == "pickup-promote") ??
                       (IRole)await Context.Guild.CreateRoleAsync("pickup-promote", GuildPermissions.None, Color.Orange,
                                                                  false);

            if (role == null)
            {
                return; //Failed to get or create role;
            }
            await Context.Channel.TriggerTypingAsync();

            var users = Context.Guild.Users.Where(w => w.Roles.Any(r => r.Id == role.Id)).ToList();

            if (!users.Any())
            {
                await ReplyAsync("No users have subscribed using the `!subscribe` command.");

                return;
            }

            if (string.IsNullOrWhiteSpace(queueName))
            {
                var queues = await _queueRepository.AllQueues(Context.Guild.Id.ToString());

                var filtered = queues.Where(q => q.MaxInQueue > q.Subscribers.Count).ToArray();
                if (filtered.Any())
                {
                    await ReplyAsync($"There are {filtered.Length} pickup queues with spots left, check out the `!list`! - {role.Mention}");
                }
            }
            else if (queue != null)
            {
                var voiceChannel = Context.Guild.VoiceChannels.OrderBy(c => c.Position).FirstOrDefault();
                var embed        = new EmbedBuilder
                {
                    Title       = $"Pickup queue {queue.Name} needs more players",
                    Description = "**Current queue**" +
                                  $"{Environment.NewLine} " +
                                  $"{ParseSubscribers(queue)}" +
                                  $"{Environment.NewLine}{Environment.NewLine}" +
                                  $"**Spots left**: {queue.MaxInQueue - queue.Subscribers.Count}" +
                                  $"{Environment.NewLine}" +
                                  $"**Team size**: {queue.TeamSize}" +
                                  $"{Environment.NewLine}{Environment.NewLine}" +
                                  $"Just run `!add {queue.Name}` in channel <#{Context.Channel.Id}> on the **{Context.Guild.Name}** server to join!"
                                  /*$"voice channel [<#{voiceChannel?.Id}>](https://discordapp.com/channels/{Context.Guild.Id}/{voiceChannel?.Id})"*/,
                    Author = new EmbedAuthorBuilder {
                        Name = "pickup-bot"
                    },
                    Color = Color.Orange
                }.Build();

                var tasks = users.Select(user => user.SendMessageAsync(embed: embed));

                await Task.WhenAll(tasks);
            }
        }
Пример #30
0
        public async Task Add([Name("Queue name"), Summary("Queue name"), Remainder] string queueName = "")
        {
            //find queue with name {queueName}
            PickupQueue queue = null;

            if (!string.IsNullOrWhiteSpace(queueName))
            {
                queue = await _queueRepository.FindQueue(queueName, Context.Guild.Id.ToString());
            }
            else
            {
                var queues = (await _queueRepository.AllQueues(Context.Guild.Id.ToString())).OrderByDescending(w => w.Readiness).ToList();
                queue = queues.Any(q => q.Readiness < 100) ? queues.FirstOrDefault(q => q.Readiness < 100) : queues.FirstOrDefault();
            }

            if (queue == null)
            {
                await Context.Channel.SendMessageAsync($"`Queue with the name '{queueName}' doesn't exists!`");

                return;
            }

            if (!await VerifyUserFlaggedStatus())
            {
                return;
            }

            if (queue.Subscribers.Any(w => w.Id == Context.User.Id))
            {
                await Context.Channel.SendMessageAsync($"`{queue.Name} - {ParseSubscribers(queue)}`");

                return;
            }

            if (queue.Subscribers.Count >= queue.MaxInQueue)
            {
                if (queue.WaitingList.All(w => w.Id != Context.User.Id))
                {
                    queue.Updated = DateTime.UtcNow;
                    queue.WaitingList.Add(new Subscriber {
                        Id = Context.User.Id, Name = GetNickname(Context.User)
                    });

                    await _queueRepository.UpdateQueue(queue);

                    await ReplyAsync($"`You have been added to the '{queue.Name}' waiting list`");
                }
                else
                {
                    await ReplyAsync($"`You are already on the '{queue.Name}' waiting list`");
                }

                return;
            }

            queue.Updated = DateTime.UtcNow;
            queue.Subscribers.Add(new Subscriber {
                Id = Context.User.Id, Name = GetNickname(Context.User)
            });

            //if queue found
            await _queueRepository.UpdateQueue(queue);

            if (queue.Subscribers.Count == queue.MaxInQueue)
            {
                await NotifyUsers(queue, Context.Guild.Name, queue.Subscribers.Select(subscriber => Context.Guild.GetUser(subscriber.Id)).ToArray());
            }

            await Context.Channel.SendMessageAsync($"`{queue.Name} - {ParseSubscribers(queue)}`");
        }