Пример #1
0
        protected override void GetDisplayContent(ChannelLink link, out List <Tuple <string, DiscordEmbed> > tagAndContent)
        {
            tagAndContent = new List <Tuple <string, DiscordEmbed> >();
            DiscordEmbedBuilder builder = new DiscordEmbedBuilder();

            builder.WithColor(MessageBuilder.EmbedColor);
            foreach (Election election in ElectionManager.Obj.CurrentElections.Where(x => x.Valid() && x.State == Shared.Items.ProposableState.Active))
            {
                string tag = BaseTag + " [" + election.Id + "]";
                builder.WithTitle(election.Name);

                // Proposer name
                builder.AddField("Proposer", election.Creator.Name);

                // Time left
                builder.AddField("Time Left", TimeFormatter.FormatSpan(election.TimeLeft));

                // Process
                builder.AddField("Process", election.Process.Name);

                // Choices
                if (!election.BooleanElection && election.Choices.Count > 0)
                {
                    string choiceDesc = string.Empty;
                    foreach (ElectionChoice choice in election.Choices)
                    {
                        choiceDesc += choice.Name + "\n";
                    }
                    builder.AddField("Choices", choiceDesc);
                }

                // Votes
                string voteDesc = string.Empty;
                foreach (RunoffVote vote in election.Votes)
                {
                    string topChoiceName = null;
                    int    topChoiceID   = vote.RankedVotes.FirstOrDefault();
                    foreach (ElectionChoice choice in election.Choices)
                    {
                        if (choice.ID == topChoiceID)
                        {
                            topChoiceName = choice.Name;
                            break;
                        }
                    }
                    voteDesc += vote.Voter.Name + ": " + topChoiceName + "\n";
                }
                if (string.IsNullOrEmpty(voteDesc))
                {
                    voteDesc = "--- No Votes Recorded ---";
                }
                builder.AddField("Votes (" + election.TotalVotes + ")", voteDesc);

                if (builder.Fields.Count > 0)
                {
                    tagAndContent.Add(new Tuple <string, DiscordEmbed>(tag, builder.Build()));
                }
                builder.ClearFields();
            }
        }
Пример #2
0
        public override async Task OnMessageDeleted(DiscordMessage message)
        {
            if (message.IsDm())
            {
                return;
            }

            using (await _overlapLock.LockAsync()) // Avoid crashes caused by data being manipulated and used simultaneously
            {
                for (int i = 0; i < DLConfig.Data.SnippetChannels.Count; ++i)
                {
                    ChannelLink link = DLConfig.Data.SnippetChannels[i];
                    if (!link.IsValid())
                    {
                        continue;
                    }

                    string channel = link.DiscordChannel.ToLower();
                    if (channel == message.Channel.Name.ToLower() || channel == message.ChannelId.ToString())
                    {
                        await ReloadSnippets();

                        break;
                    }
                }
            }
            await base.OnMessageDeleted(message);
        }
Пример #3
0
        protected override void GetDisplayContent(ChannelLink link, out List <Tuple <string, DiscordEmbed> > tagAndContent)
        {
            DiscordEmbed content = MessageBuilder.GetServerInfo(GetServerInfoFlagForChannel(link as ServerInfoChannel));

            tagAndContent = new List <Tuple <string, DiscordEmbed> >();
            tagAndContent.Add(new Tuple <string, DiscordEmbed>(BaseTag, content));
        }
Пример #4
0
        private static Channel EnsureChannelForDvbEpg(SchedulerServiceAgent tvSchedulerAgent, TvDatabase.Channel mpChannel,
                                                      bool epgSyncAutoCreateChannels, bool epgSyncAutoCreateChannelsWithGroup)
        {
            ChannelLink channelLink = ChannelLinks.GetChannelLinkForMediaPortalChannel(mpChannel);
            ChannelType channelType = mpChannel.IsTv ? ChannelType.Television : ChannelType.Radio;
            Channel     channel     = null;

            if (channelLink != null)
            {
                channel = tvSchedulerAgent.GetChannelById(channelLink.ChannelId);
                if (channel == null)
                {
                    channel = tvSchedulerAgent.GetChannelByDisplayName(channelType, channelLink.ChannelName);
                }
            }
            if (channel == null)
            {
                channel = tvSchedulerAgent.GetChannelByDisplayName(channelType, mpChannel.DisplayName);
            }
            if (channel == null &&
                (epgSyncAutoCreateChannels || epgSyncAutoCreateChannelsWithGroup))
            {
                string groupName = "DVB-EPG";
                if (epgSyncAutoCreateChannelsWithGroup)
                {
                    IList <TvDatabase.GroupMap> groupMaps = mpChannel.ReferringGroupMap();
                    foreach (TvDatabase.GroupMap groupMap in groupMaps)
                    {
                        TvDatabase.ChannelGroup channelGroup = TvDatabase.ChannelGroup.Retrieve(groupMap.IdGroup);
                        if (channelGroup != null)
                        {
                            groupName = channelGroup.GroupName;
                            break;
                        }
                    }
                }

                Guid channelId = tvSchedulerAgent.EnsureChannel(channelType, mpChannel.DisplayName, groupName);
                channel = tvSchedulerAgent.GetChannelById(channelId);

                if (!channel.LogicalChannelNumber.HasValue &&
                    mpChannel.ChannelNumber > 0)
                {
                    channel.LogicalChannelNumber = mpChannel.ChannelNumber;
                    tvSchedulerAgent.SaveChannel(channel);
                }
            }
            return(channel);
        }
