如何解决服务器不响应机器人请求
我创建了一个服务器并决定向其中添加一个机器人。首先我加了一个类
public static class AppSettings
{
public static string Url { get; set; } = @"https://47bc6f8ba722.ngrok.io/{0}";
public static string Name { get; set; } = "Hop_hipBot";
public static string Key { get; set; } = "1549046386:AAHJtCMVaCT-8O3D_P8VLsfq6EKAr4P9JfSU";
}
然后我创建了一个命令和一个机器人。
public class Bot
{
private static TelegramBotClient botClient;
private static List<Command> commandsList;
public static IReadOnlyList<Command> Commands => commandsList.AsReadOnly();
public static async Task<TelegramBotClient> GetBotClientAsync()
{
if (botClient != null)
{
return botClient;
}
commandsList = new List<Command>();
commandsList.Add(new StartCommand());
//TODO: Add more commands
botClient = new TelegramBotClient(AppSettings.Key);
string hook = string.Format(AppSettings.Url,@"api/message/update");
await botClient.SetWebhookAsync(hook);
return botClient;
}
}
public class StartCommand : Command
{
public override string Name => @"/start";
public override bool Contains(Message message)
{
if (message.Type != Telegram.Bot.Types.Enums.MessageType.Text)
return false;
return message.Text.Contains(Name);
}
public override async Task Execute(Message message,TelegramBotClient botClient)
{
var chatId = message.Chat.Id;
await botClient.SendTextMessageAsync(chatId,"Hello I'm ASP.NET Core Bot");
}
}
然后我将所有东西都与控制器相连,并在 Startup.cs 的 Bot.GetBotClientAsync().Wait();
中添加 Configure()
[Route("api/message/update")]
public class MessageController : ControllerBase
{
// GET api/values
[HttpGet]
public string Get()
{
return "Method GET unuvalable";
}
[HttpPost]
public async Task<OkResult> Post([FromBody] Update update)
{
if (update == null) return Ok();
var commands = Bot.Commands;
var message = update.Message;
var botClient = await Bot.GetBotClientAsync();
foreach (var command in commands)
{
if (command.Contains(message))
{
await command.Execute(message,botClient);
break;
}
}
return Ok();
}
}
我在端口 44339 上启动服务器,并在 ngrox.exe http 44339
的帮助下为本地主机创建一个 URL,然后我开始一切。应用程序有效,沿 api/message/update
路由的 get 请求也有效,来自机器人的消息(我在 ngrok 检查上看到它),但服务器不响应它们。这与什么有关?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。