Пример #1
0
        /*METHODS*/
        public async Task AnswerTurn(CancellationToken ct)
        {
            try
            {
                await User.SendMessageAsync("Please answer the following questions as accurately as you can.");

                finishedTurn            = false;
                Client.MessageReceived += CheckForResponse;
                foreach (PlayerFibbagePrompt prompt in prompts)
                {
                    responded = false;
                    response  = "";
                    await User.SendMessageAsync(prompt.AnswererQuestion);

                    while (!responded)
                    {
                        await Task.Delay(500);

                        ct.ThrowIfCancellationRequested();
                    }
                    prompt.Truth = response;
                }
                await User.SendMessageAsync("That's all! Please return to the game channel.");

                finishedTurn = true;
            }
            catch (OperationCanceledException)
            {
                await User.SendMessageAsync("Time is up! Please return to the game channel.");
            }
            catch (Exception err)
            {
                await ResponseChannel.SendMessageAsync($"IN TURN {User.Id}\n{err.ToString()}");
            }
        }
Пример #2
0
 private static void DequeueLoop()
 {
     foreach (CorrelationItem <string> item in ResponseChannel.GetConsumingEnumerable())
     {
         Console.WriteLine($"{item.Value} [{item.Correlation:N}]");
     }
 }
Пример #3
0
        public static LocalUser GetUser(ResponseChannel rc, VBotService.RemoteUser remoteUser)
        {
            LocalUser luser = VBotDB.Instance.LocalUsers.FirstOrDefault(
                u => u.Screenname == rc.ToName && u.Service == rc.Connection.Alias);

            if (luser == null)
            {

                luser = new LocalUser
                {
                    Screenname = rc.ToName,
                    Service = rc.Connection.Alias,
                    BoardUserID = remoteUser.UserID,
                    LastUpdate = DateTime.Now
                };

                VBotDB.Instance.LocalUsers.InsertOnSubmit(luser);
                VBotDB.Instance.SubmitChanges();

            }
            else
            {
                luser.LastUpdate = DateTime.Now;
                VBotDB.Instance.SubmitChanges();
            }

            if (luser != null)
            {
                luser.ResponseChannel = rc;
            }

            return luser;
        }
Пример #4
0
        /*METHODS*/
        public async Task takeTurn(List <Prompt> prompts, CancellationToken ct, int playerID)
        {
            try
            {
                await User.SendMessageAsync("Please answer the following 2 prompts as best as you can.");

                finishedTurn = false;

                //connect message being recieved to response checking
                Client.MessageReceived += CheckForResponse;
                foreach (Prompt prompt in prompts)
                {
                    responded = false;
                    response  = "";
                    if (prompt.PlayerA == playerID)
                    {
                        //send the prompt
                        await User.SendMessageAsync(prompt.Question);

                        //wait for response (see method CheckForResponse)
                        while (!responded)
                        {
                            await Task.Delay(1);

                            ct.ThrowIfCancellationRequested();
                        }
                        prompt.AnswerA = response;
                    }
                    else if (prompt.PlayerB == playerID)
                    {
                        //send the prompt
                        await User.SendMessageAsync(prompt.Question);

                        //wait for response (see method CheckForResponse)
                        while (!responded)
                        {
                            await Task.Delay(1);

                            ct.ThrowIfCancellationRequested();
                        }
                        prompt.AnswerB = response;
                    }
                }
                await User.SendMessageAsync("That's all! Please return to the game channel.");

                finishedTurn = true;
                await Task.CompletedTask;
            }
            catch (OperationCanceledException)
            {
                await User.SendMessageAsync("Time is up! Please return to the game channel.");

                await Task.CompletedTask;
            }
            catch (Exception err)
            {
                await ResponseChannel.SendMessageAsync(err.ToString());
            }
        }
Пример #5
0
        public static UserCredentials Credentialize(ResponseChannel channel)
        {
            UserCredentials creds = new UserCredentials();

            creds.Username = channel.ToName;
            creds.ServiceName = channel.Connection.Alias;

            return creds;
        }
