Advertisement
Guest User

Untitled

a guest
Oct 20th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 24.36 KB | None | 0 0
  1. using Discord;
  2. using Discord.WebSocket;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using Osu;
  8. using System.Threading.Tasks;
  9. using System.Configuration;
  10. using System.Collections;
  11. using System.Globalization;
  12. using OppaiSharp;
  13. using System.Net;
  14. using System.Timers;
  15. using System.IO;
  16. using HtmlAgilityPack;
  17. using System.Text.RegularExpressions;
  18.  
  19. namespace AOB_Console
  20. {
  21. public class Program
  22. {
  23. public static void Main(string[] args)
  24. => new Program().MainAsync().GetAwaiter().GetResult();
  25.  
  26. public Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location);
  27. public Osu.Api osuClient = new Osu.Api("fea67188efcce072438d4082cc530d149905504c");
  28. public DiscordSocketClient client;
  29.  
  30. public async Task MainAsync()
  31. {
  32. //Discord Client
  33. client = new DiscordSocketClient(new DiscordSocketConfig
  34. {
  35. LogLevel = LogSeverity.Verbose
  36. });
  37. client.Log += Log;
  38. client.MessageReceived += MessageReceived;
  39.  
  40. //configure timer
  41. Timer playCheckTimer = new Timer(1000 * 60);
  42. playCheckTimer.AutoReset = true;
  43. playCheckTimer.Enabled = true;
  44. playCheckTimer.Start();
  45. playCheckTimer.Elapsed += PlayCheckTimer_Elapsed;
  46.  
  47. string token = "";
  48. await client.LoginAsync(TokenType.Bot, token);
  49. await client.StartAsync();
  50. checkForNewPlays(client);
  51. //Logged in till program closed
  52. await Task.Delay(-1);
  53. }
  54.  
  55. private void PlayCheckTimer_Elapsed(object sender, ElapsedEventArgs e)
  56. {
  57. //Here we will call to check to see if anyone from the user DB has gotten any new plays
  58. checkForNewPlays(client);
  59. }
  60.  
  61. public async void checkForNewPlays(DiscordSocketClient client, IChannel channel = null)
  62. {
  63. DateTime timeNowSaved = DateTime.UtcNow;
  64. timeNowSaved.AddSeconds(-35);
  65.  
  66. foreach (string user in ConfigurationManager.AppSettings)
  67. {
  68. foreach (string value in ConfigurationManager.AppSettings.GetValues(user))
  69. {
  70. if (user != "osuChannel")
  71. {
  72.  
  73.  
  74. Console.WriteLine("OSUID: " + value);
  75. var url = "https://osu.ppy.sh/pages/include/profile-leader.php?u=" + value + " &m=0&pp=0";
  76. var web = new HtmlWeb();
  77. var doc = web.Load(url);
  78. string beatmapId = "";
  79. foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//time[@class='timeago']"))
  80. {
  81.  
  82. foreach (HtmlNode beatmapLink in node.ParentNode.ParentNode.SelectNodes("//a"))
  83. {
  84.  
  85. if (beatmapLink.Attributes["href"].Value.Contains("/web/") || beatmapLink.Attributes["href"].Value.Contains("wiki"))
  86. {
  87.  
  88. }
  89. else
  90. {
  91. beatmapId = beatmapLink.Attributes["href"].Value;
  92. }
  93.  
  94. //Console.WriteLine(beatmapId);
  95. }
  96.  
  97. string newdatetime = Regex.Replace(node.Attributes["datetime"].Value, "[^0-9.+-:]", " ");
  98. DateTime playTime = DateTime.ParseExact(newdatetime, "yyyy-MM-dd HH:mm:ss ", CultureInfo.InvariantCulture);
  99. TimeSpan i = timeNowSaved.Subtract(playTime);
  100. double timeSince = i.TotalDays * 24 * 60 * 60;
  101. if (timeSince < 35)
  102. {
  103. Console.WriteLine("!!!!!!!!!!!! NEW PLAY !!!!!!!!!!!!!!!!");
  104. if (ConfigurationManager.AppSettings["osuChannel"] != null)
  105. {
  106.  
  107. ulong cid = Convert.ToUInt64(ConfigurationManager.AppSettings["osuChannel"]);
  108. IMessageChannel msg = client.GetChannel(cid) as IMessageChannel;
  109. await msg.SendMessageAsync("");
  110. var osuuser = await osuClient.GetUserAsync(value);
  111. var getscore = await osuClient.GetScoresAsync(Convert.ToInt64(beatmapId), u: value);
  112. var x = await osuClient.GetBeatmapsAsync(b: Convert.ToInt64(beatmapId));
  113. Osu.Beatmap bm = null;
  114. foreach (Osu.Beatmap beatmap in x)
  115. {
  116. bm = beatmap;
  117. }
  118.  
  119. foreach (Osu.Scores playerScore in getscore)
  120. {
  121. long aa = Convert.ToInt64(beatmapId);
  122. await embedForPlay(playerScore, bm, Convert.ToInt64(value));
  123. }
  124. }
  125. else
  126. {
  127. //no channel set
  128. }
  129.  
  130. }
  131.  
  132. }
  133. }
  134. }
  135. }
  136. }
  137.  
  138. private async Task MessageReceived(SocketMessage message)
  139. {
  140. Console.WriteLine("Message received: " + message.Content);
  141. string input = message.Content.ToLower();
  142. switch (input.Split(' ').First())
  143. {
  144. //Usage: .rank <username> OR .rank (with account link)
  145. //Returns Raw PP & Global rank for the given player/user
  146. case ".rank":
  147. await GetPP(message);
  148. break;
  149.  
  150. //Usage:
  151. case ".recent":
  152. await GetRecent(message);
  153. break;
  154.  
  155. //Usage:
  156. case ".setuser":
  157. await SetUser(message);
  158. break;
  159.  
  160. case ".setchannel":
  161. await SetChannel(message);
  162. break;
  163.  
  164.  
  165. }
  166. }
  167.  
  168. private async Task SetChannel(SocketMessage message)
  169. {
  170. var channel = message.Channel.Id;
  171.  
  172. if (ConfigurationManager.AppSettings["osuChannel"] != null)
  173. {
  174. config.AppSettings.Settings.Remove("osuChannel");
  175. config.AppSettings.Settings.Add("osuChannel", channel.ToString());
  176. ConfigurationManager.RefreshSection("appSettings");
  177. await message.Channel.SendMessageAsync("Channel updated!");
  178. }
  179. else
  180. {
  181. config.AppSettings.Settings.Add("osuChannel", channel.ToString());
  182. ConfigurationManager.RefreshSection("appSettings");
  183. await message.Channel.SendMessageAsync("Channel added! " + channel.ToString());
  184. }
  185. config.Save(ConfigurationSaveMode.Minimal);
  186. ConfigurationManager.RefreshSection("appSettings");
  187. }
  188.  
  189. private async Task GetPP(SocketMessage message)
  190. {
  191. Console.WriteLine("GetPP called");
  192. if (message.Content.Length > 5)
  193. {
  194. string username = message.Content.Substring(6);
  195. var user = await osuClient.GetUserAsync(username);
  196. string ppraw = user.PPRaw.ToString();
  197. string userrank = user.PPRank.ToString();
  198. await message.Channel.SendMessageAsync("RawPP: " + ppraw + "\r\nGlobal Rank: " + userrank);
  199. }
  200.  
  201. else if (ConfigurationManager.AppSettings[message.Author.Id.ToString()] != null)
  202. {
  203. //User has set their osu username
  204. int idint = Convert.ToInt32(GetOSUID(message.Author.Id.ToString()));
  205. var userWithID = await osuClient.GetUserAsync(idint);
  206. string pprawID = userWithID.PPRaw.ToString();
  207. string pprankID = userWithID.PPRank.ToString();
  208.  
  209. await message.Channel.SendMessageAsync("RawPPID: " + pprawID + "\r\nGlobal Rank with ID: " + pprankID);
  210. }
  211. else
  212. {
  213. await message.Channel.SendMessageAsync("No username set! Please use .setuser <osu!username>");
  214. }
  215.  
  216.  
  217. }
  218.  
  219. private async Task SetUser(SocketMessage message)
  220. {
  221. string DiscordID = message.Author.Id.ToString();
  222. string OSUname = message.Content.Substring(9);
  223. var user = await osuClient.GetUserAsync(OSUname);
  224.  
  225. if (ConfigurationManager.AppSettings[DiscordID] != null)
  226. {
  227. //Key Already exists so overwrite the ENTIRE value
  228. config.AppSettings.Settings.Remove(DiscordID);
  229. config.AppSettings.Settings.Add(DiscordID, user.UserId.ToString());
  230. ConfigurationManager.RefreshSection("appSettings");
  231. await message.Channel.SendMessageAsync("Username updated!");
  232. }
  233. else
  234. {
  235. //Key doesn't exist so add a new entry
  236. config.AppSettings.Settings.Add(DiscordID, user.UserId.ToString());
  237. await message.Channel.SendMessageAsync("Username has been set!");
  238. }
  239. config.Save(ConfigurationSaveMode.Minimal);
  240. ConfigurationManager.RefreshSection("appSettings");
  241.  
  242. }
  243.  
  244. public static string GetOSUID(String DiscordID)
  245. {
  246. if (ConfigurationManager.AppSettings[DiscordID] != null)
  247. {
  248. //Yes key exists
  249. return ConfigurationManager.AppSettings[DiscordID];
  250. }
  251. else
  252. {
  253. return null;
  254. }
  255. }
  256.  
  257. public static string CalcAcc(int? c300, int? c100, int? c50, int? cM)
  258. {
  259. double? accuracy;
  260. int? line1;
  261. line1 = 50 * c50 + 100 * c100 + 300 * c300;
  262. accuracy = line1 * 100 / ((double)300 * (cM + c50 + c100 + c300));
  263. return Math.Round((double)accuracy, 2).ToString("#.00", CultureInfo.InvariantCulture) + "%";
  264. }
  265.  
  266. public static string RankUrl(string rank)
  267. {
  268. switch (rank)
  269. {
  270. case "F":
  271. return "https://osu.ppy.sh/images/badges/score-ranks/Score-F-Small-60.png";
  272. break;
  273. case "A":
  274. return "https://osu.ppy.sh/images/badges/score-ranks/Score-A-Small-60.png";
  275. break;
  276. case "B":
  277. return "https://osu.ppy.sh/images/badges/score-ranks/Score-B-Small-60.png";
  278. break;
  279. case "C":
  280. return "https://osu.ppy.sh/images/badges/score-ranks/Score-C-Small-60.png";
  281. break;
  282. case "S":
  283. return "https://osu.ppy.sh/images/badges/score-ranks/Score-S-Small-60.png";
  284. break;
  285. case "X":
  286. return "https://osu.ppy.sh/images/badges/score-ranks/Score-SS-Small-60.png";
  287. break;
  288. case "XH":
  289. return "https://osu.ppy.sh/images/badges/score-ranks/Score-SPlus-Small-60.png";
  290. break;
  291. case "SH":
  292. return "https://osu.ppy.sh/images/badges/score-ranks/Score-SSPlus-Small-60.png";
  293. break;
  294. }
  295.  
  296.  
  297. return null;
  298. }
  299.  
  300. public static List<string> PPCalc(string beatmapurl, Scores score)
  301. {
  302. List<string> ppinfo = new List<string>();
  303. // ppinfo format //
  304. // 0 - diff Total //
  305. // 1 - pp //
  306. // ppinfo format //
  307.  
  308.  
  309. //create a StreamReader for your beatmap
  310. byte[] data = new WebClient().DownloadData(beatmapurl);
  311. var stream = new MemoryStream(data, false);
  312. var reader = new StreamReader(stream);
  313.  
  314. //read a beatmap
  315. var beatmap = OppaiSharp.Beatmap.Read(reader);
  316.  
  317. OppaiSharp.Mods enabledMods = OppaiSharp.Mods.NoMod;
  318. foreach (string modEnabled in modsnames(score))
  319. {
  320. switch (modEnabled)
  321. {
  322. case "None":
  323. enabledMods |= OppaiSharp.Mods.NoMod;
  324. break;
  325. case "NoFail":
  326. enabledMods |= OppaiSharp.Mods.NoFail;
  327. break;
  328. case "Easy":
  329. enabledMods |= OppaiSharp.Mods.Easy;
  330. break;
  331. case "TouchDevice":
  332. enabledMods |= OppaiSharp.Mods.TouchDevice;
  333. break;
  334. case "Hidden":
  335. enabledMods |= OppaiSharp.Mods.Hidden;
  336. break;
  337. case "Hardrock":
  338. enabledMods |= OppaiSharp.Mods.Hardrock;
  339. break;
  340. case "SuddenDeath":
  341. break;
  342. case "DoubleTime":
  343. enabledMods |= OppaiSharp.Mods.DoubleTime;
  344. break;
  345. case "Relax":
  346.  
  347. break;
  348. case "HalfTime":
  349. enabledMods |= OppaiSharp.Mods.HalfTime;
  350. break;
  351. case "Nightcore":
  352. enabledMods |= OppaiSharp.Mods.Nightcore;
  353. break;
  354. case "Flashlight":
  355. enabledMods |= OppaiSharp.Mods.Flashlight;
  356. break;
  357. case "Autoplay":
  358.  
  359. break;
  360. case "SpunOut":
  361. enabledMods |= OppaiSharp.Mods.SpunOut;
  362. break;
  363. case "Relax2":
  364. break;
  365. case "Perfect":
  366. break;
  367. }
  368. }
  369. var diff = new DiffCalc().Calc(beatmap, enabledMods);
  370. Console.WriteLine(string.Format("Star rating: {0:F2} (aim stars: {1:F2}, speed stars: {2:F2})", diff.Total, diff.Aim, diff.Speed));
  371. ppinfo.Add(diff.Total.ToString("#.00", CultureInfo.InvariantCulture));
  372. var pp = new PPv2(new PPv2Parameters(beatmap, diff, c100: (int)score.Count100, c300: (int)score.Count300, c50: (int)score.Count50, cMiss: (int)score.CountMiss, combo: (int)score.MaxCombo, mods: enabledMods));
  373. ppinfo.Add(pp.Total.ToString("#.00", CultureInfo.InvariantCulture));
  374. return ppinfo;
  375. }
  376.  
  377. public static List<string> modsnames(Scores score)
  378. {
  379. int singleMod;
  380. string mods = score.EnabledMods.ToString();
  381. List<string> enabledModsNames = new List<string>();
  382. if (mods.All(char.IsDigit))
  383. {
  384. string binary = Convert.ToString(Convert.ToInt32(mods, 10), 2);
  385. int i = 0;
  386. double pos = 0;
  387. double value = 0;
  388. double modValue = 0;
  389. List<string> enabledModsNumeric = new List<string>();
  390.  
  391.  
  392. while ((i = binary.IndexOf('1', i)) != -1)
  393. {
  394. pos = binary.Length - binary.Substring(i).Length;
  395. pos = +binary.Substring(i).Length - 1;
  396. modValue = Math.Pow(2, pos);
  397. value += Math.Pow(2, pos);
  398. enabledModsNumeric.Add(modValue.ToString());
  399. i++;
  400. }
  401. Console.WriteLine("value:" + value + "mods value: " + mods.ToString());
  402. foreach (string enbldMods in enabledModsNumeric)
  403. {
  404. switch (enbldMods)
  405. {
  406. case "1":
  407. Console.WriteLine("NoFail");
  408. enabledModsNames.Add("NoFail");
  409. break;
  410. case "2":
  411. Console.WriteLine("Easy");
  412. enabledModsNames.Add("Easy");
  413. break;
  414. case "4":
  415. Console.WriteLine("TouchDevice");
  416. enabledModsNames.Add("TouchDevice");
  417. break;
  418. case "8":
  419. Console.WriteLine("Hidden");
  420. enabledModsNames.Add("Hidden");
  421. break;
  422. case "16":
  423. Console.WriteLine("Hardrock");
  424. enabledModsNames.Add("Hardrock");
  425. break;
  426. case "32":
  427. Console.WriteLine("SuddenDeath");
  428. enabledModsNames.Add("SuddenDeath");
  429. break;
  430. case "64":
  431. Console.WriteLine("Double Time");
  432. enabledModsNames.Add("DoubleTime");
  433. break;
  434. case "128":
  435. Console.WriteLine("Relax");
  436. enabledModsNames.Add("Relax");
  437. break;
  438. case "256":
  439. Console.WriteLine("HalfTime");
  440. enabledModsNames.Add("HalfTime");
  441. break;
  442. case "512":
  443. Console.WriteLine("Nightcore");
  444. enabledModsNames.Add("Nightcore");
  445. break;
  446. case "1024":
  447. Console.WriteLine("Flashlight");
  448. enabledModsNames.Add("Flashlight");
  449. break;
  450. case "2048":
  451. Console.WriteLine("Autoplay");
  452. enabledModsNames.Add("Autoplay");
  453. break;
  454. case "4096":
  455. Console.WriteLine("SpunOut");
  456. enabledModsNames.Add("SpunOut");
  457. break;
  458. case "8192":
  459. Console.WriteLine("Relax2");
  460. enabledModsNames.Add("Relax2");
  461. break;
  462. case "16384":
  463. Console.WriteLine("Perfect");
  464. enabledModsNames.Add("Perfect");
  465. break;
  466. }
  467. }
  468. }
  469. else
  470. {
  471. //One mod, is a string
  472. switch (mods)
  473. {
  474. case "None":
  475. enabledModsNames.Add("None");
  476. break;
  477. case "NoFail":
  478. enabledModsNames.Add("NoFail");
  479. break;
  480. case "Easy":
  481. enabledModsNames.Add("Easy");
  482. break;
  483. case "TouchDevice":
  484. enabledModsNames.Add("TouchDevice");
  485. break;
  486. case "Hidden":
  487. enabledModsNames.Add("Hidden");
  488. break;
  489. case "Hardrock":
  490. enabledModsNames.Add("Hardrock");
  491. break;
  492. case "SuddenDeath":
  493. enabledModsNames.Add("SuddenDeath");
  494. break;
  495. case "DoubleTime":
  496. enabledModsNames.Add("DoubleTime");
  497. break;
  498. case "Relax":
  499. enabledModsNames.Add("Relax");
  500. break;
  501. case "HalfTime":
  502. enabledModsNames.Add("Half Time");
  503. break;
  504. case "Nightcore":
  505. enabledModsNames.Add("Nightcore");
  506. break;
  507. case "Flashlight":
  508. enabledModsNames.Add("Flashlight");
  509. break;
  510. case "Autoplay":
  511. enabledModsNames.Add("Autoplay");
  512. break;
  513. case "SpunOut":
  514. enabledModsNames.Add("SpunOut");
  515. break;
  516. case "Relax2":
  517. enabledModsNames.Add("Relax2");
  518. break;
  519. case "Perfect":
  520. enabledModsNames.Add("Perfect");
  521. break;
  522. }
  523. }
  524. return enabledModsNames;
  525. }
  526.  
  527. private async Task embedForPlay(Scores scores, Osu.Beatmap beatmap, long osuuserid)
  528. {
  529. EmbedBuilder embedBuilder = new EmbedBuilder();
  530. embedBuilder.ImageUrl = "https://assets.ppy.sh/beatmaps/" + beatmap.BeatmapSetId + "/covers/cover.jpg";
  531. // embedBuilder.Title = "Recent plays for " + message.Author.ToString();
  532. embedBuilder.ThumbnailUrl = RankUrl(scores.Rank);
  533. embedBuilder.AddField("Song", beatmap.Artist + " " + beatmap.Title + " [" + beatmap.Version + "]" + "//" + beatmap.Creator);
  534. embedBuilder.AddField("Mods: ", string.Join(" ", modsnames(scores)));
  535. embedBuilder.AddField("Star Diff: ", PPCalc("https://osu.ppy.sh/osu/" + scores.BeatmapId, scores)[0]);
  536. embedBuilder.AddField("Max Combo", scores.MaxCombo);
  537. embedBuilder.AddField("Accuracy: ", CalcAcc(scores.Count300, scores.Count100, scores.Count50, scores.CountMiss));
  538. embedBuilder.AddField("Score", scores.Score);
  539. string ppforplay = PPCalc("https://osu.ppy.sh/osu/" + scores.BeatmapId, scores)[1];
  540. string formatedPP = string.Format("{0:0.00}", ppforplay);
  541. embedBuilder.AddField("PP", formatedPP);
  542. embedBuilder.Color = Color.Purple;
  543. ulong cid = Convert.ToUInt64(ConfigurationManager.AppSettings["osuChannel"]);
  544. IMessageChannel msg = client.GetChannel(cid) as IMessageChannel;
  545. await msg.SendMessageAsync("", embed: embedBuilder.Build());
  546. }
  547.  
  548. private async Task GetRecent(SocketMessage message)
  549. {
  550. EmbedBuilder embedBuilder = new EmbedBuilder();
  551.  
  552. try
  553. {
  554. int idint = Convert.ToInt32(GetOSUID(message.Author.Id.ToString()));
  555. var userRecent = await osuClient.GetUserRecentAsync(idint, limit: 1);
  556. foreach (Osu.Scores scores in userRecent){
  557.  
  558. await osuClient.GetBeatmapsAsync(b: scores.BeatmapId, limit: 1);
  559. var beatmaps = await osuClient.GetBeatmapsAsync(b: scores.BeatmapId, limit: 1);
  560.  
  561. foreach (Osu.Beatmap recentScoreOnMap in beatmaps)
  562. {
  563. await embedForPlay(scores, recentScoreOnMap, idint);
  564. }
  565.  
  566. }
  567. }
  568. catch (Exception e)
  569. {
  570. await message.Channel.SendMessageAsync("Error getting recent! Exception: `" + e + "`");
  571. }
  572. }
  573.  
  574. private Task Log(LogMessage msg)
  575. {
  576. Console.WriteLine(msg.ToString());
  577. return Task.CompletedTask;
  578. }
  579.  
  580.  
  581. }
  582. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement