Esempio n. 1
0
        private bool AddToTradeQueue(PK8 pk8, int code, LiveChatMessage e, bool sudo, PokeRoutineType type, out string msg)
        {
            // var user = e.WhisperMessage.UserId;
            var userID = ulong.Parse(e.AuthorDetails.ChannelId);
            var name   = e.AuthorDetails.DisplayName;

            var trainer  = new PokeTradeTrainerInfo(name);
            var notifier = new YouTubeTradeNotifier <PK8>(pk8, trainer, code, e.AuthorDetails.DisplayName, client, Hub.Config.YouTube);
            var tt       = type == PokeRoutineType.SeedCheck ? PokeTradeType.Seed : PokeTradeType.Specific;
            var detail   = new PokeTradeDetail <PK8>(pk8, trainer, notifier, tt, code: code);
            var trade    = new TradeEntry <PK8>(detail, userID, type, name);

            var added = Info.AddToTradeQueue(trade, userID, sudo);

            if (added == QueueResultAdd.AlreadyInQueue)
            {
                msg = $"@{name}: Sorry, you are already in the queue.";
                return(false);
            }

            var position = Info.CheckPosition(userID, type);

            msg = $"@{name}: Added to the {type} queue, unique ID: {detail.ID}. Current Position: {position.Position}";

            var botct = Info.Hub.Bots.Count;

            if (position.Position > botct)
            {
                var eta = Info.Hub.Config.Queues.EstimateDelay(position.Position, botct);
                msg += $". Estimated: {eta:F1} minutes.";
            }
            return(true);
        }
        /// <summary>
        /// Adds a message to a live chat.
        /// Documentation https://developers.google.com/youtube/v3/reference/liveChatMessages/insert
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Youtube service.</param>
        /// <param name="part">The part parameter serves two purposes. It identifies the properties that the write operation will set as well as the properties that the API response will include. Set the parameter value to snippet.</param>
        /// <param name="body">A valid Youtube v3 body.</param>
        /// <returns>LiveChatMessageResponse</returns>
        public static LiveChatMessage Insert(YoutubeService service, string part, LiveChatMessage body)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }
                if (part == null)
                {
                    throw new ArgumentNullException(part);
                }

                // Make the request.
                return(service.LiveChatMessages.Insert(body, part).Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request LiveChatMessages.Insert failed.", ex);
            }
        }
Esempio n. 3
0
        private async Task MessageBackgroundPolling()
        {
            LiveChatMessage lastMessage = null;

            while (!this.messageBackgroundPollingTokenSource.IsCancellationRequested)
            {
                try
                {
                    LiveChatMessagesResultModel result = await this.connection.LiveChat.GetRecentMessages(this.broadcast, maxResults : 1000);

                    if (result != null)
                    {
                        if (lastMessage != null)
                        {
                            List <LiveChatMessage> newMessages = new List <LiveChatMessage>();
                            foreach (LiveChatMessage message in result.Messages)
                            {
                                if (message.Id.Equals(lastMessage.Id))
                                {
                                    break;
                                }
                                newMessages.Add(message);
                            }
                            this.OnMessagesReceived?.Invoke(this, newMessages);
                        }
                        lastMessage = result.Messages.FirstOrDefault();

                        await Task.Delay((int)result.PollingInterval);
                    }
                }
                catch (TaskCanceledException) { }
                catch (Exception ex) { Logger.Log(ex); }
            }
        }
Esempio n. 4
0
 /// <summary>
 /// Deletes the specified message from the live chat.
 /// </summary>
 /// <param name="message">The message to delete</param>
 /// <returns>An awaitable Task</returns>
 public async Task DeleteMessage(LiveChatMessage message)
 {
     Validator.ValidateVariable(message, "message");
     await this.YouTubeServiceWrapper <object>(async() =>
     {
         LiveChatMessagesResource.DeleteRequest request = this.connection.GoogleYouTubeService.LiveChatMessages.Delete(message.Id);
         await request.ExecuteAsync();
         return(null);
     });
 }
Esempio n. 5
0
 public ChatMessage MapToChatMessage(LiveChatMessage item)
 {
     return(new ChatMessage
     {
         Author = item.AuthorDetails.displayName,
         Message = item.snippet.displayMessage,
         Date = item.snippet.publishedAt,
         Source = "Youtube",
         SourceMessageId = item.id,
         SourceAuthorId = item.AuthorDetails.channelId
     });
 }
Esempio n. 6
0
        private string HandleCommand(LiveChatMessage m, string c, string args)
        {
            bool sudo() => m is LiveChatMessage ch && (ch.AuthorDetails.IsChatOwner.Equals(true) || Settings.IsSudo(m.AuthorDetails.DisplayName));

            switch (c)
            {
            // User Usable Commands
            case "trade":
                var _ = YouTubeCommandsHelper.AddToWaitingList(args, m.AuthorDetails.DisplayName, m.AuthorDetails.DisplayName, out string msg);
                return(msg);

            case "ts":
                return($"@{m.AuthorDetails.DisplayName}: {Info.GetPositionString(ulong.Parse(m.AuthorDetails.ChannelId))}");

            case "tc":
                return($"@{m.AuthorDetails.DisplayName}: {YouTubeCommandsHelper.ClearTrade(ulong.Parse(m.AuthorDetails.ChannelId))}");

            case "code":
                return(YouTubeCommandsHelper.GetCode(ulong.Parse(m.AuthorDetails.ChannelId)));

            // Sudo Only Commands
            case "tca" when !sudo():
            case "pr" when !sudo():
            case "pc" when !sudo():
            case "tt" when !sudo():
            case "tcu" when !sudo():
                return("This command is locked for sudo users only!");

            case "tca":
                Info.ClearAllQueues();
                return("Cleared all queues!");

            case "pr":
                return(Info.Hub.Ledy.Pool.Reload() ? $"Reloaded from folder. Pool count: {Info.Hub.Ledy.Pool.Count}" : "Failed to reload from folder.");

            case "pc":
                return($"The pool count is: {Info.Hub.Ledy.Pool.Count}");

            case "tt":
                return(Info.Hub.Queues.Info.ToggleQueue()
                        ? "Users are now able to join the trade queue."
                        : "Changed queue settings: **Users CANNOT join the queue until it is turned back on.**");

            case "tcu":
                return(YouTubeCommandsHelper.ClearTrade(args));

            default: return(null);
            }
        }