Пример #6
0
        internal Response(IChannelOwner parent, string guid, ResponseInitializer initializer) : base(parent, guid)
        {
            _channel     = new(guid, parent.Connection, this);
            _initializer = initializer;
            _initializer.Request.Timing = _initializer.Timing;
            _finishedTask = new();

            _headers = new RawHeaders(_initializer.Headers.ConvertAll(x => new NameValueEntry(x.Name, x.Value)).ToArray());
        }
Пример #7
0
 private void WatchLoop()
 {
     foreach (var r in RequestChannel.GetConsumingEnumerable())
     {
         var request = r;                    // capture variable
         Thread.Sleep(request.Value * 1000); // BAD PRACTICE (should be await Task.Delay)
         var item = new CorrelationItem <string>(request.Correlation, $"Data of {request.Value}");
         ResponseChannel.TryAdd(item);
     }
 }
Пример #8
0
 private void WatchLoop()
 {
     foreach (var response in ResponseChannel.GetConsumingEnumerable())
     {
         if (_map.TryRemove(response.Correlation,
                            out TaskCompletionSource <string> tcs))
         {
             tcs.TrySetResult(response.Value);
         }
     }
 }
Пример #9
0
        internal Response(IChannelOwner parent, string guid, ResponseInitializer initializer) : base(parent, guid)
        {
            _channel     = new ResponseChannel(guid, parent.Connection, this);
            _initializer = initializer;

            if (initializer.Headers != null)
            {
                foreach (var kv in initializer.Headers)
                {
                    _headers[kv.Name] = kv.Value;
                }
            }
        }
Пример #10
0
 private void WatchLoopAsync()
 {
     foreach (var r in RequestChannel.GetConsumingEnumerable())
     {
         var request = r; // capture variable
         var t       = Task.Run(async() =>
         {
             await Task.Delay(request.Value * 1000).ConfigureAwait(false);
             var item = new CorrelationItem <string>(request.Correlation, $"Data of {request.Value}");
             ResponseChannel.TryAdd(item);
         });
         t.Start();
     }
 }
Пример #11
0
 private void WatchLoop()
 {
     foreach (var r in RequestChannel.GetConsumingEnumerable())
     {
         var request = r; // capture variable
         var t       = new Thread(() =>
         {
             Thread.Sleep(request.Value * 1000); // BAD PRACTICE
             var item = new CorrelationItem <string>(request.Correlation, $"Data of {request.Value}");
             ResponseChannel.TryAdd(item);
         });
         t.Start();
     }
 }
Пример #12
0
        /// <summary>
        /// Fills the player's Lies with answers for the current round
        /// </summary>
        /// <param name="prompts">The round's prompts</param>
        /// <param name="roundUsername">The round's subject's username. For giving the player the correct username</param>
        /// <param name="ct">To cancel the process when time runs up</param>
        /// <returns></returns>
        public async Task LieTurn(PlayerFibbagePrompt[] prompts, string roundUsername, CancellationToken ct)
        {
            try
            {
                responses = new string[prompts.Length];
                await User.SendMessageAsync("Please answer the following prompts with answers that may fool your other players into believing they are true");

                finishedTurn            = false;
                Client.MessageReceived += CheckForResponse;
                for (int i = 0; i < prompts.Length; i++)
                {
                    responded = false;
                    response  = "";
                    await User.SendMessageAsync(prompts[i].GetLiarQuestion(roundUsername));

                    while (!responded)
                    {
                        await Task.Delay(500);

                        ct.ThrowIfCancellationRequested();
                    }
                    if (response == prompts[i].Truth)
                    {
                        await User.SendMessageAsync("You entered the truth! Please answer again, with something different this time.");

                        i--;
                        continue;
                    }
                    responses[i] = response;

                    await User.SendMessageAsync("That's all! Please return to the game channel.");

                    finishedTurn = true;
                }
            }
            catch (OperationCanceledException)
            {
                await User.SendMessageAsync("Time is up! Please return to the game channel.");
            }
            catch (Exception err)
            {
                await ResponseChannel.SendMessageAsync($"IN TURN {User.Id}\n{err.ToString()}");
            }
        }
