Beispiel #1
0
 private async void pinMessage_Click(object sender, RoutedEventArgs e)
 {
     if (Message?.IsPinned == false)
     {
         await Message.PinAsync();
     }
 }
Beispiel #2
0
        public async Task StartAsync()
        {
            bool startSucceeded = false;

            await this.DoReadWriteActionOnCurrentTournamentAsync(
                async currentTournament =>
            {
                if (currentTournament?.Stage != TournamentStage.AddPlayers)
                {
                    // !start only applies once we've started adding players
                    this.Logger.Debug("Start failed because we were in stage {stage}", currentTournament?.Stage);
                    await this.SendChannelMessage(BotStrings.CommandOnlyUsedTournamentReadyStart);
                    return;
                }

                await this.UpdateStageAsync(currentTournament, TournamentStage.BotSetup);

                try
                {
                    // TODO: Add more messaging around the current status
                    this.Logger.Debug("Generating tournament");
                    IScheduleFactory scheduleFactory = new RoundRobinScheduleFactory(
                        currentTournament.RoundRobinsCount);

                    currentTournament.Schedule = scheduleFactory.Generate(
                        new HashSet <Team>(currentTournament.Teams),
                        new HashSet <Reader>(currentTournament.Readers));

                    this.Logger.Debug("Tournament generated. Creating channels and roles");
                    await this.Context.Channel.SendMessageAsync(
                        BotStrings.CreatingChannelsAndRoles, options: RequestOptionsSettings.Default);
                    await this.CreateArtifactsAsync(currentTournament);

                    IUserMessage updateMessage = await this.UpdateStageAsync(
                        currentTournament, TournamentStage.RunningTournament);
                    await updateMessage.PinAsync(RequestOptionsSettings.Default);
                    currentTournament.PinnedStartMessageId = updateMessage.Id;

                    startSucceeded = true;
                }
                catch (Exception ex)
                {
                    // TODO: Make the exceptions we catch more defined.
                    // Go back to the previous stage and undo any artifacts added.
                    this.Logger.Error(ex, "Error starting the tournament. Cleaning up the tournament artifacts");
                    await this.CleanupTournamentArtifactsAsync(currentTournament);
                    await this.UpdateStageAsync(currentTournament, TournamentStage.AddPlayers);
                    throw;
                }
            });

            if (startSucceeded)
            {
                await this.Context.Channel.SendMessageAsync(
                    BotStrings.TournamentHasStarted(
                        MentionUtils.MentionChannel(this.Context.Channel.Id)),
                    options : RequestOptionsSettings.Default);
            }
        }
Beispiel #3
0
        public async Task AddPin(IUserMessage message)
        {
            await message.PinAsync();

            using (var db = data.GetContext()) {
                await db.AddPin(message.Channel.Id, message.Id);
            }
        }
Beispiel #4
0
        public Task EnqueueCreate(ICommandContext context, List <string> commands)
        {
            if (createQueues.ContainsKey(context.Guild.Id))
            {
                var queue = createQueues[context.Guild.Id];
                foreach (string command in commands)
                {
                    queue.Enqueue(command);
                }
            }
            else
            {
                createQueues.Add(context.Guild.Id, new Queue <string>(commands));
            }

            if (progress.ContainsKey(context.Guild.Id))
            {
                try
                {
                    progress[context.Guild.Id].ModifyAsync((x) =>
                    {
                        EmbedBuilder embed = progress[context.Guild.Id].Embeds.First().ToEmbedBuilder();
                        embed.Fields.Find((x) => x.Name == "Creations").Value = createQueues[context.Guild.Id].Count;
                        x.Embed = embed.Build();
                    }, options);
                }
                catch (Exception e)
                {
                    _logger.Log(new LogMessage(LogSeverity.Error, nameof(EnqueueCreate), $"Error while editing progress message in Guild {context.Guild.Id}: {e.Message}", e));
                }
            }
            else
            {
                var embed = defaultEmbed.WithCurrentTimestamp();
                embed.Fields[0].Value = createQueues[context.Guild.Id].Count;
                embed.Fields[1].Value = editQueues.ContainsKey(context.Guild.Id) ? editQueues[context.Guild.Id].Count : 0;
                embed.Footer.Text     = $"use {_settings[context.Guild.Id].Prefix}pause or {_settings[context.Guild.Id].Prefix}resume to manage the export!";
                IUserMessage msg = context.Channel.SendMessageAsync(embed: embed.Build()).Result;
                try
                {
                    msg.PinAsync(options);
                }
                catch (Exception e)
                {
                    _logger.Log(new LogMessage(LogSeverity.Error, nameof(EnqueueCreate), $"Error pinning progress message in Guild {context.Guild.Id}: {e.Message}", e));
                }
                progress[context.Guild.Id] = msg;
            }

            if (!workers.ContainsKey(context.Guild.Id) || (workers[context.Guild.Id].IsCompleted && !workers[context.Guild.Id].IsCompleted))
            {
                CancellationTokenSource source = new CancellationTokenSource();
                tokens[context.Guild.Id] = source;
                workers.Add(context.Guild.Id, Work(context.Guild.Id, context.Channel, source.Token));
            }
            return(Task.CompletedTask);
        }
Beispiel #5
0
        private async Task AddRuleboxReactions(Guild guild, IUserMessage rulebox)
        {
            var agreeEmote    = new Emoji(guild.Admin.Rulebox.AgreeEmote) as IEmote;
            var disagreeEmote = new Emoji(guild.Admin.Rulebox.DisagreeEmote) as IEmote;

            await rulebox.AddReactionAsync(agreeEmote);

            await rulebox.AddReactionAsync(disagreeEmote);

            await rulebox.PinAsync();
        }
