This repository has been archived by the owner on Sep 23, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
516 lines (486 loc) ยท 21.1 KB
/
Program.cs
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
๏ปฟusing System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Telesharp;
using Telesharp.Common.BotTypes;
using Telesharp.Common.Types;
using File = System.IO.File;
namespace LIKE5BOT
{
// (i) Information:
// Please, don't edit this sources and don't use for your works!!!
// It's better to create your own.
// by DaFri-Nochiterov
internal class Program
{
public static Bot Bot;
private static string _cacheDirectory;
//private static readonly Dictionary<int, DateTime> ClearedDatas = new Dictionary<int, DateTime>();
private static Dictionary<string, int[,]> _indexes;
#region Prog
private static void Main()
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
Bot = new Bot(new BotSettings(INSERT_YOUR_TOKEN_HERE)
{
InfoToConsole = true,
ExceptionsToConsole = true,
RequestsToConsole = true,
ResponsesToConsole = true,
Name = "LIKE5BOT",
GetProfile = true
});
_cacheDirectory = Environment.CurrentDirectory + Path.DirectorySeparatorChar + "WallCache" + Path.DirectorySeparatorChar;
if (!Directory.Exists(_cacheDirectory))
{
Directory.CreateDirectory(_cacheDirectory);
}
Run();
Bot.WaitToDie();
}
#endregion
private static void Run()
{
// Fix commands:
//var helpCommand = new HelpCommand();
var buttonsCommand = new WallpaperButtonsCommand();
Bot.OnParseMessage += (sender, eventArgs) =>
{
// Checking for message text is null
if (eventArgs.Message.Text == null || eventArgs.Message.Chat.Id == "-31756060") return;
// Checking for texts
switch (eventArgs.Message.Text.ToLower())
{
case "/stop":
case "nothing":
case "all":
case "โ๏ธ ok, it's all":
Bot.Methods.SendMessage(eventArgs.Message.Chat, "๐", false, new ReplyKeyboardHide());
return;
case "๐ menu":
buttonsCommand.Executed(eventArgs.Message);
return;
}
// Prepare message:
var messageText = eventArgs.Message.Text;
var indexOfName = messageText.IndexOf('@' + Bot.Me.UserName, StringComparison.OrdinalIgnoreCase);
messageText = messageText.ToLower().Remove(0, 1);
if (indexOfName != -1)
{
messageText = messageText.Remove(indexOfName - 1, Bot.Me.UserName.Length + 1);
}
eventArgs.Message.Text = messageText;
// Find command
switch (eventArgs.Message.Text)
{
case "wallpaper_auto":
SendWall(eventArgs.Message.Chat, "Auto");
break;
case "wallpaper_beauty":
SendWall(eventArgs.Message.Chat, "Beauty");
break;
case "wallpaper_cartoon":
SendWall(eventArgs.Message.Chat, "Cartoon");
break;
case "wallpaper_classic":
SendWall(eventArgs.Message.Chat, "Classic");
break;
case "wallpaper_game":
case "wallpaper_games":
SendWall(eventArgs.Message.Chat, "Game");
break;
case "wallpaper_holiday":
SendWall(eventArgs.Message.Chat, "Holiday");
break;
case "wallpaper_movies":
case "wallpaper_films":
SendWall(eventArgs.Message.Chat, "Movies");
break;
case "wallpaper_scenery":
case "wallpaper_nature":
case "wallpaper_landscape":
SendWall(eventArgs.Message.Chat, "Scenery");
break;
case "wallpaper_sports":
case "wallpaper_sport":
SendWall(eventArgs.Message.Chat, "Sports");
break;
case "help":
case "start":
// Help command
buttonsCommand.Executed(eventArgs.Message);
//helpCommand.Executed(eventArgs.Message);
break;
case "wallpaper":
buttonsCommand.Executed(eventArgs.Message);
break;
default:
// Trying to search other commands
CheckCommand(eventArgs.Message);
break;
}
};
Bot.Run();
}
public static void SendWall(Chat chat, string category)
{
// Getting ranges of wallpapers
var randrange = GetRange(category, GetRandomBoolean());
if (randrange.Length == 0)
{
Bot.Methods.SendMessage(chat, "โ ๏ธ Sorry, unable to connect with LIKE5.");
return;
}
// Sending preview:
SendPreviewWall(chat, (new Random()).Next(randrange[0], randrange[1]), category);
}
public static void SendFullWall(Message message, int id, string category)
{
var uploadDone = false;
Task.Factory.StartNew(() =>
{
while (!uploadDone)
{
Bot.Methods.SendChatAction(message.Chat, "upload_document");
Thread.Sleep(4999);
}
});
Task.Factory.StartNew(delegate
{
var filename = _cacheDirectory + id + ".jpg";
var readyId = '_' + category.ToLower() + '_' +
Path.GetFileName(filename).Replace(".jpg", "");
if (!File.Exists(filename))
{
var uri = $"http://hao.newtabplus.com/cloudWallpaper/{category}/{id}.jpg";
try
{
var wc = new WebClient();
wc.DownloadFile(uri, filename);
}
catch (WebException exc)
{
var errorResponse = exc.Response as HttpWebResponse;
if (errorResponse == null) return;
switch (errorResponse.StatusCode)
{
case HttpStatusCode.NotFound:
Bot.Methods.ReplyToMessage(message, "โ ๏ธ This wallpaper not found.");
break;
default:
Bot.Methods.ReplyToMessage(message, "โ ๏ธ Error, when download image. Try again in 5 seconds:\n"
+ "/fullsize" + readyId);
break;
}
uploadDone = true;
return;
}
}
var fileInfo = new FileInfo(filename);
if (IsFileLocked(fileInfo))
{
Bot.Methods.SendMessage(message.Chat, "Please wait...");
while (IsFileLocked(fileInfo)) { }
}
var markup = new ReplyKeyboardMarkup()
{
Keyboard = new[]
{
new[] { $"/wallpaper_{category.ToLower()}" },
new[] { "๐ Menu", "โ๏ธ Ok, it's all" }
},
ResizeKeyboard = true,
OneTimeKeyboard = true
};
var msg = Bot.Methods.ReplyToMessageWithDocumentFile(message, new FileInfo(filename), markup);
uploadDone = true;
if (msg != null)
{
Bot.Methods.SendMessage(message.Chat, "๐ก If you like this wallpapers visit LIKE5:\nhttp://www.like5.com ๐",
true);
}
else
{
Bot.Methods.SendMessage(message.Chat, "We are sorry, but something went wrong.");
}
GC.Collect();
});
}
public static void SendPreviewWall(Chat chat, int id, string category)
{
Bot.Methods.SendChatAction(chat, "upload_photo");
Task.Factory.StartNew(delegate
{
var filename = _cacheDirectory + "s_" + id + ".jpg";
var readyId = '_' + category.ToLower() + '_' +
Path.GetFileName(filename).Replace(".jpg", "").Replace("s_", "");
if (!File.Exists(filename))
{
var uri = $"http://hao.newtabplus.com/cloudWallpaper/{category}/s_{id}.jpg";
try
{
var wc = new WebClient();
wc.DownloadFile(uri, filename);
}
catch (WebException exc)
{
var errorResponse = exc.Response as HttpWebResponse;
if (errorResponse == null) return;
switch (errorResponse.StatusCode)
{
case HttpStatusCode.NotFound:
Bot.Methods.SendMessage(chat, "โ ๏ธ This wallpaper not found.");
break;
default:
Bot.Methods.SendMessage(chat, "โ ๏ธ Error, when get image. Try again in 5 seconds:\n"
+ "/fullsize" + readyId);
break;
}
return;
}
}
var fileInfo = new FileInfo(filename);
if (IsFileLocked(fileInfo))
{
Bot.Methods.SendMessage(chat, "Please wait...");
while (IsFileLocked(fileInfo))
{
Thread.Sleep(1000);
}
}
// + "\n/wallpaper_" + category.ToLower() + " - next wallpaper from this category",
var markup = new ReplyKeyboardMarkup()
{
Keyboard = new[]
{
new[] {$"/wallpaper_{category.ToLower()}"},
new[] {$"/fullsize{readyId}"},
new[] { "๐ Menu", "โ๏ธ Ok, it's all" }
},
ResizeKeyboard = true,
OneTimeKeyboard = false
};
Bot.Methods.SendPhotoFile(chat, filename, $"/fullsize{readyId}", markup);
GC.Collect();
});
}
public static void SendGoogleUrl(Message message, int id, string category)
{
var uri = $"http://hao.newtabplus.com/cloudWallpaper/{category}/s_{id}.jpg";
Bot.Methods.SendMessage(message.From,
"You can search this image in Google:\n" +
$"https://images.google.com/searchbyimage?image_url={Uri.EscapeDataString(uri)}&image_content=&filename=&hl=en");
}
public static void CheckCommand(Message message)
{
var chat = message.Chat;
var text = message.Text;
try
{
if (text.IndexOf("fullsize_", StringComparison.Ordinal) == 0)
{
text = text.Remove(0, 9);
var category = UppercaseFirst(text.Substring(0, text.IndexOf('_')));
text = text.Remove(0, text.IndexOf('_') + 1);
int id;
if (int.TryParse(text, out id))
{
SendFullWall(message, id, category);
}
}
else if (text.IndexOf("preview_", StringComparison.Ordinal) == 0)
{
text = text.Remove(0, 8);
var category = UppercaseFirst(text.Substring(0, text.IndexOf('_')));
text = text.Remove(0, text.IndexOf('_') + 1);
int id;
if (int.TryParse(text, out id))
{
SendPreviewWall(chat, id, category);
}
}
// else if (text.IndexOf("google_", StringComparison.Ordinal) == 0)
// {
// text = text.Remove(0, 7);
// var category = UppercaseFirst(text.Substring(0, text.IndexOf('_')));
// text = text.Remove(0, text.IndexOf('_') + 1);
// int id;
// if (int.TryParse(text, out id))
// {
// SendGoogleUrl(message, id, category);
// }
// }
}
catch
{
Bot.Methods.SendMessage(chat, "โ ๏ธ Something wrong with your command.");
}
}
public static bool IsFileLocked(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread
//or does not exist (has already been processed)
return true;
}
finally
{
stream?.Close();
}
//file is not locked
return false;
}
private static string UppercaseFirst(string s)
{
// Check for empty string.
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
// Return char and concat substring.
return char.ToUpper(s[0]) + s.Substring(1);
}
private static Dictionary<string, int[,]> GetIndexes()
{
var categoriesIndexes = new Dictionary<string, int[,]>();
var wc = new WebClient();
string json;
try
{
json = wc.DownloadString("http://hao.newtabplus.com/cloudWallpaper/index.json?t=0");
}
catch
{
return null;
}
Console.WriteLine(json);
var array = JToken.Parse(json);
foreach (var content in array.Children<JProperty>())
{
Console.WriteLine(content.Name + ": " + content.Value);
// Create new massive of values for category:
categoriesIndexes[content.Name.ToLower()] = new[,] {{0, 0}, {0, 0}};
var strings = ((string) content.Value).Split(','); // Get indexes
Array.Reverse(strings); // Reverse array
var i = 0;
foreach (var sStrings in strings.Select(s => s.Split('-')))
{
Array.Reverse(sStrings); // Reverse this array
var i2 = 0;
foreach (var sString in sStrings)
{
int val;
if (!int.TryParse(sString, out val)) continue;
// Skip if can parse
categoriesIndexes[content.Name.ToLower()][i, i2] = val;
i2++;
}
i++;
}
}
return categoriesIndexes;
}
public static int[] GetRange(string category, bool additionals)
{
if (_indexes == null)
{
var cacheIndexes = GetIndexes();
if (cacheIndexes == null)
{
return new int[0];
}
_indexes = cacheIndexes;
}
category = category.ToLower();
if (!additionals) return new[] {_indexes[category][0, 0], _indexes[category][0, 1]};
if (_indexes[category][1, 0] == 0 && _indexes[category][1, 1] == 0)
{
return new[] {_indexes[category][0, 0], _indexes[category][0, 1]};
}
return new[] {_indexes[category][1, 0], _indexes[category][1, 1]};
}
/// <summary>
/// Gets the random boolean.
/// </summary>
/// <returns></returns>
public static bool GetRandomBoolean()
{
return (new Random(DateTime.Now.Millisecond)).Next(0, 2) == 0;
}
//private class HelpCommand : SimpleComparerCommand
//{
// public HelpCommand()
// {
// CompareMode = Mode.BeginsWithTextFromOriginalMessage;
// HelpText = "Helpful command";
// Prototype = new Message(-1, "/help");
// }
// public override void Executed(Message message)
// {
// Bot.Methods.SendMessage(message.Chat, "Hello, i'm wallpaper bot!\n" +
// "I can send to you random wallpapers by catogories:\n" +
// "๐ป /wallpaper_cartoon - favorite cartoons ๐\n" +
// "๐ /wallpaper_classic\n" +
// "๐ป /wallpaper_scenery - Natural\n" +
// "๐บ /wallpaper_movies\n" +
// "๐ฎ /wallpaper_games - Gamessssss*BOOM*๐พ\n" +
// "๐ /wallpaper_sports\n" +
// "๐ /wallpaper_holiday\n" +
// "๐ /wallpaper_beauty\n\n" +
// "If you want to get more wallpapers, visit:\n" +
// "๐ http://www.like5.com/?tgbot");
// }
//}
private class WallpaperButtonsCommand : SimpleComparerCommand
{
public WallpaperButtonsCommand()
{
CompareMode = Mode.BeginsWithTextFromOriginalMessage;
HelpText = "Display buttons with /wallpaper_* commands";
Prototype = new Message(-1, "/wallpaper");
}
public override void Executed(Message message)
{
var markup = new ReplyKeyboardMarkup()
{
Keyboard = new[]
{
new [] {"/wallpaper_cartoon", "/wallpaper_classic"},
new [] {"/wallpaper_scenery", "/wallpaper_movies"},
new [] {"/wallpaper_games", "/wallpaper_sports"},
new [] {"/wallpaper_holiday", "/wallpaper_beauty"},
new [] {"/help"}
},
ResizeKeyboard = true
};
Bot.Methods.SendMessage(message.Chat, "Hello, i'm wallpaper bot.\n" +
"I'll send randow wallpapers for these commands:\n" +
"๐ป /wallpaper_cartoon - favorite cartoons ๐\n" +
"๐ /wallpaper_classic\n" +
"๐ป /wallpaper_scenery - Natural\n" +
"๐บ /wallpaper_movies\n" +
"๐ฎ /wallpaper_games - Gamessssss*BOOM*๐พ\n" +
"๐ /wallpaper_sports\n" +
"๐ /wallpaper_holiday\n" +
"๐ /wallpaper_beauty\n\n" +
"If you want to get list of wallpapers (no random), visit:\n" +
"๐ http://www.like5.com/?tgbot", false, markup);
}
}
}
}