Esempio n. 7
0
        public async Task <bool> sendChatMessage(string message, string chatID)
        {
            LiveChatMessage liveMessage = new LiveChatMessage();

            liveMessage.Snippet = new LiveChatMessageSnippet()
            {
                LiveChatId         = chatID,
                Type               = "textMessageEvent",
                TextMessageDetails = new LiveChatTextMessageDetails()
                {
                    MessageText = message
                }
            };
            var response = await youTubeService.LiveChatMessages.Insert(liveMessage, "snippet").ExecuteAsync();

            return(response != null);
        }
Esempio n. 8
0
        /// <summary>
        /// Sends a message to the live chat.
        /// </summary>
        /// <param name="broadcast">The broadcast of the live chat</param>
        /// <param name="message">The message to send</param>
        /// <returns>The resulting message</returns>
        public async Task <LiveChatMessage> SendMessage(LiveBroadcast broadcast, string message)
        {
            Validator.ValidateVariable(broadcast, "broadcast");
            Validator.ValidateString(message, "message");
            return(await this.YouTubeServiceWrapper(async() =>
            {
                LiveChatMessage newMessage = new LiveChatMessage();
                newMessage.Snippet = new LiveChatMessageSnippet();
                newMessage.Snippet.LiveChatId = broadcast.Snippet.LiveChatId;
                newMessage.Snippet.Type = "textMessageEvent";
                newMessage.Snippet.TextMessageDetails = new LiveChatTextMessageDetails();
                newMessage.Snippet.TextMessageDetails.MessageText = message;

                LiveChatMessagesResource.InsertRequest request = this.connection.GoogleYouTubeService.LiveChatMessages.Insert(newMessage, "snippet");
                return await request.ExecuteAsync();
            }));
        }
Esempio n. 9
0
 public ChatMessage MapToChatMessage(LiveChatMessage item)
 {
     return(new ChatMessage
     {
         Message = item.snippet.displayMessage,
         Date = item.snippet.publishedAt,
         Source = ApiSource.Youtube,
         SourceMessageId = item.id,
         Author = new Author
         {
             Name = item.AuthorDetails.displayName,
             Source = ApiSource.Youtube,
             SourceAuthorId = item.AuthorDetails.channelId
         },
         Type = item.snippet.type
     });
 }
Esempio n. 10
0
        public async Task UpdateVideoMetadataAsync(VideoMetadataModel videoMetadataModel, string chatMessage, CancellationToken cancellationToken)
        {
            _logger.LogTrace($"{GetType()} - BEGIN {nameof(UpdateVideoMetadataAsync)}");

            try
            {
                YouTubeService ytService = await _ytServiceProvider.CreateServiceAsync(cancellationToken);

                string videoId = GetVideoIdFromUrl(videoMetadataModel.VideoUrl);
                if (!string.IsNullOrEmpty(videoId))
                {
                    IEnumerable <VideoCategory> categories = await GetCategoriesAsync(cancellationToken);

                    VideoCategory category = categories.FirstOrDefault(c => c.Snippet.Title == videoMetadataModel.Category);

                    Video video = await GetVideoMetadataInternalAsync(videoId, cancellationToken);

                    video.HydrateFromVideoModel(videoMetadataModel);
                    video.Snippet.CategoryId = category.Id;

                    VideosResource.UpdateRequest req = ytService.Videos.Update(video, new string[] { "snippet", "status" });
                    await req.ExecuteAsync(cancellationToken);

                    if (!string.IsNullOrEmpty(chatMessage))
                    {
                        LiveChatMessage msg = new LiveChatMessage {
                            Snippet = new LiveChatMessageSnippet {
                                LiveChatId         = video.LiveStreamingDetails.ActiveLiveChatId,
                                Type               = "textMessageEvent",
                                TextMessageDetails = new LiveChatTextMessageDetails {
                                    MessageText = chatMessage
                                }
                            }
                        };
                        ytService.LiveChatMessages.Insert(msg, SNIPPET_PART_PARAM);
                    }
                }
            }
            catch (Exception e)
            {
                _logger.LogError("An error occurred while updating video", e);
                throw;
            }
        }
        public async Task <LiveChatMessage> SendMessageAsync(string message)
        {
            if (!string.IsNullOrWhiteSpace(this.liveChatId))
            {
                var liveChatMessage = new LiveChatMessage
                {
                    Snippet = new LiveChatMessageSnippet
                    {
                        LiveChatId         = this.liveChatId,
                        Type               = "textMessageEvent",
                        TextMessageDetails = new LiveChatTextMessageDetails {
                            MessageText = message
                        }
                    }
                };

                var request = this.youtubeService.LiveChatMessages.Insert(liveChatMessage, "snippet");
                return(await request.ExecuteAsync().ConfigureAwait(false));
            }

            return(null);
        }
Esempio n. 12
0
 /// <summary>
 /// Deletes the specified message from the live chat.
 /// </summary>
 /// <param name="message">The message to delete</param>
 /// <returns>An awaitable Task</returns>
 public async Task DeleteMessage(LiveChatMessage message)
 {
     await this.connection.LiveChat.DeleteMessage(message);
 }