-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathTelegramProxy.cs
89 lines (74 loc) · 3.36 KB
/
TelegramProxy.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
using System.Net;
using System.Web;
using FluentValidation.Results;
using NLog;
using NzbDrone.Common.Extensions;
using NzbDrone.Common.Http;
using NzbDrone.Common.Serializer;
namespace NzbDrone.Core.Notifications.Telegram
{
public interface ITelegramProxy
{
void SendNotification(string title, string message, TelegramSettings settings);
ValidationFailure Test(TelegramSettings settings);
}
public class TelegramProxy : ITelegramProxy
{
private const string URL = "https://api.telegram.org";
private readonly IHttpClient _httpClient;
private readonly Logger _logger;
public TelegramProxy(IHttpClient httpClient, Logger logger)
{
_httpClient = httpClient;
_logger = logger;
}
public void SendNotification(string title, string message, TelegramSettings settings)
{
// Format text to add the title before and bold using markdown
var text = $"<b>{HttpUtility.HtmlEncode(title)}</b>\n{HttpUtility.HtmlEncode(message)}";
var requestBuilder = new HttpRequestBuilder(URL).Resource("bot{token}/sendmessage").Post();
var request = requestBuilder.SetSegment("token", settings.BotToken)
.AddFormParameter("chat_id", settings.ChatId)
.AddFormParameter("parse_mode", "HTML")
.AddFormParameter("text", text)
.AddFormParameter("disable_notification", settings.SendSilently)
.AddFormParameter("message_thread_id", settings.TopicId)
.Build();
_httpClient.Post(request);
}
public ValidationFailure Test(TelegramSettings settings)
{
try
{
const string title = "Test Notification";
const string body = "This is a test message from Sonarr";
SendNotification(title, body, settings);
}
catch (Exception ex)
{
_logger.Error(ex, "Unable to send test message");
if (ex is WebException webException)
{
return new ValidationFailure("Connection", $"{webException.Status.ToString()}: {webException.Message}");
}
else if (ex is Common.Http.HttpException restException && restException.Response.StatusCode == HttpStatusCode.BadRequest)
{
var error = Json.Deserialize<TelegramError>(restException.Response.Content);
var property = "BotToken";
if (error.Description.ContainsIgnoreCase("chat not found") || error.Description.ContainsIgnoreCase("group chat was upgraded to a supergroup chat"))
{
property = "ChatId";
}
else if (error.Description.ContainsIgnoreCase("message thread not found"))
{
property = "TopicId";
}
return new ValidationFailure(property, error.Description);
}
return new ValidationFailure("BotToken", "Unable to send test message");
}
return null;
}
}
}