mirror of
https://github.com/Bubuni-Team/telegram-bot.git
synced 2026-07-31 00:29:24 +03:00
Initial webhook support
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
using BotFramework.Abstractions.UpdateProvider;
|
||||
using BotFramework.Config;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Newtonsoft.Json;
|
||||
using System.Threading.Tasks;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types;
|
||||
|
||||
namespace Kruzya.TelegramBot.Core.Controllers
|
||||
{
|
||||
[Route("/Telegram")]
|
||||
public class Telegram : Controller
|
||||
{
|
||||
private const string SecretTokenHeader = "X-Telegram-Bot-Api-Secret-Token";
|
||||
|
||||
private readonly ILogger<Telegram> _logger;
|
||||
private readonly ITelegramBotClient _client;
|
||||
private readonly IUpdateTarget _updateTarget;
|
||||
private readonly string _secretToken;
|
||||
|
||||
public Telegram(ILogger<Telegram> logger, ITelegramBotClient client, IUpdateTarget updateTarget, IOptions<BotConfig> config)
|
||||
{
|
||||
_logger = logger;
|
||||
_client = client;
|
||||
_updateTarget = updateTarget;
|
||||
|
||||
_secretToken = config.Value.Webhook.SecretToken;
|
||||
if (string.IsNullOrEmpty(_secretToken))
|
||||
{
|
||||
_secretToken = null;
|
||||
}
|
||||
}
|
||||
|
||||
[Route("/WebHook")]
|
||||
[HttpPost]
|
||||
public IActionResult Index()
|
||||
{
|
||||
if (_secretToken != null && !Request.Headers.ContainsKey(SecretTokenHeader))
|
||||
{
|
||||
_logger.LogWarning("Someone tried push update without secret key in headers");
|
||||
return BadRequest();
|
||||
}
|
||||
|
||||
var ok = (_secretToken == null || Request.Headers[SecretTokenHeader] == _secretToken);
|
||||
if (!ok)
|
||||
{
|
||||
_logger.LogWarning("Someone tried push update with wrong secret key in headers");
|
||||
return BadRequest();
|
||||
}
|
||||
|
||||
LaunchHandle();
|
||||
return Ok();
|
||||
}
|
||||
|
||||
private void LaunchHandle()
|
||||
{
|
||||
try
|
||||
{
|
||||
var update = JsonConvert.DeserializeObject<Update>(Request.Body.ToString());
|
||||
if (update == null)
|
||||
{
|
||||
throw new System.Exception("Invalid request body");
|
||||
}
|
||||
|
||||
_updateTarget.Push(update);
|
||||
}
|
||||
catch (System.Exception e)
|
||||
{
|
||||
_logger.LogError($"Error occured when handling a new update: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user