Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using Discord;
- using Discord.WebSocket;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Osu;
- using System.Threading.Tasks;
- using System.Configuration;
- using System.Collections;
- using System.Globalization;
- using OppaiSharp;
- using System.Net;
- using System.Timers;
- using System.IO;
- using HtmlAgilityPack;
- using System.Text.RegularExpressions;
- namespace AOB_Console
- {
- public class Program
- {
- public static void Main(string[] args)
- => new Program().MainAsync().GetAwaiter().GetResult();
- public Configuration config = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location);
- public Osu.Api osuClient = new Osu.Api("fea67188efcce072438d4082cc530d149905504c");
- public DiscordSocketClient client;
- public async Task MainAsync()
- {
- //Discord Client
- client = new DiscordSocketClient(new DiscordSocketConfig
- {
- LogLevel = LogSeverity.Verbose
- });
- client.Log += Log;
- client.MessageReceived += MessageReceived;
- //configure timer
- Timer playCheckTimer = new Timer(1000 * 60);
- playCheckTimer.AutoReset = true;
- playCheckTimer.Enabled = true;
- playCheckTimer.Start();
- playCheckTimer.Elapsed += PlayCheckTimer_Elapsed;
- string token = "";
- await client.LoginAsync(TokenType.Bot, token);
- await client.StartAsync();
- checkForNewPlays(client);
- //Logged in till program closed
- await Task.Delay(-1);
- }
- private void PlayCheckTimer_Elapsed(object sender, ElapsedEventArgs e)
- {
- //Here we will call to check to see if anyone from the user DB has gotten any new plays
- checkForNewPlays(client);
- }
- public async void checkForNewPlays(DiscordSocketClient client, IChannel channel = null)
- {
- DateTime timeNowSaved = DateTime.UtcNow;
- timeNowSaved.AddSeconds(-35);
- foreach (string user in ConfigurationManager.AppSettings)
- {
- foreach (string value in ConfigurationManager.AppSettings.GetValues(user))
- {
- if (user != "osuChannel")
- {
- Console.WriteLine("OSUID: " + value);
- var url = "https://osu.ppy.sh/pages/include/profile-leader.php?u=" + value + " &m=0&pp=0";
- var web = new HtmlWeb();
- var doc = web.Load(url);
- string beatmapId = "";
- foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//time[@class='timeago']"))
- {
- foreach (HtmlNode beatmapLink in node.ParentNode.ParentNode.SelectNodes("//a"))
- {
- if (beatmapLink.Attributes["href"].Value.Contains("/web/") || beatmapLink.Attributes["href"].Value.Contains("wiki"))
- {
- }
- else
- {
- beatmapId = beatmapLink.Attributes["href"].Value;
- }
- //Console.WriteLine(beatmapId);
- }
- string newdatetime = Regex.Replace(node.Attributes["datetime"].Value, "[^0-9.+-:]", " ");
- DateTime playTime = DateTime.ParseExact(newdatetime, "yyyy-MM-dd HH:mm:ss ", CultureInfo.InvariantCulture);
- TimeSpan i = timeNowSaved.Subtract(playTime);
- double timeSince = i.TotalDays * 24 * 60 * 60;
- if (timeSince < 35)
- {
- Console.WriteLine("!!!!!!!!!!!! NEW PLAY !!!!!!!!!!!!!!!!");
- if (ConfigurationManager.AppSettings["osuChannel"] != null)
- {
- ulong cid = Convert.ToUInt64(ConfigurationManager.AppSettings["osuChannel"]);
- IMessageChannel msg = client.GetChannel(cid) as IMessageChannel;
- await msg.SendMessageAsync("");
- var osuuser = await osuClient.GetUserAsync(value);
- var getscore = await osuClient.GetScoresAsync(Convert.ToInt64(beatmapId), u: value);
- var x = await osuClient.GetBeatmapsAsync(b: Convert.ToInt64(beatmapId));
- Osu.Beatmap bm = null;
- foreach (Osu.Beatmap beatmap in x)
- {
- bm = beatmap;
- }
- foreach (Osu.Scores playerScore in getscore)
- {
- long aa = Convert.ToInt64(beatmapId);
- await embedForPlay(playerScore, bm, Convert.ToInt64(value));
- }
- }
- else
- {
- //no channel set
- }
- }
- }
- }
- }
- }
- }
- private async Task MessageReceived(SocketMessage message)
- {
- Console.WriteLine("Message received: " + message.Content);
- string input = message.Content.ToLower();
- switch (input.Split(' ').First())
- {
- //Usage: .rank <username> OR .rank (with account link)
- //Returns Raw PP & Global rank for the given player/user
- case ".rank":
- await GetPP(message);
- break;
- //Usage:
- case ".recent":
- await GetRecent(message);
- break;
- //Usage:
- case ".setuser":
- await SetUser(message);
- break;
- case ".setchannel":
- await SetChannel(message);
- break;
- }
- }
- private async Task SetChannel(SocketMessage message)
- {
- var channel = message.Channel.Id;
- if (ConfigurationManager.AppSettings["osuChannel"] != null)
- {
- config.AppSettings.Settings.Remove("osuChannel");
- config.AppSettings.Settings.Add("osuChannel", channel.ToString());
- ConfigurationManager.RefreshSection("appSettings");
- await message.Channel.SendMessageAsync("Channel updated!");
- }
- else
- {
- config.AppSettings.Settings.Add("osuChannel", channel.ToString());
- ConfigurationManager.RefreshSection("appSettings");
- await message.Channel.SendMessageAsync("Channel added! " + channel.ToString());
- }
- config.Save(ConfigurationSaveMode.Minimal);
- ConfigurationManager.RefreshSection("appSettings");
- }
- private async Task GetPP(SocketMessage message)
- {
- Console.WriteLine("GetPP called");
- if (message.Content.Length > 5)
- {
- string username = message.Content.Substring(6);
- var user = await osuClient.GetUserAsync(username);
- string ppraw = user.PPRaw.ToString();
- string userrank = user.PPRank.ToString();
- await message.Channel.SendMessageAsync("RawPP: " + ppraw + "\r\nGlobal Rank: " + userrank);
- }
- else if (ConfigurationManager.AppSettings[message.Author.Id.ToString()] != null)
- {
- //User has set their osu username
- int idint = Convert.ToInt32(GetOSUID(message.Author.Id.ToString()));
- var userWithID = await osuClient.GetUserAsync(idint);
- string pprawID = userWithID.PPRaw.ToString();
- string pprankID = userWithID.PPRank.ToString();
- await message.Channel.SendMessageAsync("RawPPID: " + pprawID + "\r\nGlobal Rank with ID: " + pprankID);
- }
- else
- {
- await message.Channel.SendMessageAsync("No username set! Please use .setuser <osu!username>");
- }
- }
- private async Task SetUser(SocketMessage message)
- {
- string DiscordID = message.Author.Id.ToString();
- string OSUname = message.Content.Substring(9);
- var user = await osuClient.GetUserAsync(OSUname);
- if (ConfigurationManager.AppSettings[DiscordID] != null)
- {
- //Key Already exists so overwrite the ENTIRE value
- config.AppSettings.Settings.Remove(DiscordID);
- config.AppSettings.Settings.Add(DiscordID, user.UserId.ToString());
- ConfigurationManager.RefreshSection("appSettings");
- await message.Channel.SendMessageAsync("Username updated!");
- }
- else
- {
- //Key doesn't exist so add a new entry
- config.AppSettings.Settings.Add(DiscordID, user.UserId.ToString());
- await message.Channel.SendMessageAsync("Username has been set!");
- }
- config.Save(ConfigurationSaveMode.Minimal);
- ConfigurationManager.RefreshSection("appSettings");
- }
- public static string GetOSUID(String DiscordID)
- {
- if (ConfigurationManager.AppSettings[DiscordID] != null)
- {
- //Yes key exists
- return ConfigurationManager.AppSettings[DiscordID];
- }
- else
- {
- return null;
- }
- }
- public static string CalcAcc(int? c300, int? c100, int? c50, int? cM)
- {
- double? accuracy;
- int? line1;
- line1 = 50 * c50 + 100 * c100 + 300 * c300;
- accuracy = line1 * 100 / ((double)300 * (cM + c50 + c100 + c300));
- return Math.Round((double)accuracy, 2).ToString("#.00", CultureInfo.InvariantCulture) + "%";
- }
- public static string RankUrl(string rank)
- {
- switch (rank)
- {
- case "F":
- return "https://osu.ppy.sh/images/badges/score-ranks/Score-F-Small-60.png";
- break;
- case "A":
- return "https://osu.ppy.sh/images/badges/score-ranks/Score-A-Small-60.png";
- break;
- case "B":
- return "https://osu.ppy.sh/images/badges/score-ranks/Score-B-Small-60.png";
- break;
- case "C":
- return "https://osu.ppy.sh/images/badges/score-ranks/Score-C-Small-60.png";
- break;
- case "S":
- return "https://osu.ppy.sh/images/badges/score-ranks/Score-S-Small-60.png";
- break;
- case "X":
- return "https://osu.ppy.sh/images/badges/score-ranks/Score-SS-Small-60.png";
- break;
- case "XH":
- return "https://osu.ppy.sh/images/badges/score-ranks/Score-SPlus-Small-60.png";
- break;
- case "SH":
- return "https://osu.ppy.sh/images/badges/score-ranks/Score-SSPlus-Small-60.png";
- break;
- }
- return null;
- }
- public static List<string> PPCalc(string beatmapurl, Scores score)
- {
- List<string> ppinfo = new List<string>();
- // ppinfo format //
- // 0 - diff Total //
- // 1 - pp //
- // ppinfo format //
- //create a StreamReader for your beatmap
- byte[] data = new WebClient().DownloadData(beatmapurl);
- var stream = new MemoryStream(data, false);
- var reader = new StreamReader(stream);
- //read a beatmap
- var beatmap = OppaiSharp.Beatmap.Read(reader);
- OppaiSharp.Mods enabledMods = OppaiSharp.Mods.NoMod;
- foreach (string modEnabled in modsnames(score))
- {
- switch (modEnabled)
- {
- case "None":
- enabledMods |= OppaiSharp.Mods.NoMod;
- break;
- case "NoFail":
- enabledMods |= OppaiSharp.Mods.NoFail;
- break;
- case "Easy":
- enabledMods |= OppaiSharp.Mods.Easy;
- break;
- case "TouchDevice":
- enabledMods |= OppaiSharp.Mods.TouchDevice;
- break;
- case "Hidden":
- enabledMods |= OppaiSharp.Mods.Hidden;
- break;
- case "Hardrock":
- enabledMods |= OppaiSharp.Mods.Hardrock;
- break;
- case "SuddenDeath":
- break;
- case "DoubleTime":
- enabledMods |= OppaiSharp.Mods.DoubleTime;
- break;
- case "Relax":
- break;
- case "HalfTime":
- enabledMods |= OppaiSharp.Mods.HalfTime;
- break;
- case "Nightcore":
- enabledMods |= OppaiSharp.Mods.Nightcore;
- break;
- case "Flashlight":
- enabledMods |= OppaiSharp.Mods.Flashlight;
- break;
- case "Autoplay":
- break;
- case "SpunOut":
- enabledMods |= OppaiSharp.Mods.SpunOut;
- break;
- case "Relax2":
- break;
- case "Perfect":
- break;
- }
- }
- var diff = new DiffCalc().Calc(beatmap, enabledMods);
- Console.WriteLine(string.Format("Star rating: {0:F2} (aim stars: {1:F2}, speed stars: {2:F2})", diff.Total, diff.Aim, diff.Speed));
- ppinfo.Add(diff.Total.ToString("#.00", CultureInfo.InvariantCulture));
- 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));
- ppinfo.Add(pp.Total.ToString("#.00", CultureInfo.InvariantCulture));
- return ppinfo;
- }
- public static List<string> modsnames(Scores score)
- {
- int singleMod;
- string mods = score.EnabledMods.ToString();
- List<string> enabledModsNames = new List<string>();
- if (mods.All(char.IsDigit))
- {
- string binary = Convert.ToString(Convert.ToInt32(mods, 10), 2);
- int i = 0;
- double pos = 0;
- double value = 0;
- double modValue = 0;
- List<string> enabledModsNumeric = new List<string>();
- while ((i = binary.IndexOf('1', i)) != -1)
- {
- pos = binary.Length - binary.Substring(i).Length;
- pos = +binary.Substring(i).Length - 1;
- modValue = Math.Pow(2, pos);
- value += Math.Pow(2, pos);
- enabledModsNumeric.Add(modValue.ToString());
- i++;
- }
- Console.WriteLine("value:" + value + "mods value: " + mods.ToString());
- foreach (string enbldMods in enabledModsNumeric)
- {
- switch (enbldMods)
- {
- case "1":
- Console.WriteLine("NoFail");
- enabledModsNames.Add("NoFail");
- break;
- case "2":
- Console.WriteLine("Easy");
- enabledModsNames.Add("Easy");
- break;
- case "4":
- Console.WriteLine("TouchDevice");
- enabledModsNames.Add("TouchDevice");
- break;
- case "8":
- Console.WriteLine("Hidden");
- enabledModsNames.Add("Hidden");
- break;
- case "16":
- Console.WriteLine("Hardrock");
- enabledModsNames.Add("Hardrock");
- break;
- case "32":
- Console.WriteLine("SuddenDeath");
- enabledModsNames.Add("SuddenDeath");
- break;
- case "64":
- Console.WriteLine("Double Time");
- enabledModsNames.Add("DoubleTime");
- break;
- case "128":
- Console.WriteLine("Relax");
- enabledModsNames.Add("Relax");
- break;
- case "256":
- Console.WriteLine("HalfTime");
- enabledModsNames.Add("HalfTime");
- break;
- case "512":
- Console.WriteLine("Nightcore");
- enabledModsNames.Add("Nightcore");
- break;
- case "1024":
- Console.WriteLine("Flashlight");
- enabledModsNames.Add("Flashlight");
- break;
- case "2048":
- Console.WriteLine("Autoplay");
- enabledModsNames.Add("Autoplay");
- break;
- case "4096":
- Console.WriteLine("SpunOut");
- enabledModsNames.Add("SpunOut");
- break;
- case "8192":
- Console.WriteLine("Relax2");
- enabledModsNames.Add("Relax2");
- break;
- case "16384":
- Console.WriteLine("Perfect");
- enabledModsNames.Add("Perfect");
- break;
- }
- }
- }
- else
- {
- //One mod, is a string
- switch (mods)
- {
- case "None":
- enabledModsNames.Add("None");
- break;
- case "NoFail":
- enabledModsNames.Add("NoFail");
- break;
- case "Easy":
- enabledModsNames.Add("Easy");
- break;
- case "TouchDevice":
- enabledModsNames.Add("TouchDevice");
- break;
- case "Hidden":
- enabledModsNames.Add("Hidden");
- break;
- case "Hardrock":
- enabledModsNames.Add("Hardrock");
- break;
- case "SuddenDeath":
- enabledModsNames.Add("SuddenDeath");
- break;
- case "DoubleTime":
- enabledModsNames.Add("DoubleTime");
- break;
- case "Relax":
- enabledModsNames.Add("Relax");
- break;
- case "HalfTime":
- enabledModsNames.Add("Half Time");
- break;
- case "Nightcore":
- enabledModsNames.Add("Nightcore");
- break;
- case "Flashlight":
- enabledModsNames.Add("Flashlight");
- break;
- case "Autoplay":
- enabledModsNames.Add("Autoplay");
- break;
- case "SpunOut":
- enabledModsNames.Add("SpunOut");
- break;
- case "Relax2":
- enabledModsNames.Add("Relax2");
- break;
- case "Perfect":
- enabledModsNames.Add("Perfect");
- break;
- }
- }
- return enabledModsNames;
- }
- private async Task embedForPlay(Scores scores, Osu.Beatmap beatmap, long osuuserid)
- {
- EmbedBuilder embedBuilder = new EmbedBuilder();
- embedBuilder.ImageUrl = "https://assets.ppy.sh/beatmaps/" + beatmap.BeatmapSetId + "/covers/cover.jpg";
- // embedBuilder.Title = "Recent plays for " + message.Author.ToString();
- embedBuilder.ThumbnailUrl = RankUrl(scores.Rank);
- embedBuilder.AddField("Song", beatmap.Artist + " " + beatmap.Title + " [" + beatmap.Version + "]" + "//" + beatmap.Creator);
- embedBuilder.AddField("Mods: ", string.Join(" ", modsnames(scores)));
- embedBuilder.AddField("Star Diff: ", PPCalc("https://osu.ppy.sh/osu/" + scores.BeatmapId, scores)[0]);
- embedBuilder.AddField("Max Combo", scores.MaxCombo);
- embedBuilder.AddField("Accuracy: ", CalcAcc(scores.Count300, scores.Count100, scores.Count50, scores.CountMiss));
- embedBuilder.AddField("Score", scores.Score);
- string ppforplay = PPCalc("https://osu.ppy.sh/osu/" + scores.BeatmapId, scores)[1];
- string formatedPP = string.Format("{0:0.00}", ppforplay);
- embedBuilder.AddField("PP", formatedPP);
- embedBuilder.Color = Color.Purple;
- ulong cid = Convert.ToUInt64(ConfigurationManager.AppSettings["osuChannel"]);
- IMessageChannel msg = client.GetChannel(cid) as IMessageChannel;
- await msg.SendMessageAsync("", embed: embedBuilder.Build());
- }
- private async Task GetRecent(SocketMessage message)
- {
- EmbedBuilder embedBuilder = new EmbedBuilder();
- try
- {
- int idint = Convert.ToInt32(GetOSUID(message.Author.Id.ToString()));
- var userRecent = await osuClient.GetUserRecentAsync(idint, limit: 1);
- foreach (Osu.Scores scores in userRecent){
- await osuClient.GetBeatmapsAsync(b: scores.BeatmapId, limit: 1);
- var beatmaps = await osuClient.GetBeatmapsAsync(b: scores.BeatmapId, limit: 1);
- foreach (Osu.Beatmap recentScoreOnMap in beatmaps)
- {
- await embedForPlay(scores, recentScoreOnMap, idint);
- }
- }
- }
- catch (Exception e)
- {
- await message.Channel.SendMessageAsync("Error getting recent! Exception: `" + e + "`");
- }
- }
- private Task Log(LogMessage msg)
- {
- Console.WriteLine(msg.ToString());
- return Task.CompletedTask;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement