Ejemplo n.º 1
0
 public static async Task <BotData> SetConversationDataAsync(this IBotState operations, string channelId, string conversationId, BotData botData, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.SetConversationDataWithHttpMessagesAsync(channelId, conversationId, botData, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Ejemplo n.º 2
0
 /// <summary>
 /// GetPrivateConversationData
 /// </summary>
 /// get bot's data for a single user in a conversation
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='channelId'>
 /// channelId
 /// </param>
 /// <param name='conversationId'>
 /// The id for the conversation on the channel
 /// </param>
 /// <param name='userId'>
 /// id for the user on the channel
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <BotData> GetPrivateConversationDataAsync(this IBotState operations, string channelId, string conversationId, string userId, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.GetPrivateConversationDataWithHttpMessagesAsync(channelId, conversationId, userId, null, cancellationToken).ConfigureAwait(false))
     {
         return(await _result.HandleErrorAsync <BotData>().ConfigureAwait(false));
     }
 }
Ejemplo n.º 3
0
 public static async Task <IList <string> > DeleteStateForUserAsync(this IBotState operations, string channelId, string userId, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.DeleteStateForUserWithHttpMessagesAsync(channelId, userId, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Ejemplo n.º 4
0
 public static async Task <BotData> GetUserDataAsync(this IBotState operations, string channelId, string userId, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.GetUserDataWithHttpMessagesAsync(channelId, userId, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Ejemplo n.º 5
0
        public async Task UpdateAsync(Activity activity, MeetingData inData)
        {
            using (StateClient stateClient = activity.GetStateClient())
            {
                IBotState chatbotState = stateClient.BotState;
                BotData   chatbotData  = await chatbotState.GetUserDataAsync(
                    activity.ChannelId, activity.From.Id);

                MeetingData meetingData =
                    chatbotData.GetProperty <MeetingData>(MeetingDataProperty);

                if (meetingData == null)
                {
                    meetingData = new MeetingData();
                }

                meetingData.UserChannelID = activity.From.Id;
                meetingData.UserDBID      = inData.UserDBID;
                meetingData.Dialog        = inData.Dialog;
                meetingData.Method        = inData.Method;

                chatbotData.SetProperty(MeetingDataProperty, data: meetingData);
                await chatbotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, chatbotData);
            }
        }
Ejemplo n.º 6
0
        public async Task <string> GetScoresAsync(ConnectorClient connector, Activity activity)
        {
            Activity typingActivity = activity.BuildTypingActivity();
            await connector.Conversations.ReplyToActivityAsync(typingActivity);

            await Task.Delay(millisecondsDelay : 10000);

            using (StateClient stateClient = activity.GetStateClient())
            {
                IBotState chatbotState = stateClient.BotState;
                BotData   chatbotData  = await chatbotState.GetUserDataAsync(
                    activity.ChannelId, activity.From.Id);

                Queue <PlayScore> scoreQueue =
                    chatbotData.GetProperty <Queue <PlayScore> >(property: "scores");

                if (scoreQueue == null)
                {
                    return("Try typing Rock, Paper, or Scissors to play first.");
                }

                int plays       = scoreQueue.Count;
                int userWins    = scoreQueue.Where(q => q.UserWin).Count();
                int chatbotWins = scoreQueue.Where(q => !q.UserWin).Count();

                int ties = chatbotData.GetProperty <int>(property: "ties");

                return($"Out of the last {plays} contests, " +
                       $"you scored {userWins} and " +
                       $"Chatbot scored {chatbotWins}. " +
                       $"You've also had {ties} ties since playing.");
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Archives post links for a <see cref="ArchiveSubreddit"/>
        /// </summary>
        /// <param name="sub">An <see cref="ArchiveSubreddit"/> used for archiving the post with a specific <see cref="IArchiveService"/></param>
        /// <param name="config">A <see cref="Config"/> for flavortext</param>
        /// <param name="state">An <see cref="IBotState"/> used to keep track of comments and other things</param>
        /// <param name="post">A <see cref="Post"/> that you are replying to</param>
        /// <param name="archivedLinks">A <see cref="List{T}"/> of <see cref="ArchiveLink"/> used for keeping track of original and archived links</param>
        public static void ArchivePostLinks(ArchiveSubreddit sub, Config config, IBotState state, Post post, List <ArchiveLink> archivedLinks)
        {
            List <string> LinksToPost = new List <string>();

            if (sub.ArchivePost && sub.SubredditArchiveService.Verify(post.Url))
            {
                LinksToPost.Add($"* **Post:** {sub.SubredditArchiveService.Save(post.Url)}\n"); // saves post if you want to archive something
            }
            if (archivedLinks.Count != 0)
            {
                foreach (var link in archivedLinks)
                {
                    if (link.IsExcluded)
                    {
                        continue;
                    }
                    LinksToPost.Add($"* **Link: {link.Position}** ([{link.Hostname}]({link.OriginalLink})): {link.ArchivedLink}\n");
                }
            }
            if (LinksToPost.Count == 0)
            {
                return;
            }
            PostArchiveLinks(config, state, Program.Headers[0], post, LinksToPost);
        }
Ejemplo n.º 8
0
 /// <summary>
 /// Initializes client properties.
 /// </summary>
 private void Initialize()
 {
     this.BotState         = new BotState(this);
     this.BaseUri          = new Uri("https://state.botframework.com");
     SerializationSettings = new JsonSerializerSettings
     {
         Formatting            = Formatting.Indented,
         DateFormatHandling    = DateFormatHandling.IsoDateFormat,
         DateTimeZoneHandling  = DateTimeZoneHandling.Utc,
         NullValueHandling     = NullValueHandling.Ignore,
         ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
         ContractResolver      = new ReadOnlyJsonContractResolver(),
         Converters            = new List <JsonConverter>
         {
             new Iso8601TimeSpanConverter()
         }
     };
     DeserializationSettings = new JsonSerializerSettings
     {
         DateFormatHandling    = DateFormatHandling.IsoDateFormat,
         DateTimeZoneHandling  = DateTimeZoneHandling.Utc,
         NullValueHandling     = NullValueHandling.Ignore,
         ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
         ContractResolver      = new ReadOnlyJsonContractResolver(),
         Converters            = new List <JsonConverter>
         {
             new Iso8601TimeSpanConverter()
         }
     };
 }
Ejemplo n.º 9
0
        public async Task <string> GetScoresAsync(Activity activity)
        {
            using (StateClient stateClient = activity.GetStateClient())
            {
                //Get user state data base on Channel Id and From Id.
                IBotState chatbotState = stateClient.BotState;
                BotData   chatbotData  = await chatbotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                //Get state data(property), it was set/created in function: UpdateScoreAsync() as below
                Queue <PlaySore> scoreQueue = chatbotData.GetProperty <Queue <PlaySore> >(property: "scores");

                if (scoreQueue == null)
                {
                    return("Try typing Rock, Paper, or Scissors to Play first.");
                }

                int plays       = scoreQueue.Count;
                int userWins    = scoreQueue.Where(q => q.UserWin).Count();
                int chatbotWins = scoreQueue.Where(q => !q.UserWin).Count();
                int ties        = chatbotData.GetProperty <int>(property: "ties");

                return($"Out of the last {plays} contests, you scored {userWins} and chatbot scored {chatbotWins}. "
                       + $"You have also {ties} ties since playing.");
            }
        }
Ejemplo n.º 10
0
        public async Task UpdateScoresAsync(Activity activity, bool userWin)
        {
            using (StateClient stateClient = activity.GetStateClient())
            {
                IBotState chatbotState = stateClient.BotState;
                BotData   chatbotData  = await chatbotState.GetUserDataAsync(
                    activity.ChannelId, activity.From.Id);

                Queue <PlayScore> scoreQueue =
                    chatbotData.GetProperty <Queue <PlayScore> >(property: "scores");

                if (scoreQueue == null)
                {
                    scoreQueue = new Queue <PlayScore>();
                }

                if (scoreQueue.Count >= 10)
                {
                    scoreQueue.Dequeue();
                }

                scoreQueue.Enqueue(new PlayScore {
                    UserWin = userWin
                });

                chatbotData.SetProperty <Queue <PlayScore> >(property: "scores", data: scoreQueue);
                await chatbotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, chatbotData);
            }
        }
Ejemplo n.º 11
0
 /// <summary>
 /// ExportBotStateData
 /// </summary>
 /// <remarks>
 /// get all the state data for a bot in this channel. This returns a list of
 /// BotStateData and (possibly) a continuation token
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='channelId'>
 /// the channelId
 /// </param>
 /// <param name='continuationToken'>
 /// the skip token returned previously, or null
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <BotStateDataResult> ExportBotStateDataAsync(this IBotState operations, string channelId, string continuationToken = default(string), CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.ExportBotStateDataWithHttpMessagesAsync(channelId, continuationToken, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Ejemplo n.º 12
0
        public async Task DeleteAsync(Activity activity)
        {
            using (StateClient stateClient = activity.GetStateClient())
            {
                IBotState chatbotState = stateClient.BotState;

                await chatbotState.DeleteStateForUserAsync(activity.ChannelId, activity.From.Id);
            }
        }
Ejemplo n.º 13
0
        public async Task <string> DeleteScoreAsync(Activity activity)
        {
            using (StateClient stateClient = activity.GetStateClient())
            {
                IBotState chatbotState = stateClient.BotState;
                await chatbotState.DeleteStateForUserAsync(activity.ChannelId, activity.From.Id);

                return("All Scores Deleted.");
            }
        }
Ejemplo n.º 14
0
        public static async Task <BotData> GetUserDataAsync(this IBotState operations, string channelId, string userId, CancellationToken cancellationToken = default(CancellationToken))
        {
#if NET45
            Trace.TraceWarning(Messages.StateApiDeprecated);
#endif
            using (var _result = await operations.GetUserDataWithHttpMessagesAsync(channelId, userId, null, cancellationToken).ConfigureAwait(false))
            {
                return(await _result.HandleErrorAsync <BotData>().ConfigureAwait(false));
            }
        }
Ejemplo n.º 15
0
        public async Task <MeetingData> GetAsync(IActivity activity)
        {
            using (StateClient stateClient = activity.GetStateClient())
            {
                IBotState chatbotState = stateClient.BotState;
                BotData   chatbotData  =
                    await chatbotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                return(chatbotData.GetProperty <MeetingData>(MeetingDataProperty));
            }
        }
Ejemplo n.º 16
0
        public async Task AddTieAsync(Activity activity)
        {
            using (StateClient stateClient = activity.GetStateClient())
            {
                IBotState chatbotState = stateClient.BotState;
                BotData   chatbotData  = await chatbotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);

                int ties = chatbotData.GetProperty <int>(property: "ties");

                chatbotData.SetProperty <int>(property: "ties", data: ++ties);

                await chatbotState.SetUserDataAsync(activity.ChannelId, activity.From.Id, chatbotData);
            }
        }
Ejemplo n.º 17
0
        public static bool IsToMe(this EventMessageBase message, IBotState botState)
        {
            if (!IsActivePlainMessage(message))
            {
                return(false);
            }

            if (IsIm(message, botState))
            {
                return(true);
            }

            var messageBase = CastTo <MessageBase>(message);

            return((messageBase.Text ?? "").StartsWith($"<@{botState.Self.Id}>:"));
        }
Ejemplo n.º 18
0
        /// <summary>
        /// An asyncronous version of <seealso cref="ArchiveCommentLinks(Config, IBotState, Reddit, Comment, List{string}, List{string})"/> with <see cref="List{ArchiveLink}"/> support instead
        /// </summary>
        /// <param name="config">A <see cref="Config"/> used for flavortext</param>
        /// <param name="state">An <see cref="IBotState"/> used for keeping track of things</param>
        /// <param name="reddit">A <see cref="Reddit"/> used for getting things</param>
        /// <param name="comment">The <see cref="Comment"/> you are archiving</param>
        /// <param name="archiveLinks">A <see cref="List{ArchiveLink}"/> used for archived links</param>
        /// <returns>A <see cref="Task"/> for asyncronous using</returns>
        public static async Task ArchiveCommentLinksAsync(Config config, IBotState state, Reddit reddit, Comment comment, List <ArchiveLink> archiveLinks)
        {
            if (archiveLinks.Count < 1)
            {
                return;
            }
            List <string>         Links     = new List <string>();
            string                commentID = comment.Id;
            string                postID    = comment.LinkId.Substring(3);
            Task <List <string> > linksTask = Task.Run(() =>
            {
                List <string> links = new List <string>();
                foreach (ArchiveLink link in archiveLinks)
                {
                    if (link.IsExcluded)
                    {
                        continue;
                    }
                    links.Add($"* **By [{comment.AuthorName.DeMarkup()}]({comment.Shortlink.Replace("oauth", "www")})** ([{link.Hostname}]({link.OriginalLink})): {link.ArchivedLink}\n");
                }
                return(links);
            });

            if (state.DoesCommentExist(postID))
            {
                string botCommentThingID = state.GetCommentForPost(postID);
                if (!botCommentThingID.Contains("t1_"))
                {
                    botCommentThingID = "t1_" + botCommentThingID;
                }
                Console.WriteLine($"Already have post in {postID}, getting comment {botCommentThingID.Substring(3)}");
                Links = await linksTask;
                if (!EditArchiveComment((Comment)reddit.GetThingByFullname(botCommentThingID), Links))
                {
                    PostArchiveLinksToComment(config, state, Program.Headers[2], comment, Links);
                }
            }
            else
            {
                Links = await linksTask;
                Console.WriteLine($"No comment in {postID} to edit, making new one");
                PostArchiveLinks(config, state, Program.Headers[2], comment.GetCommentPost(reddit), Links);
            }
            state.AddCheckedComment(commentID);
        }
Ejemplo n.º 19
0
        public static bool IsIm(this EventMessageBase message, IBotState botState)
        {
            if (botState == null)
            {
                throw new ArgumentNullException(nameof(botState));
            }

            if (!IsActivePlainMessage(message))
            {
                return(false);
            }

            var messageBase = CastTo <MessageBase>(message);

            if (botState.Ims.Any(i => i.Id == messageBase.Channel))
            {
                return(true);
            }

            return(false);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Posts all links archived, throws <see cref="ArgumentNullException"/> if you attempt to call this with any null arguments
        /// </summary>
        /// <param name="config"></param>
        /// <param name="state"></param>
        /// <param name="head"></param>
        /// <param name="post"></param>
        /// <param name="ArchiveList"></param>
        public static void PostArchiveLinks(Config config, IBotState state, string head, Post post, List <string> ArchiveList)
        {
            if (config == null || state == null || head == null || post == null || ArchiveList == null)
            {
                throw new ArgumentNullException(config == null ? nameof(config) : state == null ? nameof(state) : head == null ? nameof(head) : post == null ? nameof(post) : nameof(ArchiveList));
            }
            Console.Title = $"Posting new comment to post {post.Id}";
            string  LinksListBody = string.Join("", ArchiveList);
            string  c             = head + LinksListBody + "\n" + string.Format(Program.Headers[3], config.FlavorText[rand.Next(0, config.FlavorText.Length)]);
            Comment botComment    = post.Comment(c);

            try
            {
                state.AddBotComment(post.Id, botComment.Id);
                Console.WriteLine(c);
            }
            catch (InvalidOperationException e)
            {
                Console.WriteLine($"Caught exception replying to post {post.Id} with new comment  {Regex.Replace(botComment.Id, "t1_", "")}: {e.Message}");
                botComment.Del();
            }
        }
Ejemplo n.º 21
0
 public static BotData GetConversationData(this IBotState operations, string channelId, string conversationId)
 {
     return(Task.Factory.StartNew(s => ((IBotState)s).GetConversationDataAsync(channelId, conversationId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }
Ejemplo n.º 22
0
 public static IList <string> DeleteStateForUser(this IBotState operations, string channelId, string userId)
 {
     return(operations.DeleteStateForUserAsync(channelId, userId).GetAwaiter().GetResult());
 }
Ejemplo n.º 23
0
 public static string[] DeleteStateForUser(this IBotState operations, string channelId, string userId)
 {
     return(Task.Factory.StartNew(s => ((IBotState)s).DeleteStateForUserAsync(channelId, userId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }
Ejemplo n.º 24
0
 public static BotData SetConversationData(this IBotState operations, string channelId, string conversationId, BotData botData)
 {
     return(operations.SetConversationDataAsync(channelId, conversationId, botData).GetAwaiter().GetResult());
 }
Ejemplo n.º 25
0
 /// <summary>
 /// ExportBotStateData
 /// </summary>
 /// <remarks>
 /// get all the state data for a bot in this channel. This returns a list of
 /// BotStateData and (possibly) a continuation token
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='channelId'>
 /// the channelId
 /// </param>
 /// <param name='continuationToken'>
 /// the skip token returned previously, or null
 /// </param>
 public static BotStateDataResult ExportBotStateData(this IBotState operations, string channelId, string continuationToken = default(string))
 {
     return(operations.ExportBotStateDataAsync(channelId, continuationToken).GetAwaiter().GetResult());
 }
Ejemplo n.º 26
0
        /// <summary>
        /// SetUserData
        /// </summary>
        /// Update the bot's data for a user
        /// <param name='operations'>
        /// The operations group for this extension method.
        /// </param>
        /// <param name='channelId'>
        /// channelId
        /// </param>
        /// <param name='userId'>
        /// id for the user on the channel
        /// </param>
        /// <param name='botData'>
        /// the new botdata
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        public static async Task <BotData> SetUserDataAsync(this IBotState operations, string channelId, string userId, BotData botData, CancellationToken cancellationToken = default(CancellationToken))
        {
            var _result = await operations.SetUserDataWithHttpMessagesAsync(channelId, userId, botData, null, cancellationToken).ConfigureAwait(false);

            return(_result.HandleError <BotData>());
        }
Ejemplo n.º 27
0
        /// <summary>
        /// DeleteStateForUser
        /// </summary>
        /// Delete all data for a user in a channel (UserData and
        /// PrivateConversationData)
        /// <param name='operations'>
        /// The operations group for this extension method.
        /// </param>
        /// <param name='channelId'>
        /// channelId
        /// </param>
        /// <param name='userId'>
        /// id for the user on the channel
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        public static async Task <string[]> DeleteStateForUserAsync(this IBotState operations, string channelId, string userId, CancellationToken cancellationToken = default(CancellationToken))
        {
            var _result = await operations.DeleteStateForUserWithHttpMessagesAsync(channelId, userId, null, cancellationToken).ConfigureAwait(false);

            return(_result.HandleError <string[]>());
        }
Ejemplo n.º 28
0
 public static BotData SetUserData(this IBotState operations, string channelId, string userId, BotData botData)
 {
     return(operations.SetUserDataAsync(channelId, userId, botData).GetAwaiter().GetResult());
 }
Ejemplo n.º 29
0
 public static BotData SetUserData(this IBotState operations, string channelId, string userId, BotData botData)
 {
     return(Task.Factory.StartNew(s => ((IBotState)s).SetUserDataAsync(channelId, userId, botData), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }
Ejemplo n.º 30
0
 public static BotData GetPrivateConversationData(this IBotState operations, string channelId, string conversationId, string userId)
 {
     return(operations.GetPrivateConversationDataAsync(channelId, conversationId, userId).GetAwaiter().GetResult());
 }