与bot framefork聊天的通用列表

时间:2018-05-09 19:32:14

标签: c# botframework bots telegram

我想用Microsoft Bot Framework(C#)构建简单的Telegram bot 我现在要做的是创建一个列表,可以由群聊中的每个人填写。我想要的结果:

user a: /add hello
user b: /add world
user a: /show
bot: hello world
user b: /show
bot: hello world

但我现在拥有的是:

user a: /add hello
user b: /add world
user a: /show
bot: hello
user b: /show
bot: world

[Serializable]
public class RootDialog : IDialog<object>
{
    private List<string> list = new List<string>();

    public Task StartAsync(IDialogContext context)
    {
        context.Wait(MessageReceivedAsync);

        return Task.CompletedTask;
    }

    private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
    {
        var activity = await result as Activity;
        switch (Parser.GetCommand(activity))
        {
            case "/add":
                AddNewThingToList(activity);
                break;
            case "/show":
                ShowList(context);
                break;
        }

        context.Wait(MessageReceivedAsync);
    }

    private void AddNewThingToList(Activity activity)
    {
        list.Add(Parser.GetAfterCommandText(activity));
    }

    private void ShowList(IDialogContext context)
    {
        var response = new StringBuilder();

        for (var i = 0; i < list.Count; i++)
        {
            response.Append($"{i}. {list[i]}{Environment.NewLine}");
        }

        context.PostAsync(response.ToString());
    }
}

创建公共列表的最简单方法是什么?

1 个答案:

答案 0 :(得分:1)

听起来您需要在单独的静态列表中使用列表来维护根对话框的所有实例之间的单个列表。可以通过RootDialog访问以下内容:

static class ListTest
{
    static List<string> _list; // Static List instance

    static ListTest()
    {
        _list = new List<string>();
    }

    public static void AddNewThingToList(Activity activity)
    {
        _list.Add(Parser.GetAfterCommandText(activity));
    }

    public static void ShowList()
    {
        var response = new StringBuilder();

        for (var i = 0; i < _list.Count; i++)
        {
            response.Append($"{i}. {_list[i]}{Environment.NewLine}");
        }
        return response;
    }
}

访问列表的多个读者/编写者必须考虑因素,但代码应该指向解决方案。