Пример #5
0
        protected override void GetDisplayContent(ChannelLink link, out List <Tuple <string, DiscordEmbed> > tagAndContent)
        {
            string tag     = BaseTag;
            string title   = "Players";
            string content = "\n" + MessageBuilder.GetPlayerList();

            if ((link as PlayerListChannelLink).UsePlayerCount == true)
            {
                title = MessageBuilder.GetPlayerCount() + " Players Online";
            }

            DiscordEmbedBuilder embed = new DiscordEmbedBuilder()
                                        .WithColor(MessageBuilder.EmbedColor)
                                        .WithTitle(title)
                                        .WithDescription(content);

            tagAndContent = new List <Tuple <string, DiscordEmbed> >();
            tagAndContent.Add(new Tuple <string, DiscordEmbed>(tag, embed));
        }
Пример #6
0
        private async Task FindMessages(DiscordLink plugin)
        {
            _targetDisplays.Clear();

            foreach (DiscordTarget target in GetDiscordTargets())
            {
                IReadOnlyList <DiscordMessage> targetMessages = null;

                ChannelLink channelLink = target as ChannelLink;
                UserLink    userLink    = target as UserLink;
                if (channelLink == null && userLink == null)
                {
                    continue;
                }

                TargetDisplayData data = new TargetDisplayData(target);
                _targetDisplays.Add(data);
                if (channelLink != null)
                {
                    if (!channelLink.IsValid())
                    {
                        continue;
                    }

                    // Get the channel and verify permissions
                    DiscordGuild discordGuild = plugin.GuildByNameOrId(channelLink.DiscordGuild);
                    if (discordGuild == null)
                    {
                        continue;
                    }
                    DiscordChannel discordChannel = discordGuild.ChannelByNameOrId(channelLink.DiscordChannel);
                    if (discordChannel == null)
                    {
                        continue;
                    }
                    if (!DiscordUtil.ChannelHasPermission(discordChannel, Permissions.ReadMessageHistory))
                    {
                        continue;
                    }
                    targetMessages = await DiscordUtil.GetMessagesAsync(discordChannel);
                }
                else if (userLink != null)
                {
                    DiscordDmChannel dmChannel = await userLink.Member.CreateDmChannelAsync();

                    targetMessages = await dmChannel.GetMessagesAsync();
                }

                if (targetMessages == null)
                {
                    // There was an error or no messages exist - Clean up and return
                    _targetDisplays.Clear();
                    return;
                }

                // Go through the messages and find any our tagged messages
                foreach (DiscordMessage message in targetMessages)
                {
                    if (!message.Content.StartsWith(BaseTag))
                    {
                        continue;
                    }
                    data.MessageIDs.Add(message.Id);
                }
            }
            _dirty = false;
        }
