gpt4 book ai didi

c# - 无法发布事件。未经授权。机器人模拟器错误

转载 作者:行者123 更新时间:2023-12-05 06:27:03 26 4
gpt4 key购买 nike

我已将这些代码行添加到我的机器人的 Startup.cs 中,以便它能够在 Azure 的 WebChat 中工作:

var appid = Configuration.GetSection("microsoftappid").Value;
var apppassword = Configuration.GetSection("microsoftapppassword").Value;
options.CredentialProvider = new SimpleCredentialProvider(appid, apppassword);

但是,当我有这些行时,我的机器人无法在机器人模拟器中工作。如何将它与我的机器人集成,以便在模拟器中发布和打开我的机器人时不需要注释/取消注释代码行。我还不太擅长阅读代码,所以很抱歉问这个问题。谢谢!

public class Startup
{
private ILoggerFactory _loggerFactory;
private bool _isProduction = false;

public Startup(IHostingEnvironment env)
{
_isProduction = env.IsProduction();

var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();

Configuration = builder.Build();
}

public IConfiguration Configuration { get; }


public void ConfigureServices(IServiceCollection services)
{
var secretKey = Configuration.GetSection("botFileSecret")?.Value;
var botFilePath = Configuration.GetSection("botFilePath")?.Value;
if (!File.Exists(botFilePath))
{
throw new FileNotFoundException($"The .bot configuration file was not found. botFilePath: {botFilePath}");
}

BotConfiguration botConfig = null;
try
{
botConfig = BotConfiguration.Load(botFilePath, secretKey);
}
catch
{
var msg = @"Error reading bot file. Please ensure you have valid botFilePath and botFileSecret set for your environment.
- You can find the botFilePath and botFileSecret in the Azure App Service application settings.
- If you are running this bot locally, consider adding a appsettings.json file with botFilePath and botFileSecret.
- See https://aka.ms/about-bot-file to learn more about .bot file its use and bot configuration.
";
throw new InvalidOperationException(msg);
}

services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot configuration file could not be loaded. botFilePath: {botFilePath}"));

var connectedServices = InitBotServices(botConfig);
services.AddSingleton(sp => connectedServices);

var environment = _isProduction ? "production" : "development";
var service = botConfig.Services.FirstOrDefault(s => s.Type == "endpoint" && s.Name == environment);
if (service == null && _isProduction)
{

service = botConfig.Services.Where(s => s.Type == "endpoint" && s.Name == "development").FirstOrDefault();
}

if (!(service is EndpointService endpointService))
{
throw new InvalidOperationException($"The .bot file does not contain an endpoint with name '{environment}'.");
}

services.AddBot<CoreBot>(options =>
{
options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword);
options.ChannelProvider = new ConfigurationChannelProvider(Configuration);

var appid = Configuration.GetSection("microsoftappid").Value;
var apppassword = Configuration.GetSection("microsoftapppassword").Value;
options.CredentialProvider = new SimpleCredentialProvider(appid, apppassword);

ILogger logger = _loggerFactory.CreateLogger<CoreBot>();
options.OnTurnError = async (context, exception) =>
{
logger.LogError($"Exception caught : {exception}");
await context.SendActivityAsync($"Oops Sorry, it looks like something went wrong.");
};

IStorage dataStore = new MemoryStorage();

var conversationState = new ConversationState(dataStore);
options.State.Add(conversationState);

var userState = new UserState(dataStore);
options.State.Add(userState);

});

services.AddSingleton<BasicAccessors>(sp =>
{
var options = sp.GetRequiredService<IOptions<BotFrameworkOptions>>().Value;
if (options == null)
{
throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the state accessors");
}

var conversationState = options.State.OfType<ConversationState>().FirstOrDefault();
if (conversationState == null)
{
throw new InvalidOperationException(
"ConversationState must be defined and added before adding conversation-scoped state accessors.");
}

var userState = options.State.OfType<UserState>().FirstOrDefault();
if (userState == null)
{
throw new InvalidOperationException(
"UserState must be defined and added before adding user-scoped state accessors.");
}

var accessors = new BasicAccessors(conversationState, userState)
{
DialogStateAccessor = conversationState.CreateProperty<DialogState>(BasicAccessors.DialogStateAccessorName),
UserStateAccessor = userState.CreateProperty<UserProfile>(BasicAccessors.UserStateAccessorName),
ComplaintTicketAccessor = conversationState.CreateProperty<ComplaintTicket>(BasicAccessors.ComplaintTicketName),
};

return accessors;
});
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
_loggerFactory = loggerFactory;

app.UseDefaultFiles()
.UseStaticFiles()
.UseBotFramework();
}

private static BotServices InitBotServices(BotConfiguration config)
{
var qnaServices = new Dictionary<string, QnAMaker>();
var luisServices = new Dictionary<string, LuisRecognizer>();

foreach (var service in config.Services)
{
switch (service.Type)
{
case ServiceTypes.Luis:
{
if (!(service is LuisService luis))
{
throw new InvalidOperationException("The LUIS service is not configured correctly in your '.bot' file.");
}

var app = new LuisApplication(luis.AppId, luis.SubscriptionKey, luis.GetEndpoint());
var recognizer = new LuisRecognizer(app);
luisServices.Add(luis.Name, recognizer);
break;
}

case ServiceTypes.Dispatch:

if (!(service is DispatchService dispatch))
{
throw new InvalidOperationException("The Dispatch service is not configured correctly in your '.bot' file.");
}

var dispatchApp = new LuisApplication(dispatch.AppId, dispatch.AuthoringKey, dispatch.GetEndpoint());

var dispatchARecognizer = new LuisRecognizer(dispatchApp);
luisServices.Add(dispatch.Name, dispatchARecognizer);
break;

case ServiceTypes.QnA:
{

if (!(service is QnAMakerService qna))
{
throw new InvalidOperationException("The QnA service is not configured correctly in your '.bot' file.");
}

var qnaEndpoint = new QnAMakerEndpoint()
{
KnowledgeBaseId = qna.KbId,
EndpointKey = qna.EndpointKey,
Host = qna.Hostname,
};

var qnaMaker = new QnAMaker(qnaEndpoint);
qnaServices.Add(qna.Name, qnaMaker);

break;
}
}
}

return new BotServices(qnaServices, luisServices);
}
}

}

最佳答案

使用 2 个 .bot 文件(例如 dev.bot 和 prod.bot)

在 dev.bot 中,为模拟器添加端点,如下所示:

{
"type": "endpoint",
"name": "dev",
"endpoint": "http://localhost:3978/api/messages",
"appId": "",
"appPassword": "",
"id": "1"
},

您可以在 prod.bot 中添加 appId 和 appPassword 以及正确的端点(例如托管在 Azure 上:***.azurewebsites.net/api/messages)。

使用 appSettings.json + 创建 appSettings.dev.json 和 appSettings.prod.json。确保 .dev.json 设置

"botFilePath": ".\\dev.bot"

与 appSettings.prod.json 类似。

我发现当 ASPNETCORE_ENVIRONMENT 环境变量不等于正在使用的 .bot 文件中的“name”端点参数时,您会在模拟器中收到未经授权的错误。因此,在模拟器上进行本地调试时,请将 ASPNETCORE_ENVIRONMENT 设置为等于(在本例中)“dev”。

您可以通过右键单击 .NET core Web 项目 -> 属性 -> 调试(选项卡) -> 环境变量来设置此设置。

Set env vars in .NET core web project

关于c# - 无法发布事件。未经授权。机器人模拟器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55646534/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com