Пример #13
0
        public static LocalUser GetUser(ResponseChannel rc)
        {
            LocalUser luser = VBotDB.Instance.LocalUsers.FirstOrDefault(
                u => u.Screenname == rc.ToName && u.Service == rc.Connection.Alias);

            if (luser == null)
            {
                VBotService.RequestResult result = BotService.Instance.WhoAmI(BotService.Credentialize(rc));

                if (result.Code == 0)
                {
                    luser = new LocalUser
                    {
                        Screenname = rc.ToName,
                        Service = rc.Connection.Alias,
                        BoardUserID = result.RemoteUser.UserID,
                        LastUpdate = DateTime.Now
                    };

                    VBotDB.Instance.LocalUsers.InsertOnSubmit(luser);
                    VBotDB.Instance.SubmitChanges();
                }
            }
            else
            {
                luser.LastUpdate = DateTime.Now;
                VBotDB.Instance.SubmitChanges();
            }

            if (luser != null)
            {
                luser.ResponseChannel = rc;
            }

            return luser;
        }
Пример #14
0
        public void postNotificationElapsed(object sender, ElapsedEventArgs e)
        {
            log.Info("Notification Timer Elapsed()");
            if (_conComp.Connections != null && _conComp.Connections.Count() > 0)
            {
                VBotService.PostNotificationsResult result = BotService.Instance.GetPostNotifications(false);

                if (result.Result.Code == 0)
                {
                    if (result.PostNotificationList != null && result.PostNotificationList.Count() > 0)
                    {
                        log.Info(string.Format("{0} post notifications recieved", result.PostNotificationList.Count()));

                        foreach (VBotService.PostNotification not in result.PostNotificationList)
                        {
                            Connection c = _conComp.GetConnection(not.IMNotificationInfo.InstantIMService);

                            if (c != null)
                            {
                                string strScreenName = not.IMNotificationInfo.InstantIMScreenname;
                                string strResponse = c.NewLine + "Forum: '" + not.Forum.Title + "'" + c.NewLine + "Thread: '" + not.Thread.ThreadTitle + "'" + c.NewLine;

                                ResponseChannel rc = new ResponseChannel(strScreenName, c);
                                strResponse = rc.FetchTemplate("postnotificationbit",
                                    new object[] {
                                        not.Forum.Title,
                                        not.Thread.ThreadTitle,
                                        not.Post.PageText,
                                        not.Post.PostIndex,
                                        not.Post.DateLineText,
                                        not.Post.Username,
                                        not.Thread.ThreadID });

                                rc.SendMessage(strResponse);
                                System.Threading.Thread.Sleep(2000);
                            }
                            else
                            {
                                log.WarnFormat("Could not get Connection object frop composite: {0}", not.IMNotificationInfo.InstantIMService);
                            }
                        }
                    }
                    else
                    {// TODO: error checking

                    }
                }
            }
            else
            {
                log.Info("No open connections.");
            }
        }
