-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
80 lines (73 loc) · 2.54 KB
/
Copy pathProgram.cs
File metadata and controls
80 lines (73 loc) · 2.54 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
using RSMatrix;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using RSMatrix.Models;
using RSMatrix.Http;
using RSMatrix.Crypto;
// load environment variables or a .env file
DotNetEnv.Env.TraversePath().Load();
var userid = Environment.GetEnvironmentVariable("MATRIX_USER_ID");
var password = Environment.GetEnvironmentVariable("MATRIX_PASSWORD");
var device = Environment.GetEnvironmentVariable("MATRIX_DEVICE_ID");
if (string.IsNullOrWhiteSpace(userid) || string.IsNullOrWhiteSpace(password) || string.IsNullOrWhiteSpace(device))
{
throw new ArgumentException("Please provide the required environment variables: MATRIX_USER_ID, MATRIX_PASSWORD, MATRIX_DEVICE_ID");
}
//set up dependency injection
var services = new ServiceCollection()
.AddHttpClient()
.AddLogging(logging =>
{
logging.AddSimpleConsole(options =>
{
options.IncludeScopes = true;
options.SingleLine = true;
options.TimestampFormat = "hh:mm:ss ";
});
logging.AddFilter("System.Net.Http.HttpClient", LogLevel.Warning); // Filter logs from HttpClient
logging.SetMinimumLevel(LogLevel.Information); // Set minimum log level to Warning
})
.BuildServiceProvider();
//Using CancellationToken as a shutdown mechanism
var cancellationTokenSource = new CancellationTokenSource();
Console.CancelKeyPress += (sender, e) =>
{ // allows shutting down the app using Ctrl+C
e.Cancel = true;
cancellationTokenSource.Cancel();
};
try
{
var client = await MatrixTextClient.ConnectAsync(userid, password, device,
services.GetRequiredService<IHttpClientFactory>(), cancellationTokenSource.Token,
services.GetRequiredService<ILogger<MatrixTextClient>>());
client.DebugMode = true;
await foreach (var message in client.Messages.ReadAllAsync(cancellationTokenSource.Token))
{
await MessageReceivedAsync(message);
}
Console.WriteLine("Sync has ended.");
}
catch (OperationCanceledException)
{
Console.WriteLine("Shutdown requested...");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
await services.DisposeAsync();
}
Console.WriteLine("Goodbye!");
async Task MessageReceivedAsync(ReceivedTextMessage message)
{
Console.WriteLine(message);
var age = DateTimeOffset.Now - message.Timestamp;
if(message.Body?.Contains("ping") == true && age.TotalSeconds < 10)
{
await message.Room.SendTypingNotificationAsync();
await Task.Delay(2000);
await message.SendResponseAsync("pong!");
}
}