Пример #7
0
        protected sealed override async Task UpdateInternal(DiscordLink plugin, DLEventType trigger, object data)
        {
            // Avoid hitting the rate limitation by not allowig events that can be fired often to pass straight through.
            if ((trigger & HighFrequencyTriggerFlags) == trigger)
            {
                if (_HighFrequencyEventTimer == null)
                {
                    _HighFrequencyEventTimer = new Timer(this.TriggerTimedUpdate, null, HighFrequencyEventDelayMS, Timeout.Infinite);
                }
                return;
            }

            if (_dirty || _targetDisplays.Count <= 0)
            {
                await FindMessages(plugin);

                if (_dirty || _targetDisplays.Count <= 0)
                {
                    return;                                       // If something went wrong, we should just retry later
                }
            }

            bool                  createdOrDestroyedMessage = false;
            List <string>         matchedTags       = new List <string>();
            List <DiscordMessage> unmatchedMessages = new List <DiscordMessage>();

            foreach (TargetDisplayData channelDisplayData in _targetDisplays)
            {
                DiscordTarget target      = channelDisplayData.Target;
                ChannelLink   channelLink = target as ChannelLink;
                UserLink      userLink    = target as UserLink;
                if (channelLink == null && userLink == null)
                {
                    continue;
                }

                DiscordChannel targetChannel = null;
                if (channelLink != null)
                {
                    // Get the channel and verify permissions
                    DiscordGuild discordGuild = plugin.GuildByNameOrId(channelLink.DiscordGuild);
                    if (discordGuild == null)
                    {
                        continue;
                    }
                    targetChannel = discordGuild.ChannelByNameOrId(channelLink.DiscordChannel);
                    if (targetChannel == null)
                    {
                        continue;
                    }
                    if (!DiscordUtil.ChannelHasPermission(targetChannel, Permissions.ReadMessageHistory))
                    {
                        continue;
                    }
                }
                else if (userLink != null)
                {
                    targetChannel = await userLink.Member.CreateDmChannelAsync();
                }

                GetDisplayContent(target, out List <Tuple <string, DiscordLinkEmbed> > tagsAndContent);

                foreach (ulong messageID in channelDisplayData.MessageIDs)
                {
                    DiscordMessage message = await DiscordUtil.GetMessageAsync(targetChannel, messageID);

                    if (message == null)
                    {
                        _dirty = true;
                        return; // We cannot know which messages are wrong and duplicates may be created if we continue.
                    }
                    if (!message.Content.StartsWith(BaseTag))
                    {
                        continue;                                       // The message belongs to a different display
                    }
                    bool found = false;
                    foreach (var tagAndContent in tagsAndContent)
                    {
                        if (message.Content.Contains(tagAndContent.Item1))
                        {
                            _ = DiscordUtil.ModifyAsync(message, tagAndContent.Item1, tagAndContent.Item2);
                            matchedTags.Add(tagAndContent.Item1);
                            found = true;
                            ++_opsCount;
                            break;
                        }
                    }

                    if (!found)
                    {
                        unmatchedMessages.Add(message);
                    }
                }

                // Delete the messages that are no longer relevant
                foreach (DiscordMessage message in unmatchedMessages)
                {
                    DiscordUtil.DeleteAsync(message).Wait();
                    createdOrDestroyedMessage = true;
                    ++_opsCount;
                }
                unmatchedMessages.Clear();

                // Send the messages that didn't already exist
                foreach (var tagAndContent in tagsAndContent)
                {
                    if (!matchedTags.Contains(tagAndContent.Item1))
                    {
                        DiscordUtil.SendAsync(targetChannel, tagAndContent.Item1, tagAndContent.Item2).Wait();
                        createdOrDestroyedMessage = true;
                        ++_opsCount;
                    }
                }
                matchedTags.Clear();
            }

            if (createdOrDestroyedMessage)
            {
                await FindMessages(plugin);
            }

            LastUpdateTime = DateTime.Now;
        }