Пример #15
0
        public void OnMessageCallback(Connection conn, InstantMessage im)
        {
            lock (this)
            {
                log.InfoFormat("INMSG ({0}) << {1}: {2}", conn.GetType().Name, im.User, im.Text);

                DateTime dtStart = DateTime.Now;

                try
                {
                    ResponseChannel = new ResponseChannel(im.User, conn);

                    VBotService.RequestResult result = BotService.Instance.WhoAmI(BotService.Credentialize(ResponseChannel));
                    if (result.Code == 0)
                    {
                        LocalUser user = LocalUser.GetUser(ResponseChannel, result.RemoteUser);

                        #region if

                        if (_inputs.ContainsKey(user.LocalUserID) && _inputs[user.LocalUserID].State == InputStateEnum.Waiting)
                        { // waiting for input?

                            InputState ist = new InputState(InputStateEnum.Responded);
                            ist.PageText = im.Text;
                            _inputs[user.LocalUserID] = ist;
                        }
                        else
                        { // the user is at the 'main menu'

                            Result lastRes = new Result();
                            string[] strCommands = Regex.Split(im.Text, @"\;");

                            foreach (string strCommand in strCommands)
                            {
                                lastRes = DoCommand(strCommand, user);

                                if (lastRes.Code != ResultCode.Success)
                                {
                                    break;
                                }
                            }

                            if (lastRes != null && (lastRes.Code == ResultCode.Success || lastRes.Code == ResultCode.Error))
                            {
                                conn.SendMessage(new InstantMessage(im.User, lastRes.Message));
                            }
                        }
                        #endregion
                    }
                    else
                    {
                        log.ErrorFormat("GetUser failed: {0}", result.Text);
                        ResponseChannel.SendMessage(ResponseChannel.FetchTemplate(result.Text));
                    }
                }
                catch (Exception ex)
                {
                    log.Error("Something bad",ex);
                }

                if (log.IsDebugEnabled)
                {
                    TimeSpan elapsed = DateTime.Now - dtStart;

                    log.InfoFormat("Response Time: {0}.{1} seconds",elapsed.Seconds, elapsed.Milliseconds);
                }
            }
        }
Пример #16
0
 internal Response(ConnectionScope scope, string guid, ResponseInitializer initializer)
 {
     _scope   = scope;
     _channel = new ResponseChannel(guid, scope, this);
 }
Пример #17
0
        public async Task lastTurn(List <Prompt> prompts, CancellationToken ct, int playerID)
        {
            try
            {
                await User.SendMessageAsync("Please answer the following prompts as best as you can. Your answer will be used for both prompts.");

                //set responded off and clear response
                responded = false;
                response  = "";

                var text = "";

                //connect message being recieved to response checking
                Client.MessageReceived += CheckForResponse;
                foreach (Prompt prompt in prompts)
                {
                    if (prompt.PlayerA == playerID)
                    {
                        if (!responded)
                        {
                            text += prompt.Question + "\n";
                            //send the prompt
                            //await User.SendMessageAsync(prompt.Question);
                        }

                        /*
                         * //wait for response (see method CheckForResponse)
                         * while (!responded)
                         * {
                         *  await Task.Delay(1);
                         *  ct.ThrowIfCancellationRequested();
                         * }
                         * prompt.AnswerA = response;
                         * responded = true;
                         */
                    }
                    else if (prompt.PlayerB == playerID)
                    {
                        if (!responded)
                        {
                            text += prompt.Question + "\n";
                            //send the prompt
                            //await User.SendMessageAsync(prompt.Question);
                        }

                        /*
                         * //wait for response (see method CheckForResponse)
                         * while (!responded)
                         * {
                         *  await Task.Delay(1);
                         *  ct.ThrowIfCancellationRequested();
                         * }
                         * prompt.AnswerB = response;
                         * responded = true;
                         */
                    }
                }

                //send the prompts
                await User.SendMessageAsync(text);

                while (!responded)
                {
                    await Task.Delay(50);

                    ct.ThrowIfCancellationRequested();
                }

                foreach (Prompt prompt in prompts)
                {
                    if (prompt.PlayerA == playerID)
                    {
                        prompt.AnswerA = response;
                    }
                    if (prompt.PlayerB == playerID)
                    {
                        prompt.AnswerB = response;
                    }
                }

                await User.SendMessageAsync("That's all! Please return to the game channel.");

                finishedTurn = true;
                await Task.CompletedTask;
            }
            catch (OperationCanceledException)
            {
                await User.SendMessageAsync("Time is up! Please return to the game channel.");

                await Task.CompletedTask;
            }
            catch (Exception err)
            {
                await ResponseChannel.SendMessageAsync(err.ToString());
            }
        }
