-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
195 lines (170 loc) · 7.36 KB
/
Program.cs
File metadata and controls
195 lines (170 loc) · 7.36 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
using System.Text.Json;
using Telegram.Bot;
using Telegram.Bot.Args;
using Telegram.Bot.Types.Enums;
using Microsoft.Extensions.Configuration;
namespace TwitterNotification;
class Program
{
private static readonly HttpClient Client = new();
private static Dictionary<string, string> _lastTweetIds = new();
private static TelegramBotClient _telegramBotClient = null!;
private static IConfiguration? Configuration { get; set; }
private static string _rapidApiKey = string.Empty;
private static string _telegramChatId = string.Empty;
static async Task Main()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
_rapidApiKey = Configuration["RapidApiKey"];
string telegramBotToken = Configuration["TelegramBotToken"];
_telegramChatId = Configuration["TelegramChatId"];
string configFilePath = Configuration["ConfigFilePath"];
_telegramBotClient = new TelegramBotClient(telegramBotToken);
_telegramBotClient.OnMessage += Bot_OnMessage;
_telegramBotClient.StartReceiving();
await LoadConfig(configFilePath);
while (true)
{
await UpdateTweets(_rapidApiKey);
await Task.Delay(TimeSpan.FromHours(1));
}
}
static async Task UpdateTweets(string rapidApiKey)
{
foreach (var username in _lastTweetIds.Keys.ToList())
{
try
{
string? newTweetId = await GetLatestTweetId(username, rapidApiKey);
if (!string.IsNullOrEmpty(newTweetId) && newTweetId != _lastTweetIds[username])
{
_lastTweetIds[username] = newTweetId;
await SendTelegramMessage(username, newTweetId);
}
}
catch (Exception ex)
{
Console.WriteLine($"Ошибка при получении твита: {ex.Message}");
}
}
}
static async Task<string> GetLatestTweetId(string username, string rapidApiKey)
{
string url = $"https://twitter154.p.rapidapi.com/user/tweets?username={username}&limit=3&include_replies=false&include_pinned=false";
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(url),
Headers =
{
{ "X-RapidAPI-Key", rapidApiKey },
{ "X-RapidAPI-Host", "twitter154.p.rapidapi.com" }
}
};
using (var response = await Client.SendAsync(request))
{
var body = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
Console.WriteLine($"Failed to get tweets for {username}. Status code: {response.StatusCode}. Body: {body}");
return string.Empty;
}
var jsonDocument = JsonDocument.Parse(body);
var resultsArray = jsonDocument.RootElement.GetProperty("results");
if (resultsArray.GetArrayLength() > 0)
{
if (resultsArray[0].TryGetProperty("tweet_id", out var tweetIdProperty))
{
string tweetId = tweetIdProperty.GetString() ?? string.Empty;
// Add pretty print output
string tweetUrl = $"https://twitter.com/{username}/status/{tweetId}";
Console.WriteLine($"New tweet from {username}: {tweetUrl}");
return tweetId;
}
if (resultsArray[0].TryGetProperty("text", out var tweetTextProperty))
{
Console.WriteLine($"Tweet text: {tweetTextProperty.GetString()}");
}
}
return string.Empty;
}
}
static async Task SendTelegramMessage(string username, string tweetId)
{
string tweetUrl = $"https://twitter.com/{username}/status/{tweetId}";
string message = $"@{username}{Environment.NewLine}Открыть твит: {tweetUrl}";
await _telegramBotClient.SendTextMessageAsync(_telegramChatId, message);
}
static async void Bot_OnMessage(object? sender, MessageEventArgs e)
{
var message = e.Message;
string configFilePath = Configuration["ConfigFilePath"];
if (message.Type == MessageType.Text)
{
if (message.Text.StartsWith("/add"))
{
string username = message.Text.Substring(4).Trim();
if (!_lastTweetIds.ContainsKey(username))
{
_lastTweetIds[username] = string.Empty;
await _telegramBotClient.SendTextMessageAsync(message.Chat.Id, $"Аккаунт {username} добавлен в список отслеживаемых.");
await SaveConfig(configFilePath);
}
else
{
await _telegramBotClient.SendTextMessageAsync(message.Chat.Id, $"Аккаунт {username} уже присутствует в списке отслеживаемых.");
}
}
else if (message.Text.StartsWith("/remove"))
{
string username = message.Text.Substring(7).Trim();
if (_lastTweetIds.ContainsKey(username))
{
_lastTweetIds.Remove(username);
await _telegramBotClient.SendTextMessageAsync(message.Chat.Id, $"Аккаунт {username} удален из списка отслеживаемых.");
await SaveConfig(configFilePath);
}
else
{
await _telegramBotClient.SendTextMessageAsync(message.Chat.Id, $"Аккаунт {username} не найден в списке отслеживаемых.");
}
}
else if (message.Text == "/list")
{
string userList = string.Join(Environment.NewLine, _lastTweetIds.Keys);
string response = string.IsNullOrEmpty(userList) ? "Список отслеживаемых аккаунтов пуст." : $"Отслеживаемые аккаунты:{Environment.NewLine}{userList}";
await _telegramBotClient.SendTextMessageAsync(message.Chat.Id, response);
}
}
}
static async Task LoadConfig(string configFilePath)
{
try
{
if (File.Exists(configFilePath))
{
string json = await File.ReadAllTextAsync(configFilePath);
_lastTweetIds = JsonSerializer.Deserialize<Dictionary<string, string>>(json) ?? new Dictionary<string, string>();
}
}
catch (Exception ex)
{
Console.WriteLine($"Ошибка при загрузке конфигурации: {ex.Message}");
}
}
static async Task SaveConfig(string configFilePath)
{
try
{
string json = JsonSerializer.Serialize(_lastTweetIds);
await File.WriteAllTextAsync(configFilePath, json);
}
catch (Exception ex)
{
Console.WriteLine($"Ошибка при сохранении конфигурации: {ex.Message}");
}
}
}