-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
409 lines (364 loc) · 16.1 KB
/
Program.cs
File metadata and controls
409 lines (364 loc) · 16.1 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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
using Dota2.GC;
using Dota2.GC.Dota.Internal;
using Newtonsoft.Json;
using SteamKit2;
using SteamKit2.Discovery;
using SteamKit2.GC;
using SteamKit2.Internal;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using static Dota2.GC.Dota.Internal.CMsgDOTARequestChatChannelListResponse;
namespace DotaSpamBot
{
class DebugListener : IDebugListener
{
public void WriteLine(string category, string msg)
{
Console.WriteLine($"DebugListener [{category}]: {msg}");
}
}
class Program
{
private SteamClient steamClient;
private CallbackManager manager;
private DotaGCHandler dota;
private ConfigModel botConfig;
private SteamUser steamUser;
private bool isRunning;
private bool dotaIsReady;
private string authCode, twoFactorAuth;
private List<ChatChannel> targetChannels;
private int totalProccessedCount;
private string[] chatRegions;
static void Main(string[] args)
{
var program = new Program();
program.Run().GetAwaiter().GetResult();
}
private async Task Run()
{
try
{
if (File.Exists("config.json"))
{
using (var sr = new StreamReader("config.json"))
{
string jsonString = string.Empty;
string line;
while ((line = sr.ReadLine()) != null)
{
jsonString += line;
}
botConfig = JsonConvert.DeserializeObject<ConfigModel>(jsonString);
if (string.IsNullOrEmpty(botConfig.login))
{
Console.WriteLine("ERROR: Steam login is empty");
await Task.Delay(3000);
return;
}
if (string.IsNullOrEmpty(botConfig.password))
{
Console.WriteLine("ERROR: Steam password is empty");
await Task.Delay(3000);
return;
}
if (string.IsNullOrEmpty(botConfig.msgText))
{
Console.WriteLine("ERROR: Message content is empty");
await Task.Delay(3000);
return;
}
}
}
else
{
Console.WriteLine("ERROR: config.json file is not found");
await Task.Delay(3000);
return;
}
if(File.Exists("chat_regions.txt"))
{
chatRegions = File.ReadAllLines("chat_regions.txt");
}
//DebugLog.AddListener(new DebugListener());
//DebugLog.Enabled = true;
//create our steamclient instance
var cellid = 0u;
// if we've previously connected and saved our cellid, load it.
if (File.Exists("cellid.txt"))
{
if (!uint.TryParse(File.ReadAllText("cellid.txt"), out cellid))
{
Console.WriteLine("Error parsing cellid from cellid.txt. Continuing with cellid 0.");
cellid = 0;
}
else
{
Console.WriteLine($"Using persisted cell ID {cellid}");
}
}
var configuration = SteamConfiguration.Create((config) =>
{
config.WithServerListProvider(new FileStorageServerListProvider("servers_list.bin"));
config.WithCellID(cellid);
});
steamClient = new SteamClient(configuration);
DotaGCHandler.Bootstrap(steamClient);
dota = steamClient.GetHandler<DotaGCHandler>();
// create the callback manager which will route callbacks to function calls
manager = new CallbackManager(steamClient);
// get the steamuser handler, which is used for logging on after successfully connecting
steamUser = steamClient.GetHandler<SteamUser>();
// register a few callbacks we're interested in
// these are registered upon creation to a callback manager, which will then route the callbacks
// to the functions specified
manager.Subscribe<SteamClient.ConnectedCallback>(OnConnected);
manager.Subscribe<SteamClient.DisconnectedCallback>(OnDisconnected);
manager.Subscribe<SteamUser.LoggedOnCallback>(OnLoggedOn);
manager.Subscribe<SteamUser.LoggedOffCallback>(OnLoggedOff);
manager.Subscribe<SteamUser.UpdateMachineAuthCallback>(OnMachineAuth);
manager.Subscribe<DotaGCHandler.BeginSessionResponse>(OnBeginSession);
manager.Subscribe<DotaGCHandler.ConnectionStatus>(OnConnectionStatus);
manager.Subscribe<DotaGCHandler.JoinChatChannelResponse>(OnJoinChatChannel);
manager.Subscribe<DotaGCHandler.ChatChannelListResponse>(OnChatChannelList);
manager.Subscribe<DotaGCHandler.GCWelcomeCallback>(OnDotaWelcome);
isRunning = true;
Console.WriteLine("Connecting to Steam...");
// initiate the connection
steamClient.Connect();
while (isRunning)
{
manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception occured: {ex.GetType()}: {ex.Message}");
dotaIsReady = false;
steamClient.Disconnect();
}
await Task.Delay(-1);
}
private void OnDotaWelcome(DotaGCHandler.GCWelcomeCallback callback)
{
if (!dotaIsReady && dota.Ready)
{
dotaIsReady = true;
Console.WriteLine($"Requesting channel list...");
dota.RequestChatChannelList();
}
}
//public void Send(IClientGCMsg msg)
//{
// var clientMsg = new ClientMsgProtobuf<CMsgGCClient>(EMsg.ClientToGC);
// clientMsg.Body.msgtype = MsgUtil.MakeGCMsg(msg.MsgType, msg.IsProto);
// clientMsg.Body.appid = (uint)570;
// clientMsg.Body.payload = msg.Serialize();
// steamClient.Send(clientMsg);
//}
private void OnConnectionStatus(DotaGCHandler.ConnectionStatus callback)
{
if (callback.result.status == Dota2.GC.Internal.GCConnectionStatus.GCConnectionStatus_NO_SESSION_IN_LOGON_QUEUE)
{
dotaIsReady = false;
Console.WriteLine("Waiting for LOGON QUEUE 10 seconds...");
Thread.Sleep(TimeSpan.FromSeconds(10));
return;
}
if (callback.result.status != Dota2.GC.Internal.GCConnectionStatus.GCConnectionStatus_HAVE_SESSION)
{
dotaIsReady = false;
if (dota.Ready)
dota.Stop();
dota.Start();
}
}
private void OnBeginSession(DotaGCHandler.BeginSessionResponse callback)
{
Console.WriteLine($"Starting session ID: {callback.response.SessionId}: [{callback.response.Result}]");
}
private void OnChatChannelList(DotaGCHandler.ChatChannelListResponse callback)
{
Console.WriteLine("Updating channel list...");
var chatChannels = callback.result.channels;
targetChannels?.Clear();
targetChannels = chatChannels.FindAll(x => x.num_members >= botConfig.minChannelUsersCount);
//targetChannels = new List<ChatChannel> { new ChatChannel { channel_name = "Kazan, TT", channel_type = DOTAChatChannelType_t.DOTAChannelType_Regional } };
if(chatRegions != null && chatRegions.Length > 0)
{
targetChannels.AddRange(chatRegions.Select(x => new ChatChannel { channel_name = x }));
}
Console.WriteLine($"{targetChannels?.Count} channels found");
JoinChannels();
}
private void OnJoinChatChannel(DotaGCHandler.JoinChatChannelResponse callback)
{
if (callback.result.result == CMsgDOTAJoinChatChannelResponse.Result.USER_IN_TOO_MANY_CHANNELS)
{
Console.WriteLine($"Connected channels limit exceed");
dota.LeaveChatChannel(callback.result.channel_id);
}
if (callback.result.result != CMsgDOTAJoinChatChannelResponse.Result.JOIN_SUCCESS)
{
Console.WriteLine($"Failed to join {callback.result?.channel_name} ({callback.result?.channel_id})");
}
else
{
Console.WriteLine($"Sending message to {callback.result?.channel_name} ({callback.result?.channel_id})");
SendMessage(callback.result.channel_id);
Console.WriteLine($"Leaving channel {callback.result?.channel_name} ({callback.result?.channel_id})");
dota.LeaveChatChannel(callback.result.channel_id);
}
totalProccessedCount++;
Console.WriteLine($"Processed channels count: {totalProccessedCount}");
if (steamClient.IsConnected && targetChannels != null && targetChannels.Count != 0)
{
if (totalProccessedCount == targetChannels.Count-1)
{
totalProccessedCount = 0;
dota.RequestChatChannelList();
}
}
}
private void OnLoggedOff(SteamUser.LoggedOffCallback callback)
{
Console.WriteLine($"Logged off of Steam: {callback.Result}");
}
private void OnLoggedOn(SteamUser.LoggedOnCallback callback)
{
bool isSteamGuard = callback.Result == EResult.AccountLogonDenied;
bool is2FA = callback.Result == EResult.AccountLoginDeniedNeedTwoFactor;
if (isSteamGuard || is2FA)
{
Console.WriteLine("This account is SteamGuard protected!");
if (is2FA)
{
Console.Write("Please enter your 2 factor auth code from your authenticator app: ");
twoFactorAuth = Console.ReadLine();
}
else
{
Console.Write($"Please enter the auth code sent to the email at {callback.EmailDomain}: ");
authCode = Console.ReadLine();
}
return;
}
if (callback.Result != EResult.OK)
{
if (callback.Result == EResult.AccountLogonDenied)
{
// if we recieve AccountLogonDenied or one of it's flavors (AccountLogonDeniedNoMailSent, etc)
// then the account we're logging into is SteamGuard protected
// see sample 5 for how SteamGuard can be handled
Console.WriteLine("Unable to logon to Steam: This account is SteamGuard protected.");
isRunning = false;
return;
}
Console.WriteLine($"Unable to logon to Steam: {callback.Result} / {callback.ExtendedResult}");
isRunning = false;
return;
}
File.WriteAllText("cellid.txt", callback.CellID.ToString());
Console.WriteLine("Successfully logged on!");
if (!dota.Ready)
{
Console.WriteLine($"Starting dota...");
dota.Start();
}
else
{
dotaIsReady = true;
Console.WriteLine($"Requesting channel list...");
dota.RequestChatChannelList();
}
}
private void OnDisconnected(SteamClient.DisconnectedCallback callback)
{
dotaIsReady = false;
Console.WriteLine("Disconnected from Steam, reconnecting in 5 seconds...");
System.Threading.Thread.Sleep(5000);
if (dota != null && dota.Ready)
dota.Stop();
if (steamClient.IsConnected)
steamClient.Disconnect();
steamClient.Connect();
}
private void OnConnected(SteamClient.ConnectedCallback callback)
{
Console.WriteLine($"Connected to Steam! Logging in '{botConfig.login}'...");
byte[] sentryHash = null;
if (File.Exists("sentry.bin"))
{
// if we have a saved sentry file, read and sha-1 hash it
byte[] sentryFile = File.ReadAllBytes("sentry.bin");
sentryHash = CryptoHelper.SHAHash(sentryFile);
}
steamUser.LogOn(new SteamUser.LogOnDetails
{
Username = botConfig.login,
Password = botConfig.password,
// in this sample, we pass in an additional authcode
// this value will be null (which is the default) for our first logon attempt
AuthCode = authCode,
TwoFactorCode = twoFactorAuth,
// our subsequent logons use the hash of the sentry file as proof of ownership of the file
// this will also be null for our first (no authcode) and second (authcode only) logon attempts
SentryFileHash = sentryHash,
ClientLanguage = "Russian"
});
}
private void OnMachineAuth(SteamUser.UpdateMachineAuthCallback callback)
{
Console.WriteLine("Updating sentryfile...");
// write out our sentry file
// ideally we'd want to write to the filename specified in the callback
// but then this sample would require more code to find the correct sentry file to read during logon
// for the sake of simplicity, we'll just use "sentry.bin"
int fileSize;
byte[] sentryHash;
using (var fs = File.Open("sentry.bin", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
fs.Seek(callback.Offset, SeekOrigin.Begin);
fs.Write(callback.Data, 0, callback.BytesToWrite);
fileSize = (int)fs.Length;
fs.Seek(0, SeekOrigin.Begin);
using (var sha = SHA1.Create())
{
sentryHash = sha.ComputeHash(fs);
}
}
// inform the steam servers that we're accepting this sentry file
steamUser.SendMachineAuthResponse(new SteamUser.MachineAuthDetails
{
JobID = callback.JobID,
FileName = callback.FileName,
BytesWritten = callback.BytesToWrite,
FileSize = fileSize,
Offset = callback.Offset,
Result = EResult.OK,
LastError = 0,
OneTimePassword = callback.OneTimePassword,
SentryFileHash = sentryHash,
});
Console.WriteLine("Updating sentryfile has been done!");
}
private async void JoinChannels()
{
for (int i = 0; i < targetChannels.Count; i++)
{
dota.JoinChatChannel(targetChannels[i].channel_name, targetChannels[i].channel_type);
await Task.Delay(10000);
}
}
private void SendMessage(ulong channelId)
{
var message = botConfig.msgText;
dota.SendChannelMessage(channelId, message);
}
}
}