Recently, I researched monitoring group messages on Telegram and planned to extract key information from the received messages to save it to my local database. I utilized the code from the open-source repository https://github.com/Riniba/TelegramMonitor?tab=readme-ov-file, adding HTTP requests to it. First, open the source code. Right-click to open the Manage NuGet Packages and add two packages.
You can add all three of these.
Then import them globally here. This way, you can use them normally. Add the relevant code in program.cs.
// Create service collection var services = new ServiceCollection();
// Add HttpClient service services.AddHttpClient("MyClient", client => { client.BaseAddress = new Uri("http://localhost:5000"); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); });
// Build service provider var serviceProvider = services.BuildServiceProvider();
// Get HttpClientFactory var httpClientFactory = serviceProvider.GetRequiredService<IHttpClientFactory>();
await SendPostRequest(httpClientFactory);
static async Task SendPostRequest(IHttpClientFactory httpClientFactory){ var client = httpClientFactory.CreateClient("MyClient"); // Note that the name here must match the service name added earlier, creating different HTTP requests by different service names. // Set Bearer Token const string bearerToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NDU1OTI5NDMsImlkZW50aXR5IjoxLCJzY29wZSI6ImxpbiIsInR5cGUiOiJhY2Nlc3MiLCJpYXQiOjE3NDU1ODkzNDN9.kcU-VrvoqKWQvAPkCBvMmqm8eRl-mlnVj_yxjbU1QTY"; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
// Prepare data var postData = new { title = "Baidu", link = "http://www.baidu11.com", summary = "111", image = "111" };
try { var jsonContent = JsonSerializer.Serialize(postData); var content = new System.Net.Http.StringContent(jsonContent, Encoding.UTF8, "application/json");
var response = await client.PostAsync("/v1/link", content); response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine($"Response: {responseBody}"); } catch (HttpRequestException ex) { Console.WriteLine($"Request failed: {ex.Message}"); }}
The related libraries cannot be missing. The following code shows areas for improvement.
Create Data Model
public class PostData{ public string Title { get; set; } public string Link { get; set; } public string Summary { get; set; } public string Image { get; set; }}
// Create request data var postData = new PostData { Title = "Baidu", Link = "http://www.baidu.com", Summary = "111", Image = "111" };