Пример #18
0
        /// <summary>
        /// Gets what the person answers once all lies have been submitted
        /// </summary>
        /// <param name="prompt">The prompt (to present and format in DMs)</param>
        /// <param name="subjectID">The ID of the round's player, so they can't score for their own round</param>
        /// <param name="promptIndex">The prompt's index, so it can be properly formatted</param>
        /// <param name="playerIndex">The player's index according to the player list</param>
        /// <param name="ct">For cancelling when time runs out</param>
        /// <returns></returns>
        public async Task GetAnswer(EmbedBuilder prompt, ulong subjectID, int promptIndex, int playerIndex, CancellationToken ct)
        {
            try
            {
                finishedTurn = false;
                if (subjectID == User.Id)
                {
                    if (promptIndex == 0)
                    {
                        await User.SendMessageAsync("This is your round! Kick back, and wait for the others to answer.");
                    }
                    finishedTurn = true;
                }
                else
                {
                    var    sr      = new StringReader(prompt.Description);
                    string newDesc = "";
                    string line    = "";
                    int    counter = 0;

                    //remove the player's answer from the list
                    while (true)
                    {
                        counter++;
                        line = sr.ReadLine();

                        //okay we're done
                        if (line == null || line == "Answer via the DMs!")
                        {
                            break;
                        }
                        if (line == Lies[promptIndex])
                        {
                            continue;
                        }
                        newDesc += $"{counter}) {line}\n";
                    }

                    newDesc           += "Answer by typing the number for the answer you want to pick!";
                    prompt.Description = newDesc;

                    Client.MessageReceived += CheckForResponse;

                    await User.SendMessageAsync("", false, prompt);

                    while (true)
                    {
                        responded = false;
                        response  = "";
                        answer    = 0;
                        while (!responded)
                        {
                            await Task.Delay(500);

                            ct.ThrowIfCancellationRequested();
                        }
                        if (!Int32.TryParse(response, out answer) || answer < 1 || answer > 9)
                        {
                            await User.SendMessageAsync("Send a numeral between 1-9");
                        }
                        else if (answer == playerIndex + 1)
                        {
                            await User.SendMessageAsync("That number is reserved for your answer! Please try another number.");
                        }
                        else
                        {
                            break;
                        }
                    }

                    await User.SendMessageAsync("That's all! Please return to the game channel.");
                }
            }
            catch (OperationCanceledException)
            {
                await User.SendMessageAsync("Time is up! Please return to the game channel.");
            }
            catch (Exception err)
            {
                await ResponseChannel.SendMessageAsync($"IN TURN {User.Id}\n{err.ToString()}");
            }
        }
Пример #19
0
        public void Test(CommandParser parser)
        {
            Connection c = new GTalkConnection("testuser", "testpass");
            ResponseChannel rc = new ResponseChannel("aimname", c);

            Dictionary<string, object> d = new Dictionary<string, object>()
                {
                    {"PageText","this is the pagettext"},
                    {"Index",8},
                    {"DateLineText","Today at 5pm"},
                    {"Username","Manchy"},
                };

            string str = rc.FetchTemplate(@"postbit", new object[] { "text",3,"Yesterday @ 3pm","Frank Power"} );
            log.Debug(str);

            //VBotService.PostNotificationsResult result = BotService.Instance.GetPostNotifications(true);

            //UserCredentials uc = new UserCredentials();
            //uc.ServiceName = @"gtalk";
            //uc.Username = @"*****@*****.**";

            //VBotService.PostReplyResult res = BotService.Instance.PostNewThread(uc, 2, @"title", "page text");//

            //UserCredentials uc1 = new UserCredentials();
            //uc1.ServiceName = @"aim";
            //uc1.Username = @"zethon";

            //VBotService.RequestResult res = BotService.Instance.WhoAmI(uc);
        }