From 58c23c1ca3eb83f8b1f01d8703916bea27c18711 Mon Sep 17 00:00:00 2001 From: Marco Ruzak Date: Wed, 28 Apr 2021 00:32:49 +0300 Subject: [PATCH 1/8] smal hotfixes, nothing much --- bot/Modules/ListenCommand.cs | 10 +++--- bot/Modules/SearchCommand.cs | 8 ++--- bot/Other/MyRateLimit.cs | 2 +- bot/Service/LoggingService.cs | 33 +++++++++++++------- bot/Service/Spotify/Listen_spotify.cs | 4 +-- bot/Service/Spotify/Search_spotify.cs | 44 ++++++++++++++++++--------- bot/bot.csproj | 2 +- 7 files changed, 65 insertions(+), 38 deletions(-) diff --git a/bot/Modules/ListenCommand.cs b/bot/Modules/ListenCommand.cs index 967fae2..9ecb6ae 100644 --- a/bot/Modules/ListenCommand.cs +++ b/bot/Modules/ListenCommand.cs @@ -81,14 +81,14 @@ public async Task Listenn(float minutes,SocketUser user = null) if (activity is SpotifyGame spot) { Spotify_exists = true; - Console.WriteLine($"{d + 1} song recieved"); + //Console.WriteLine($"{d + 1} song recieved"); var tuple = spotify.Listen(spot.TrackTitle + " " + spot.Artists.First()); songData[d].popularity = tuple.Result.Item1; songData[d].genre_string = tuple.Result.Item2; songData[d].songname = spot.TrackTitle; - Console.WriteLine(spot.TrackTitle); - Console.WriteLine(songData[d].genre_string); + //Console.WriteLine(spot.TrackTitle); + //Console.WriteLine(songData[d].genre_string); d++; } } @@ -113,8 +113,8 @@ public async Task Listenn(float minutes,SocketUser user = null) string distinct_genres = ""; foreach (var data in distinct_data) { - Console.WriteLine(data.songname); - Console.WriteLine(data.genre_string); + //Console.WriteLine(data.songname); + //Console.WriteLine(data.genre_string); popularities[dd] = data.popularity; dd++; distinct_genres = distinct_genres + "+" + data.genre_string;//all genres to one string, in order to pass it to GetTopGenres(); diff --git a/bot/Modules/SearchCommand.cs b/bot/Modules/SearchCommand.cs index 7ea437e..cf2118a 100644 --- a/bot/Modules/SearchCommand.cs +++ b/bot/Modules/SearchCommand.cs @@ -10,10 +10,10 @@ namespace SpotifyBot.Modules { public class SearchCommand : ModuleBase { - private SpotifyService spotify; + private SpotifyService spotifyService; public SearchCommand(IServiceProvider serviceProvider) { - spotify = serviceProvider.GetRequiredService(); + spotifyService = serviceProvider.GetRequiredService(); } @@ -25,15 +25,15 @@ public async Task search([Remainder] string msg) Console.WriteLine("we in!"); try { - EmbedBuilder embedBuilerr = await spotify.Search(msg, Context.User); + EmbedBuilder embedBuilerr = await spotifyService.Search(msg, Context.User); await Context.Channel.SendMessageAsync("", false, embedBuilerr.Build()); + return MyCommandResult.FromSuccess(); } catch (Exception e) { Console.WriteLine("we messed up"); return MyCommandResult.FromError(e.Message); } - return MyCommandResult.FromSuccess(); } } } \ No newline at end of file diff --git a/bot/Other/MyRateLimit.cs b/bot/Other/MyRateLimit.cs index 0cde02b..d28826e 100644 --- a/bot/Other/MyRateLimit.cs +++ b/bot/Other/MyRateLimit.cs @@ -142,7 +142,7 @@ public override Task CheckPermissionsAsync( commandTimeout2.TimesInvoked -= 1; } - if (commandTimeout2.TimesInvoked >= this._invokeLimit) + if (commandTimeout2.TimesInvoked >= this._invokeLimit && (((this._invokeLimitPeriod - (utcNow - commandTimeout2.FirstInvoke) != this._invokeLimitPeriod)))) { a.ifFailed[context.User.Username][_.Name] = false; return Task.FromResult(PreconditionResult.FromError(this.ErrorMessage ?? $"Sheesh.. :eyes: this command is on cooldown for `{(this._invokeLimitPeriod - (utcNow - commandTimeout2.FirstInvoke)).ToString(@"hh\:mm\:ss")}`")); diff --git a/bot/Service/LoggingService.cs b/bot/Service/LoggingService.cs index 05d7867..01c8d00 100644 --- a/bot/Service/LoggingService.cs +++ b/bot/Service/LoggingService.cs @@ -17,17 +17,19 @@ public class LoggingService private readonly CommandService _commands; public LoggingService(IServiceProvider services) - { + { // get the services we need via DI, and assign the fields declared above to them - _client = services.GetRequiredService(); + _client = services.GetRequiredService(); _commands = services.GetRequiredService(); - _logger = services.GetRequiredService>(); //>() injecting logger to logging service??? + _logger = services + .GetRequiredService + >(); //>() injecting logger to logging service??? // hook into these events with the methods provided below _client.Ready += OnReadyAsync; _client.Log += OnLogAsync; _commands.Log += OnLogAsync; - + } // this method executes on the bot being connected/ready @@ -37,12 +39,22 @@ public Task OnReadyAsync() _logger.LogInformation($"We are on [{_client.Guilds.Count}] servers"); return Task.CompletedTask; } - + // this method switches out the severity level from Discord.Net's API, and logs appropriately - public Task OnLogAsync(LogMessage msg) + public async Task OnLogAsync(LogMessage msg) { string logText = $": {msg.Exception?.ToString() ?? msg.Message}"; + if (msg.Exception is CommandException cmdException) + { + // We can tell the user that something unexpected has happened + await cmdException.Context.Channel.SendMessageAsync("Something went catastrophically wrong!"); + + // We can also log this incident + Console.WriteLine( + $"{cmdException.Context.User} failed to execute '{cmdException.Command.Name}' in {cmdException.Context.Channel}."); + } + switch (msg.Severity.ToString()) { case "Critical": @@ -64,20 +76,19 @@ public Task OnLogAsync(LogMessage msg) { _logger.LogInformation(logText); break; - } + } case "Debug": { _logger.LogDebug(logText); break; - } + } case "Error": { _logger.LogError(logText); break; - } - } + } - return Task.CompletedTask; + } } } } \ No newline at end of file diff --git a/bot/Service/Spotify/Listen_spotify.cs b/bot/Service/Spotify/Listen_spotify.cs index e9e307d..b57e0ce 100644 --- a/bot/Service/Spotify/Listen_spotify.cs +++ b/bot/Service/Spotify/Listen_spotify.cs @@ -93,9 +93,9 @@ public string GetTopGenres(string all_genres_string) .GroupBy(w => w) .OrderByDescending(g => g.Count()); - foreach (var word in genre_list){ + /*foreach (var word in genre_list){ Console.WriteLine("{0}x {1}", word.Count(), word.Key); - } + }*/ int mm = 0; List list = new List(); diff --git a/bot/Service/Spotify/Search_spotify.cs b/bot/Service/Spotify/Search_spotify.cs index 8f8fe59..b00ba0e 100644 --- a/bot/Service/Spotify/Search_spotify.cs +++ b/bot/Service/Spotify/Search_spotify.cs @@ -4,13 +4,16 @@ using System.Threading.Tasks; using Discord; using Discord.WebSocket; +using Microsoft.Extensions.Logging; using SpotifyAPI.Web; namespace SpotifyBot.Service.Spotify { public partial class SpotifyService { + private static SocketUser user; + private SpotifyClient spotify; public async Task Search(string requestString, SocketUser socketUser) { string song_name; @@ -24,28 +27,41 @@ public async Task Search(string requestString, SocketUser socketUs //Getting tokens from our json. GetSpotifyTokens(); + try + { + //Connection of Bot client + var config = SpotifyClientConfig + .CreateDefault() + .WithAuthenticator(new ClientCredentialsAuthenticator(Bot_id, Bot_ids)); + spotify = new SpotifyClient(config); + } + catch (APIUnauthorizedException e) + { + Console.Write("problem api unathor"); + Console.Write("UNATHORIZED"+ e.Message + "with : " + e.Response?.StatusCode); + throw new ApplicationException(e.Message + "with : " + e.Response?.StatusCode); + } + - //Connection of Bot client - var config = SpotifyClientConfig.CreateDefault(); - var request = - new ClientCredentialsRequest(Bot_id, Bot_ids); - var response = await new OAuthClient(config).RequestToken(request); - var spotify = new SpotifyClient(config.WithToken(response.AccessToken)); - // --- try { - SearchRequest searchRequest = new SearchRequest(SearchRequest.Types.All, - requestString); - searchRequest.Limit = 5; - var result = await spotify.Search.Item(searchRequest); //Sending search request and obtaining data obj - EmbedBuilder embed = EmbedCreator(result, spotify); + var result = spotify.Search.Item(new SearchRequest(SearchRequest.Types.All,requestString)); //Sending search request and obtaining data obj + EmbedBuilder embed = EmbedCreator(result.Result, spotify); if (embed == null) { - throw new ArgumentException(""); + throw new ArgumentException("Embed is zero"); } + return embed; - + + } + catch (APIException e) + { + Console.Write("problem api excep"); + Console.Write("api excheption"+ e.Message + "with : " + e.Response?.StatusCode); + throw new ApplicationException(e.Message + "with : " + e.Response?.StatusCode); + } catch (Exception e) { diff --git a/bot/bot.csproj b/bot/bot.csproj index ac00212..8f8b6d4 100644 --- a/bot/bot.csproj +++ b/bot/bot.csproj @@ -18,7 +18,7 @@ - + From 4793adc5b4de9ab401674976e527f9c49d14b8fe Mon Sep 17 00:00:00 2001 From: Marco Ruzak Date: Sat, 1 May 2021 11:11:42 +0300 Subject: [PATCH 2/8] added test config file, changed gitignore --- .gitignore | 5 +++++ bot/Service/Spotify/Listen_spotify.cs | 3 ++- bot/entry.cs | 4 +++- 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index 4d9241a..e95862f 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,11 @@ bin/ #config file /bot/_config.json +/bot/t_config.json #log files /bot/logs/ + +#Solution file +TestBot_.sln + diff --git a/bot/Service/Spotify/Listen_spotify.cs b/bot/Service/Spotify/Listen_spotify.cs index b57e0ce..1b49b71 100644 --- a/bot/Service/Spotify/Listen_spotify.cs +++ b/bot/Service/Spotify/Listen_spotify.cs @@ -15,10 +15,11 @@ public partial class SpotifyService private static string Bot_ids; //secret Id private static readonly string configPath = @".\_config.json"; + private static readonly string t_configPath = @"C:\Users\Марко\OneDrive\Desktop\Discord\TestBotStuff\TestBot_\bot\t_config.json"; private static void GetSpotifyTokens() //Method to get spotify tokens { - StreamReader r = new StreamReader(configPath); + StreamReader r = new StreamReader(t_configPath); string json = r.ReadToEnd(); dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject(json); Bot_id = data.Spotify_id; diff --git a/bot/entry.cs b/bot/entry.cs index 93c7a0c..04f005b 100644 --- a/bot/entry.cs +++ b/bot/entry.cs @@ -48,6 +48,8 @@ Write out to the console and to a file private readonly string configPath = @".\_config.json"; + private readonly string t_configPath = @"C:\Users\Марко\OneDrive\Desktop\Discord\TestBotStuff\TestBot_\bot\t_config.json"; + private string bot_token; public static string invite_link; @@ -82,7 +84,7 @@ private async Task MainAsync() private string GetToken() { - StreamReader r = new StreamReader(configPath); + StreamReader r = new StreamReader(t_configPath); string json = r.ReadToEnd(); dynamic config_file = Newtonsoft.Json.JsonConvert.DeserializeObject(json); invite_link = config_file.Invite_link; From 7d5709fd48f4b2b6793ffb9310b98abb809d8c0b Mon Sep 17 00:00:00 2001 From: Marco Ruzak Date: Sat, 1 May 2021 11:13:31 +0300 Subject: [PATCH 3/8] Delete TestBot_.sln --- TestBot_.sln | 16 ---------------- 1 file changed, 16 deletions(-) delete mode 100644 TestBot_.sln diff --git a/TestBot_.sln b/TestBot_.sln deleted file mode 100644 index ca81af9..0000000 --- a/TestBot_.sln +++ /dev/null @@ -1,16 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "bot", "bot\bot.csproj", "{0E4DD6F0-CC55-451D-A373-CE717AF12B49}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {0E4DD6F0-CC55-451D-A373-CE717AF12B49}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {0E4DD6F0-CC55-451D-A373-CE717AF12B49}.Debug|Any CPU.Build.0 = Debug|Any CPU - {0E4DD6F0-CC55-451D-A373-CE717AF12B49}.Release|Any CPU.ActiveCfg = Release|Any CPU - {0E4DD6F0-CC55-451D-A373-CE717AF12B49}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection -EndGlobal From a12c331ee9a697f6c9cf1479c8b62436d2ad3f42 Mon Sep 17 00:00:00 2001 From: Marco Ruzak Date: Sat, 1 May 2021 11:18:44 +0300 Subject: [PATCH 4/8] reverted --- .gitignore | 5 ----- bot/Service/Spotify/Listen_spotify.cs | 3 +-- bot/entry.cs | 4 +--- 3 files changed, 2 insertions(+), 10 deletions(-) diff --git a/.gitignore b/.gitignore index e95862f..4d9241a 100644 --- a/.gitignore +++ b/.gitignore @@ -10,11 +10,6 @@ bin/ #config file /bot/_config.json -/bot/t_config.json #log files /bot/logs/ - -#Solution file -TestBot_.sln - diff --git a/bot/Service/Spotify/Listen_spotify.cs b/bot/Service/Spotify/Listen_spotify.cs index 1b49b71..b57e0ce 100644 --- a/bot/Service/Spotify/Listen_spotify.cs +++ b/bot/Service/Spotify/Listen_spotify.cs @@ -15,11 +15,10 @@ public partial class SpotifyService private static string Bot_ids; //secret Id private static readonly string configPath = @".\_config.json"; - private static readonly string t_configPath = @"C:\Users\Марко\OneDrive\Desktop\Discord\TestBotStuff\TestBot_\bot\t_config.json"; private static void GetSpotifyTokens() //Method to get spotify tokens { - StreamReader r = new StreamReader(t_configPath); + StreamReader r = new StreamReader(configPath); string json = r.ReadToEnd(); dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject(json); Bot_id = data.Spotify_id; diff --git a/bot/entry.cs b/bot/entry.cs index 04f005b..93c7a0c 100644 --- a/bot/entry.cs +++ b/bot/entry.cs @@ -48,8 +48,6 @@ Write out to the console and to a file private readonly string configPath = @".\_config.json"; - private readonly string t_configPath = @"C:\Users\Марко\OneDrive\Desktop\Discord\TestBotStuff\TestBot_\bot\t_config.json"; - private string bot_token; public static string invite_link; @@ -84,7 +82,7 @@ private async Task MainAsync() private string GetToken() { - StreamReader r = new StreamReader(t_configPath); + StreamReader r = new StreamReader(configPath); string json = r.ReadToEnd(); dynamic config_file = Newtonsoft.Json.JsonConvert.DeserializeObject(json); invite_link = config_file.Invite_link; From 0877b2122d881aa4e5d3f79441e59d5d0c73e428 Mon Sep 17 00:00:00 2001 From: Marco Ruzak Date: Sat, 1 May 2021 11:23:52 +0300 Subject: [PATCH 5/8] Revert "Delete TestBot_.sln" This reverts commit 7d5709fd48f4b2b6793ffb9310b98abb809d8c0b. --- TestBot_.sln | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 TestBot_.sln diff --git a/TestBot_.sln b/TestBot_.sln new file mode 100644 index 0000000..ca81af9 --- /dev/null +++ b/TestBot_.sln @@ -0,0 +1,16 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "bot", "bot\bot.csproj", "{0E4DD6F0-CC55-451D-A373-CE717AF12B49}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0E4DD6F0-CC55-451D-A373-CE717AF12B49}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0E4DD6F0-CC55-451D-A373-CE717AF12B49}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0E4DD6F0-CC55-451D-A373-CE717AF12B49}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0E4DD6F0-CC55-451D-A373-CE717AF12B49}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal From 91446a4cbe4957650cf083e97c2073934d1b1329 Mon Sep 17 00:00:00 2001 From: Marco Ruzak Date: Sat, 1 May 2021 15:41:29 +0300 Subject: [PATCH 6/8] Changed cooldown for <> _dictionary; public ListenCommand(IServiceProvider serviceProvider) { spotify = serviceProvider.GetRequiredService(); + _listenUsersList = serviceProvider.GetRequiredService(); + _dictionary= _listenUsersList._UsrDict; } /// @@ -42,7 +49,6 @@ public ListenCommand(IServiceProvider serviceProvider) /// [Command("listen", RunMode = RunMode.Async)] - [MyRatelimit(1,command_cooldown,MyMeasure.Minutes, RatelimitFlags.None)] public async Task Listenn(float minutes,SocketUser user = null) { if (user == null) @@ -50,6 +56,19 @@ public async Task Listenn(float minutes,SocketUser user = null) user = Context.User; } + DateTime utcNow = DateTime.UtcNow; + if (_dictionary.ContainsKey(user.Id)) + { + return MyCommandResult.FromError($"Shhh... :eyes: 'Listen' is already running for user {user.Mention}!\nEstimated end time : `{(_dictionary[user.Id].Item1 - (utcNow - _dictionary[user.Id].Item2) ).ToString(@"hh\:mm\:ss")}`"); + } + else + { + Console.WriteLine("adding...."); + TimeSpan span = TimeSpan.FromMinutes(minutes); // converting float minutes to timespan minutes + _dictionary.Add(user.Id, new Tuple(span, utcNow)); //filling dict + } + + Random random = new Random(); Color color = new Color(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255)); try @@ -153,16 +172,24 @@ public async Task Listenn(float minutes,SocketUser user = null) embedBuilder.AddField(genre_field); } + RemoveUser(user,_dictionary); await Context.Channel.SendMessageAsync("", false, embedBuilder.Build()); return MyCommandResult.FromSuccess(); } catch (Exception e) { + RemoveUser(user, _dictionary); return MyCommandResult.FromError($"Command aborted : {e.Message}"); } } - + + //Removes element from dict, thats all + private void RemoveUser(SocketUser user, Dictionary> _dict) + { + Console.WriteLine("deleting,,,"); + _dict.Remove(user.Id); + } } } diff --git a/bot/Other/MyRateLimit.cs b/bot/Other/MyRateLimit.cs index d28826e..4624061 100644 --- a/bot/Other/MyRateLimit.cs +++ b/bot/Other/MyRateLimit.cs @@ -6,6 +6,7 @@ using Discord.Commands; using Microsoft.Extensions.DependencyInjection; using SpotifyBot.Service; +using SpotifyBot.Service.ForCooldown; namespace SpotifyBot.Other { @@ -111,22 +112,7 @@ public override Task CheckPermissionsAsync( CommandInfo _, IServiceProvider __) { - var a = __.GetService<_CooldownFixer>(); - - //checking if this command exists - //if not we create and setup first run as unsucessful (to skip and rely on command handler next time) - if (!(a.ifFailed.ContainsKey(context.User.Username))) - { - var user_dict = new Dictionary(); - a.ifFailed.Add(context.User.Username,user_dict); - user_dict.Add(_.Name,true); - } - if (!(a.ifFailed[context.User.Username].ContainsKey(_.Name))) - { - a.ifFailed[context.User.Username].Add(_.Name,true); - - } if (this._noLimitInDMs && context.Channel is IPrivateChannel) @@ -137,19 +123,13 @@ public override Task CheckPermissionsAsync( CommandTimeout commandTimeout1; CommandTimeout commandTimeout2 = !this._invokeTracker.TryGetValue(key, out commandTimeout1) || !(utcNow - commandTimeout1.FirstInvoke < this._invokeLimitPeriod) ? new CommandTimeout(utcNow) : commandTimeout1; ++commandTimeout2.TimesInvoked; - if (a.ifFailed[context.User.Username][_.Name])//if null wont enter - { - commandTimeout2.TimesInvoked -= 1; - } if (commandTimeout2.TimesInvoked >= this._invokeLimit && (((this._invokeLimitPeriod - (utcNow - commandTimeout2.FirstInvoke) != this._invokeLimitPeriod)))) { - a.ifFailed[context.User.Username][_.Name] = false; return Task.FromResult(PreconditionResult.FromError(this.ErrorMessage ?? $"Sheesh.. :eyes: this command is on cooldown for `{(this._invokeLimitPeriod - (utcNow - commandTimeout2.FirstInvoke)).ToString(@"hh\:mm\:ss")}`")); } this._invokeTracker[key] = commandTimeout2; - a.ifFailed[context.User.Username][_.Name] = false; return Task.FromResult(PreconditionResult.FromSuccess()); } diff --git a/bot/Service/CommandHandler.cs b/bot/Service/CommandHandler.cs index 1205ea7..e4814b0 100644 --- a/bot/Service/CommandHandler.cs +++ b/bot/Service/CommandHandler.cs @@ -8,6 +8,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using SpotifyBot.Other; +using SpotifyBot.Service.ForCooldown; namespace SpotifyBot.Service @@ -51,27 +52,16 @@ public async Task OnCommandExecutedAsync(Optional command, ICommand { if (result.Error != CommandError.UnknownCommand) { - await context.Channel.SendMessageAsync(result.ErrorReason); + EmbedBuilder embed = new EmbedBuilder(); + embed.WithDescription(result.ErrorReason); + embed.Color = Color.Red; + await context.Channel.SendMessageAsync("", false, embed.Build()); } } - - - //This is run for cooldown issue. - var a = _services.GetService<_CooldownFixer>(); - - - - a.ifFailed[context.User.Username][command.Value.Name] = true; - if (a.ifFailed[context.User.Username].Count > 1000) //if thing is used by more than 1000 ppl - { - a.ifFailed[context.User.Username].Clear(); //clear - } - - var commandName = command.IsSpecified ? command.Value.Name : "A command"; if (result.Error != CommandError.UnmetPrecondition && result.Error != CommandError.UnknownCommand) //Ignore ratelimits, they will occur a lot. { diff --git a/bot/Service/ForCooldown/ListenUsersList.cs b/bot/Service/ForCooldown/ListenUsersList.cs new file mode 100644 index 0000000..bc08613 --- /dev/null +++ b/bot/Service/ForCooldown/ListenUsersList.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; + +namespace SpotifyBot.Service.ForCooldown +{ + + /// + /// This thingy checks if command "listen" is still running for specified user. + /// this will add every user's (who has program listen running) ID to list. + /// + public class ListenUsersList + { + /// + /// First Key : user.id, + /// first tuple item : Time span listen minutes, requested by user + /// second tuple item : utcNow of command start + /// + public Dictionary> _UsrDict = new Dictionary>(); + } +} \ No newline at end of file diff --git a/bot/Service/ServiceSetup.cs b/bot/Service/ServiceSetup.cs index ba1aeff..970d535 100644 --- a/bot/Service/ServiceSetup.cs +++ b/bot/Service/ServiceSetup.cs @@ -5,14 +5,14 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Serilog; +using SpotifyBot.Service.ForCooldown; namespace SpotifyBot.Service { public class service { private readonly DiscordSocketClient _client; - private _CooldownFixer _cooldownFixer = new _CooldownFixer(); - + public static ServiceProvider BuildServiceProvider() { var services = new ServiceCollection() @@ -23,7 +23,7 @@ public static ServiceProvider BuildServiceProvider() IgnoreExtraArgs = true, CaseSensitiveCommands = false, })) - .AddSingleton<_CooldownFixer>() + .AddSingleton() .AddSingleton() .AddSingleton() .AddSingleton() diff --git a/bot/Service/Spotify/InitService.cs b/bot/Service/Spotify/InitService.cs new file mode 100644 index 0000000..0bf2811 --- /dev/null +++ b/bot/Service/Spotify/InitService.cs @@ -0,0 +1,24 @@ +using System.IO; + +namespace SpotifyBot.Service.Spotify +{ + public partial class SpotifyService + { + private static string Bot_id; //Id of my spotify app + private static string Bot_ids; //secret Id + + private static readonly string configPath = @".\_config.json"; + private static readonly string t_configPath = @"C:\Users\Марко\OneDrive\Desktop\Discord\TestBotStuff\TestBot_\bot\t_config.json"; + //^ this is test config file + + private static void GetSpotifyTokens() //Method to get spotify tokens + { + StreamReader r = new StreamReader(t_configPath); + string json = r.ReadToEnd(); + dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject(json); + Bot_id = data.Spotify_id; + Bot_ids = data.Spotify_ids; + + } + } +} \ No newline at end of file diff --git a/bot/Service/Spotify/Listen_spotify.cs b/bot/Service/Spotify/Listen_spotify.cs index b57e0ce..47f578e 100644 --- a/bot/Service/Spotify/Listen_spotify.cs +++ b/bot/Service/Spotify/Listen_spotify.cs @@ -11,27 +11,14 @@ namespace SpotifyBot.Service.Spotify public partial class SpotifyService { - private static string Bot_id; //Id of my spotify app - private static string Bot_ids; //secret Id - - private static readonly string configPath = @".\_config.json"; - - private static void GetSpotifyTokens() //Method to get spotify tokens - { - StreamReader r = new StreamReader(configPath); - string json = r.ReadToEnd(); - dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject(json); - Bot_id = data.Spotify_id; - Bot_ids = data.Spotify_ids; - - } + /// -/// This method is created for command !listen. -/// Returns string with genres of songs artist and popularity score. -/// -/// -/// -/// + /// This method is created for command !listen. + /// Returns string with genres of songs artist and popularity score. + /// + /// + /// + /// public async Task> Listen(string songName) { diff --git a/bot/Service/_CooldownFixer.cs b/bot/Service/_CooldownFixer.cs deleted file mode 100644 index 43ff643..0000000 --- a/bot/Service/_CooldownFixer.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace SpotifyBot.Service -{ - /// - /// This class will be later injected in our service. - /// Created in order to close issue ---- https://github.com/mad-redhead/SpotifyBot_testbot/issues/5 --- issue context - /// - /// - public class _CooldownFixer - { - //User name - list - public Dictionary> ifFailed = new Dictionary>(); - - public _CooldownFixer() - { - ifFailed.Clear(); - } - } -} \ No newline at end of file diff --git a/bot/entry.cs b/bot/entry.cs index 93c7a0c..04f005b 100644 --- a/bot/entry.cs +++ b/bot/entry.cs @@ -48,6 +48,8 @@ Write out to the console and to a file private readonly string configPath = @".\_config.json"; + private readonly string t_configPath = @"C:\Users\Марко\OneDrive\Desktop\Discord\TestBotStuff\TestBot_\bot\t_config.json"; + private string bot_token; public static string invite_link; @@ -82,7 +84,7 @@ private async Task MainAsync() private string GetToken() { - StreamReader r = new StreamReader(configPath); + StreamReader r = new StreamReader(t_configPath); string json = r.ReadToEnd(); dynamic config_file = Newtonsoft.Json.JsonConvert.DeserializeObject(json); invite_link = config_file.Invite_link; From 94ed4bc872665d72c75f5450b90b7df81ad17e46 Mon Sep 17 00:00:00 2001 From: Marco Ruzak Date: Sat, 1 May 2021 18:39:08 +0300 Subject: [PATCH 7/8] Almost all stuff is now in embeds --- bot/Modules/ListenCommand.cs | 7 +------ bot/Other/UserErrorResponses.cs | 14 ++++++++++---- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/bot/Modules/ListenCommand.cs b/bot/Modules/ListenCommand.cs index bb069ca..4073677 100644 --- a/bot/Modules/ListenCommand.cs +++ b/bot/Modules/ListenCommand.cs @@ -24,10 +24,7 @@ private struct song_data public int popularity; public string genre_string; } - - ///Default value of minutes command !listen runs, if not overloaded with minutes parameter - private const int command_cooldown = 5; //--minutes \\\\Determines cooldown for our listen command; - + private const int wait_seconds = 30; //--seconds \\\\\Period of time we wait before checking song again private SpotifyService spotify; @@ -63,7 +60,6 @@ public async Task Listenn(float minutes,SocketUser user = null) } else { - Console.WriteLine("adding...."); TimeSpan span = TimeSpan.FromMinutes(minutes); // converting float minutes to timespan minutes _dictionary.Add(user.Id, new Tuple(span, utcNow)); //filling dict } @@ -187,7 +183,6 @@ public async Task Listenn(float minutes,SocketUser user = null) //Removes element from dict, thats all private void RemoveUser(SocketUser user, Dictionary> _dict) { - Console.WriteLine("deleting,,,"); _dict.Remove(user.Id); } } diff --git a/bot/Other/UserErrorResponses.cs b/bot/Other/UserErrorResponses.cs index 8a07ebf..8782b26 100644 --- a/bot/Other/UserErrorResponses.cs +++ b/bot/Other/UserErrorResponses.cs @@ -11,18 +11,24 @@ namespace SpotifyBot.Other public class UserErrorResponses { private const string listen_response = - "Hey, this commands input parameters are `< command, ICommandContext context) { if (command.Value.Name == "listen") { - await context.Channel.SendMessageAsync(listen_response); + EmbedBuilder embed = new EmbedBuilder(); + embed.WithDescription(listen_response); + embed.Color = Color.Gold; + await context.Channel.SendMessageAsync("", false, embed.Build()); } else if (command.Value.Name == "search") { - await context.Channel.SendMessageAsync(search_response); + EmbedBuilder embed = new EmbedBuilder(); + embed.WithDescription(search_response); + embed.Color = Color.Gold; + await context.Channel.SendMessageAsync("", false, embed.Build()); } } } From ca2f7ea7de3e4926889c9749a6e5caa0cb74049b Mon Sep 17 00:00:00 2001 From: Marco Ruzak Date: Sat, 1 May 2021 20:56:10 +0300 Subject: [PATCH 8/8] < { private struct song_data { - public string songname; - public int popularity; + public int s_popularity; + public int a_popularity; public string genre_string; } @@ -98,10 +98,9 @@ public async Task Listenn(float minutes,SocketUser user = null) Spotify_exists = true; //Console.WriteLine($"{d + 1} song recieved"); var tuple = spotify.Listen(spot.TrackTitle + " " + spot.Artists.First()); - songData[d].popularity = tuple.Result.Item1; - songData[d].genre_string = tuple.Result.Item2; - - songData[d].songname = spot.TrackTitle; + songData[d].s_popularity = tuple.Result.Item1; // <- song pop + songData[d].a_popularity = tuple.Result.Item2; // <- artist pop + songData[d].genre_string = tuple.Result.Item3; //Console.WriteLine(spot.TrackTitle); //Console.WriteLine(songData[d].genre_string); d++; @@ -123,14 +122,14 @@ public async Task Listenn(float minutes,SocketUser user = null) //Console.WriteLine("\n\n"); var distinct_data = songData.Distinct(); //Deletes similar elements. - int[] popularities = new int[distinct_data.Count()]; + float[] popularities = new float[distinct_data.Count()];// song popularities int dd = 0; string distinct_genres = ""; foreach (var data in distinct_data) { //Console.WriteLine(data.songname); //Console.WriteLine(data.genre_string); - popularities[dd] = data.popularity; + popularities[dd] = (data.s_popularity*0.25f + data.a_popularity*0.75f); dd++; distinct_genres = distinct_genres + "+" + data.genre_string;//all genres to one string, in order to pass it to GetTopGenres(); } @@ -169,7 +168,7 @@ public async Task Listenn(float minutes,SocketUser user = null) } RemoveUser(user,_dictionary); - await Context.Channel.SendMessageAsync("", false, embedBuilder.Build()); + await Context.Channel.SendMessageAsync(user.Mention, false, embedBuilder.Build()); return MyCommandResult.FromSuccess(); } catch (Exception e) diff --git a/bot/Service/Spotify/InitService.cs b/bot/Service/Spotify/InitService.cs index 0bf2811..abd48f4 100644 --- a/bot/Service/Spotify/InitService.cs +++ b/bot/Service/Spotify/InitService.cs @@ -13,7 +13,7 @@ public partial class SpotifyService private static void GetSpotifyTokens() //Method to get spotify tokens { - StreamReader r = new StreamReader(t_configPath); + StreamReader r = new StreamReader(configPath); string json = r.ReadToEnd(); dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject(json); Bot_id = data.Spotify_id; diff --git a/bot/Service/Spotify/Listen_spotify.cs b/bot/Service/Spotify/Listen_spotify.cs index 47f578e..e1f020f 100644 --- a/bot/Service/Spotify/Listen_spotify.cs +++ b/bot/Service/Spotify/Listen_spotify.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.IO; using System.Linq; using System.Threading.Tasks; using SpotifyAPI.Web; @@ -17,9 +16,13 @@ public partial class SpotifyService /// Returns string with genres of songs artist and popularity score. /// /// - /// + /// + ///first int = song popularity + /// second int = artist popularity + /// string = top 3 genres + /// /// - public async Task> Listen(string songName) + public async Task> Listen(string songName) { GetSpotifyTokens(); @@ -34,24 +37,22 @@ public async Task> Listen(string songName) try { var result = await spotify.Search.Item(new SearchRequest(SearchRequest.Types.All, songName)); //Sending search request and creating json - - string data_json = result.Tracks.ToJson(); + string data_json = result.Tracks.ToJson(); dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject(data_json); - var popularity = data.Items[0].Popularity; //популярність треку + var s_popularity = data.Items[0].Popularity; //популярність треку - //GenreSearch + //GenreSearch + artist popularity string artistid = data.Items[0].Album.Artists[0].Id.ToString(); - var artist = await spotify.Artists.Get(artistid); - var artistname = data.Items[0].Artists[0].Name.ToString(); + var artist = await spotify.Artists.Get(artistid); + int a_popularity = artist.Popularity; string genres_string = ""; foreach (var genre in artist.Genres.ToArray()) { genres_string = genres_string + "+" + genre; } - - return Tuple.Create((int)popularity,genres_string); + return Tuple.Create((int)s_popularity,(int)a_popularity,genres_string); } catch (Exception e) @@ -59,6 +60,7 @@ public async Task> Listen(string songName) throw new ArgumentException($"Song \"{songName}\" was not found."); } + } @@ -99,5 +101,6 @@ public string GetTopGenres(string all_genres_string) return topgenres; } + } } \ No newline at end of file diff --git a/bot/entry.cs b/bot/entry.cs index 04f005b..b5ae0fe 100644 --- a/bot/entry.cs +++ b/bot/entry.cs @@ -84,7 +84,7 @@ private async Task MainAsync() private string GetToken() { - StreamReader r = new StreamReader(t_configPath); + StreamReader r = new StreamReader(configPath); string json = r.ReadToEnd(); dynamic config_file = Newtonsoft.Json.JsonConvert.DeserializeObject(json); invite_link = config_file.Invite_link;