Пример #8
0
        protected override void GetDisplayContent(ChannelLink link, out List <Tuple <string, DiscordEmbed> > tagAndContent)
        {
            tagAndContent = new List <Tuple <string, DiscordEmbed> >();
            DiscordEmbedBuilder builder     = new DiscordEmbedBuilder();
            List <WorkParty>    workParties = Registrars.Get <WorkParty>().All <WorkParty>().NonNull().Where(x => x.State == ProposableState.Active).ToList();

            foreach (WorkParty workParty in workParties)
            {
                string tag = BaseTag + " [" + workParty.Id + "]";
                builder.WithColor(MessageBuilder.EmbedColor);
                builder.WithTitle(workParty.Name);

                // Workers
                string workersDesc = string.Empty;
                foreach (Laborer laborer in workParty.Laborers)
                {
                    if (laborer.Citizen == null)
                    {
                        continue;
                    }
                    bool isCreator = laborer.Citizen == workParty.Creator;
                    workersDesc += laborer.Citizen.Name + (isCreator ? " (Creator)" : string.Empty) + "\n";
                }

                if (string.IsNullOrWhiteSpace(workersDesc))
                {
                    workersDesc += "--- No Workers Registered ---";
                }
                builder.AddField("Workers", workersDesc);

                // Work
                foreach (Work work in workParty.Work)
                {
                    string        workDesc    = string.Empty;
                    string        workType    = string.Empty;
                    List <string> workEntries = new List <string>();
                    switch (work)
                    {
                    case LaborWork laborWork:
                    {
                        if (!string.IsNullOrEmpty(laborWork.ShortDescriptionRemainingWork))
                        {
                            workType = "Labor for " + laborWork.Order.Recipe.RecipeName;
                            workEntries.Add(MessageUtil.StripTags(laborWork.ShortDescriptionRemainingWork));
                        }
                        break;
                    }

                    case WorkOrderWork orderWork:
                    {
                        workType = "Materials for " + orderWork.Order.Recipe.RecipeName;
                        foreach (TagStack stack in orderWork.Order.MissingIngredients)
                        {
                            string itemName = string.Empty;
                            if (stack.Item != null)
                            {
                                itemName = stack.Item.DisplayName;
                            }
                            else if (stack.StackObject != null)
                            {
                                itemName = stack.StackObject.DisplayName;
                            }
                            workEntries.Add(itemName + " (" + stack.Quantity + ")");
                        }
                        break;
                    }

                    default:
                        break;
                    }

                    if (workEntries.Count > 0)
                    {
                        foreach (string material in workEntries)
                        {
                            workDesc += "- " + material + "\n";
                        }

                        if (!string.IsNullOrWhiteSpace(workDesc))
                        {
                            string percentDone = (work.PercentDone * 100.0f).ToString("N1", CultureInfo.InvariantCulture).Replace(".0", "");
                            builder.AddField("\n" + workType + " (Weight " + work.Weight + ") (" + percentDone + "% completed) \n", workDesc);
                        }
                    }
                }

                // Payment
                string paymentDesc = string.Empty;
                foreach (Payment payment in workParty.Payment)
                {
                    string desc = string.Empty;
                    switch (payment)
                    {
                    case CurrencyPayment currencyPayment:
                    {
                        float currencyAmountLeft = currencyPayment.Amount - currencyPayment.AmountPaid;
                        if (currencyAmountLeft > 0.0f)
                        {
                            desc = "Receive " + currencyAmountLeft + " " + currencyPayment.Currency.Name
                                   + (currencyPayment.PayType == PayType.SplitByWorkPercent ? ", split based on work performed" : ", split evenly")
                                   + (currencyPayment.PayAsYouGo ? ", paid as work is performed" : ", paid when the project finishes");
                        }
                        break;
                    }

                    case GrantTitlePayment titlePayment:
                    {
                        desc = "Receive title `" + titlePayment.Title.Name + "` if work contributed is at least " + titlePayment.MinContributedPercent + "%";
                        break;
                    }

                    case KnowledgeSharePayment knowledgePayment:
                    {
                        if (knowledgePayment.Skills.Entries.Count > 0)
                        {
                            desc = "Receive knowledge of `" + MessageUtil.StripTags(knowledgePayment.ShortDescription()) + "` if work contributed is at least " + knowledgePayment.MinContributedPercent + "%";
                        }
                        break;
                    }

                    case ReputationPayment reputationPayment:
                    {
                        float reputationAmountLeft = reputationPayment.Amount - reputationPayment.AmountPaid;
                        desc = "Receive " + reputationAmountLeft + " reputation from " + reputationPayment.WorkParty.Creator.Name
                               + (reputationPayment.PayType == PayType.SplitByWorkPercent ? ", split based on work performed" : ", split evenly")
                               + (reputationPayment.PayAsYouGo ? ", paid as work is performed" : ", paid when the project finishes");
                        break;
                    }

                    default:
                        break;
                    }

                    if (!string.IsNullOrEmpty(desc))
                    {
                        paymentDesc += "- " + desc + "\n";
                    }
                }

                if (!string.IsNullOrWhiteSpace(paymentDesc))
                {
                    builder.AddField("Payment", paymentDesc);
                }

                if (builder.Fields.Count > 0)
                {
                    tagAndContent.Add(new Tuple <string, DiscordEmbed>(tag, builder.Build()));
                }
                builder.ClearFields();
            }
        }
Пример #9
0
 public ChannelDisplayData(ChannelLink link)
 {
     Link       = link;
     MessageIDs = new List <ulong>();
 }
Пример #10
0
 protected abstract void GetDisplayContent(ChannelLink link, out List <Tuple <string, DiscordEmbed> > tagAndContent);