-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTelegram.cs
More file actions
95 lines (81 loc) · 2.67 KB
/
Telegram.cs
File metadata and controls
95 lines (81 loc) · 2.67 KB
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
90
91
92
93
94
95
using System.Net;
using System.Net.Http.Json;
namespace bot
{
public class Telegram : IDisposable
{
public class User
{
public long Id { get; set; }
}
public class Chat
{
public long Id { get; set; }
}
public class Message
{
public long Message_id { get; set; }
public Chat Chat { get; set; } = new();
}
private class SendMessage
{
public long Chat_id { get; set; }
public string Text { get; set; } = "";
}
public class Update
{
public long Update_id { get; set; }
public Message? Message { get; set; }
}
private class Response<TEntity>
{
public bool Ok { get; set; }
public TEntity? Result { get; set; }
}
private readonly string _token;
private string GetPath(string method) => $"https://api.telegram.org/bot{_token}/{method}";
// private readonly HttpClient _client = new(new HttpClientHandler
// {
// Proxy = new WebProxy
// {
// Address = new Uri($"http://172.20.10.3:10809")
// }
// });
private readonly HttpClient _client = new();
public void Dispose()
{
_client?.Dispose();
GC.SuppressFinalize(this);
}
public Telegram(string token)
{
_token = token;
}
public async Task<User> GetMeAsync()
{
var ret = new Response<User>();
var res = await _client.GetAsync(GetPath("getMe"));
if (res.IsSuccessStatusCode)
ret = await res.Content.ReadFromJsonAsync<Response<User>>();
return ret?.Result ?? new User();
}
public async Task<IEnumerable<Chat>> GetAllChatsAsync()
{
var ret = new Response<Update[]>();
var res = await _client.GetAsync(GetPath("getUpdates"));
if (res.IsSuccessStatusCode)
ret = await res.Content.ReadFromJsonAsync<Response<Update[]>>();
return ret?.Result?.Select(u => u.Message?.Chat ?? new Chat())
.Where(chat => chat.Id != 0)
.GroupBy(chat => chat.Id)
.Select(g => g.First())
.ToList() ?? [];
}
public Task SendAsync(string text, params Chat[] chats) =>
Task.WhenAll(chats.Select(chat => new SendMessage
{
Chat_id = chat.Id,
Text = text
}).Select(message => _client.PostAsJsonAsync(GetPath("sendMessage"), message)));
}
}