Beispiel #6
0
        private async Task pinMessage(IUserMessage message, ISocketMessageChannel channel, SocketReaction reaction, IUser user)
        {
            var client = Service.GetRequiredService <DiscordSocketClient>();

            if (message.Author.Id != client.CurrentUser.Id)
            {
                return;
            }

            if (!message.IsPinned)
            {
                await message.PinAsync().ConfigureAwait(false);
            }
        }
Beispiel #7
0
        public Player(SocketGuildUser user, ITextChannel channel)
        {
            _user    = user;
            _channel = channel;


            var pins = channel.GetPinnedMessagesAsync().Result;

            if ((_message = pins.FirstOrDefault() as IUserMessage) == null)
            {
                _message = channel.SendMessageAsync(embed: BuildEmbed(new PlayerData())).Result;
                _message.PinAsync();
            }

            var json = _message.Embeds.First().Fields[0].Value[8..^ 3];
Beispiel #8
0
        private async Task OnReactionAdded(Cacheable <IUserMessage, ulong> msg, ISocketMessageChannel chan, SocketReaction reaction)
        {
            if (reaction.Emote.Name.Equals(PIN_EMOTE))
            {
                IUserMessage m = (IUserMessage)await chan.GetMessageAsync(msg.Id);

                var ReactionList = m.Reactions;
                foreach (KeyValuePair <IEmote, ReactionMetadata> item in ReactionList)
                {
                    if (item.Key.Name.Equals(PIN_EMOTE) && item.Value.ReactionCount >= PIN_THRESHOLD)
                    {
                        await m.PinAsync();
                    }
                }
            }
        }
Beispiel #9
0
        public async Task GenerateAsync([Remainder] string keywords = "")
        {
            int ExpansionCount;

            string[] kwargs = keywords.Split(" ");

            try
            {
                ExpansionCount = int.Parse(kwargs[0]);
            }
            catch (Exception)
            {
                ExpansionCount = 6;
            }

            List <Set> selected  = new List <Set>();
            List <Set> coreSets  = _sets.Where(set => set.Type == Set.SetType.Core).ToList();
            List <Set> legalSets = _sets.Where(set => set.Type == Set.SetType.Expansion).ToList();

            for (int i = 0; i < ExpansionCount; i++)
            {
                Set set;
                do
                {
                    set = legalSets[_rng.Next(legalSets.Count)];
                } while (selected.Contains(set));

                selected.Add(set);
            }

            if (kwargs.Contains("-force--core"))
            {
                selected.Add(coreSets[_rng.Next(coreSets.Count)]);
            }

            IUserMessage message = await ReplyAsync("", false, FormulateEmbed(selected));

            await message.PinAsync();
        }
Beispiel #10
0
        public async Task Setup()
        {
            using DatabaseContext db = _db.CreateDbContext();
            GuildConfiguration config = db.GetGuildConfiguration(Context.GuildId);

            await Context.Channel.SendInfoAsync("Starting setup");

            await Response("Which channel should Availabot be used in? (#mention channel)");

            config.ChannelId = 0;
            while (config.ChannelId == 0)
            {
                MessageReceivedEventArgs response = await Context.WaitForMessageAsync(x => x.Member.Id == Context.Author.Id, TimeSpan.FromMinutes(1));

                if (response is null)
                {
                    await Response("Setup cancelled.");

                    return;
                }
                if (Mention.TryParseChannel(response.Message.Content, out Snowflake channelId) &&
                    Context.Guild.Channels.TryGetValue(channelId, out IGuildChannel guildChannel) &&
                    guildChannel is ITextChannel)
                {
                    config.ChannelId = channelId;
                }
                else
                {
                    await Response("Invalid input, please try again.");
                }
            }

            await Response("Which role should be used to label available users? (@mention role)");

            config.RoleId = 0;
            while (config.RoleId == 0)
            {
                MessageReceivedEventArgs response = await Context.WaitForMessageAsync(x => x.Member.Id == Context.Author.Id, TimeSpan.FromMinutes(1));

                if (response is null)
                {
                    await Response("Setup cancelled.");

                    return;
                }
                if (Mention.TryParseRole(response.Message.Content, out Snowflake roleId) &&
                    Context.Guild.Roles.TryGetValue(roleId, out _))
                {
                    config.RoleId = roleId;
                }
                else
                {
                    await Response("Invalid input, please try again.");
                }
            }

            ITextChannel channel = Context.Guild.Channels.First(x => x.Key == config.ChannelId).Value as ITextChannel;
            IUserMessage message = await channel.SendMessageAsync(new LocalMessageBuilder()
                                                                  .WithContent("This message will be modified shortly...")
                                                                  .WithMentions(LocalMentionsBuilder.None)
                                                                  .Build());

            await message.PinAsync();

            foreach (IEmoji emoji in Constants.NumberEmojis.Take(5))
            {
                await message.AddReactionAsync(emoji);
            }
            await message.AddReactionAsync(Constants.XEmoji);

            config.MessageId = message.Id;

            db.GuildConfigurations.Update(config);
            await db.SaveChangesAsync();

            await _availability.UpdateGuildMessageAsync(Context.GuildId);

            await Context.Channel.SendSuccessAsync("Setup completed");
        }