Esempio n. 1
0
        public async Task fmspotifyAsync(IUser user = null)
        {
            Data.Entities.User userSettings = await _userService.GetUserSettingsAsync(Context.User).ConfigureAwait(false);

            if (userSettings == null || userSettings.UserNameLastFM == null)
            {
                await ReplyAsync("Your LastFM username has not been set. Please set your username using the `.fmset 'username' 'embedfull/embedmini/textfull/textmini'` command.").ConfigureAwait(false);

                return;
            }

            try
            {
                PageResponse <LastTrack> tracks = await _lastFmService.GetRecentScrobblesAsync(userSettings.UserNameLastFM, 1).ConfigureAwait(false);

                LastTrack currentTrack = tracks.Content[0];

                string TrackName  = string.IsNullOrWhiteSpace(currentTrack.Name) ? null : currentTrack.Name;
                string ArtistName = string.IsNullOrWhiteSpace(currentTrack.ArtistName) ? null : currentTrack.ArtistName;
                string AlbumName  = string.IsNullOrWhiteSpace(currentTrack.AlbumName) ? null : currentTrack.AlbumName;

                string querystring = TrackName + " - " + ArtistName + " " + AlbumName;

                SearchItem item = await _spotifyService.GetSearchResultAsync(querystring).ConfigureAwait(false);

                if (item.Tracks?.Items?.Any() == true)
                {
                    FullTrack    track       = item.Tracks.Items.FirstOrDefault();
                    SimpleArtist trackArtist = track.Artists.FirstOrDefault();

                    await ReplyAsync("https://open.spotify.com/track/" + track.Id).ConfigureAwait(false);

                    this._logger.LogCommandUsed(Context.Guild?.Id, Context.Channel.Id, Context.User.Id, Context.Message.Content);
                }
                else
                {
                    await ReplyAsync("No results have been found for this track. Querystring: `" + querystring + "`").ConfigureAwait(false);
                }
            }
            catch (Exception e)
            {
                _logger.LogException(Context.Message.Content, e);
                await ReplyAsync("Unable to show Last.FM info via Spotify due to an internal error. Try setting a Last.FM name with the 'fmset' command, scrobbling something, and then use the command again.").ConfigureAwait(false);
            }
        }
Esempio n. 2
0
        public async Task fmAsync(string user = null)
        {
            User userSettings = await _userService.GetUserSettingsAsync(Context.User);

            if (userSettings?.UserNameLastFM == null)
            {
                await UsernameNotSetErrorResponseAsync();

                return;
            }
            if (user == "help")
            {
                await ReplyAsync(
                    "Usage: `.fm 'lastfm username/discord user'` \n" +
                    "You can set your default user and your display mode through the `.fmset 'username' 'embedfull/embedmini/textfull/textmini'` command.");

                this._logger.LogCommandUsed(Context.Guild?.Id, Context.Channel.Id, Context.User.Id, Context.Message.Content);
                return;
            }

            try
            {
                string lastFMUserName = userSettings.UserNameLastFM;
                bool   self           = true;

                if (user != null)
                {
                    if (await _lastFmService.LastFMUserExistsAsync(user))
                    {
                        lastFMUserName = user;
                        self           = false;
                    }
                    else if (!_guildService.CheckIfDM(Context))
                    {
                        IGuildUser guildUser = await _guildService.FindUserFromGuildAsync(Context, user);

                        if (guildUser != null)
                        {
                            User guildUserLastFM = await _userService.GetUserSettingsAsync(guildUser);

                            if (guildUserLastFM?.UserNameLastFM != null)
                            {
                                lastFMUserName = guildUserLastFM.UserNameLastFM;
                                self           = false;
                            }
                        }
                    }
                }


                PageResponse <LastTrack> tracks = await _lastFmService.GetRecentScrobblesAsync(lastFMUserName);

                if (tracks?.Any() != true)
                {
                    await NoScrobblesErrorResponseFoundAsync();

                    return;
                }

                LastResponse <LastUser> userinfo = await _lastFmService.GetUserInfoAsync(lastFMUserName);

                LastTrack currentTrack = tracks.Content[0];
                LastTrack lastTrack    = tracks.Content[1];

                const string nullText = "[undefined]";

                string trackName  = currentTrack.Name;
                string artistName = currentTrack.ArtistName;
                string albumName  = string.IsNullOrWhiteSpace(currentTrack.AlbumName) ? nullText : currentTrack.AlbumName;

                string lastTrackName       = lastTrack.Name;
                string lastTrackArtistName = lastTrack.ArtistName;
                string lastTrackAlbumName  = string.IsNullOrWhiteSpace(lastTrack.AlbumName) ? nullText : lastTrack.AlbumName;

                int playCount = userinfo.Content.Playcount;

                switch (userSettings.ChartType)
                {
                case ChartType.textmini:
                    await Context.Channel.SendMessageAsync(await _userService.GetUserTitleAsync(Context)
                                                           + "\n**Current** - "
                                                           + artistName
                                                           + " - "
                                                           + trackName
                                                           + " ["
                                                           + albumName
                                                           + "]\n<https://www.last.fm/user/"
                                                           + userSettings.UserNameLastFM
                                                           + ">\n"
                                                           + userSettings.UserNameLastFM
                                                           + "'s total scrobbles: "
                                                           + playCount.ToString("N0"));

                    break;

                case ChartType.textfull:
                    await Context.Channel.SendMessageAsync(await _userService.GetUserTitleAsync(Context)
                                                           + "\n**Current** - "
                                                           + artistName
                                                           + " - "
                                                           + trackName
                                                           + " ["
                                                           + albumName
                                                           + "]\n**Previous** - "
                                                           + lastTrackArtistName
                                                           + " - "
                                                           + lastTrackName
                                                           + " ["
                                                           + lastTrackAlbumName
                                                           + "]\n<https://www.last.fm/user/"
                                                           + userSettings.UserNameLastFM
                                                           + ">\n"
                                                           + userSettings.UserNameLastFM
                                                           + "'s total scrobbles: "
                                                           + playCount.ToString("N0"));

                    break;

                default:
                    if (!_guildService.CheckIfDM(Context))
                    {
                        GuildPermissions perms = await _guildService.CheckSufficientPermissionsAsync(Context);

                        if (!perms.EmbedLinks)
                        {
                            await ReplyAsync("Insufficient permissions, I need to the 'Embed links' permission to show you your scrobbles.");

                            break;
                        }
                    }

                    var userTitle = await _userService.GetUserTitleAsync(Context);

                    this._embed.AddField(
                        $"Current: {tracks.Content[0].Name}",
                        $"By **{tracks.Content[0].ArtistName}**" + (string.IsNullOrEmpty(tracks.Content[0].AlbumName) ? "" : $" | {tracks.Content[0].AlbumName}"));

                    if (userSettings.ChartType == ChartType.embedfull)
                    {
                        this._embedAuthor.WithName("Last tracks for " + userTitle);
                        this._embed.AddField(
                            $"Previous: {tracks.Content[1].Name}",
                            $"By **{tracks.Content[1].ArtistName}**" + (string.IsNullOrEmpty(tracks.Content[1].AlbumName) ? "" : $" | {tracks.Content[1].AlbumName}"));
                    }
                    else
                    {
                        this._embedAuthor.WithName("Last track for " + userTitle);
                    }

                    this._embed.WithTitle(tracks.Content[0].IsNowPlaying == true
                            ? "*Now playing*"
                            : $"Last scrobble {tracks.Content[0].TimePlayed?.ToString("g")}");

                    this._embedAuthor.WithIconUrl(Context.User.GetAvatarUrl());
                    this._embed.WithAuthor(this._embedAuthor);
                    this._embed.WithUrl("https://www.last.fm/user/" + lastFMUserName);

                    LastImageSet AlbumImages = await _lastFmService.GetAlbumImagesAsync(currentTrack.ArtistName, currentTrack.AlbumName);

                    if (AlbumImages?.Medium != null)
                    {
                        this._embed.WithThumbnailUrl(AlbumImages.Medium.ToString());
                    }

                    this._embedFooter.WithText($"{userinfo.Content.Name} has {userinfo.Content.Playcount} scrobbles.");
                    this._embed.WithFooter(this._embedFooter);

                    this._embed.WithColor(Constants.LastFMColorRed);
                    await ReplyAsync("", false, this._embed.Build());

                    break;
                }
                this._logger.LogCommandUsed(Context.Guild?.Id, Context.Channel.Id, Context.User.Id, Context.Message.Content);
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, Context.Message.Content, Context.User.Username, Context.Guild?.Name, Context.Guild?.Id);
                await ReplyAsync("Unable to show Last.FM info due to an internal error. Try scrobbling something then use the command again.");
            }
        }
Esempio n. 3
0
        public TimerService(DiscordShardedClient client, Logger logger)
        {
            _logger = logger;

            _timer = new Timer(async _ =>
            {
                string LastFMName = await userService.GetRandomLastFMUserAsync().ConfigureAwait(false);
                if (LastFMName != null)
                {
                    Random random         = new Random();
                    int randavmode        = random.Next(1, 4);
                    string randmodestring = "";

                    if (randavmode == 1)
                    {
                        randmodestring = "1 - Recent Listens";
                    }
                    else if (randavmode == 2)
                    {
                        randmodestring = "2 - Weekly Albums";
                    }
                    else if (randavmode == 3)
                    {
                        randmodestring = "3 - Overall Albums";
                    }
                    else if (randavmode == 4)
                    {
                        randmodestring = "4 - Default Avatar";
                    }


                    _logger.Log("Changing avatar to mode " + randmodestring);

                    string nulltext = "";

                    try
                    {
                        if (randavmode == 1)
                        {
                            PageResponse <LastTrack> tracks = await lastFMService.GetRecentScrobblesAsync(LastFMName).ConfigureAwait(false);
                            LastTrack currentTrack          = tracks.Content[0];

                            string TrackName  = string.IsNullOrWhiteSpace(currentTrack.Name) ? nulltext : currentTrack.Name;
                            string ArtistName = string.IsNullOrWhiteSpace(currentTrack.ArtistName) ? nulltext : currentTrack.ArtistName;
                            string AlbumName  = string.IsNullOrWhiteSpace(currentTrack.AlbumName) ? nulltext : currentTrack.AlbumName;

                            LastImageSet AlbumImages = null;

                            if (GlobalVars.CensoredAlbums.Contains(new KeyValuePair <string, string>(ArtistName, AlbumName)))
                            {
                                // use the censored cover.
                                try
                                {
                                    UseLocalAvatar(client, AlbumName, ArtistName, LastFMName);
                                    return;
                                }
                                catch (Exception)
                                {
                                    UseDefaultAvatar(client);
                                }
                            }
                            else
                            {
                                AlbumImages = await lastFMService.GetAlbumImagesAsync(ArtistName, AlbumName).ConfigureAwait(false);

                                trackString = ArtistName + " - " + AlbumName + Environment.NewLine + LastFMName;
                                _logger.Log("Changed avatar to: " + trackString);

                                if (AlbumImages?.Large != null)
                                {
                                    ChangeToNewAvatar(client, AlbumImages.Large.AbsoluteUri);
                                }
                            }
                        }
                        else if (randavmode == 2)
                        {
                            PageResponse <LastAlbum> albums = await lastFMService.GetTopAlbumsAsync(LastFMName, LastStatsTimeSpan.Week, 1).ConfigureAwait(false);
                            LastAlbum currentAlbum          = albums.Content[random.Next(albums.Count())];

                            string ArtistName = string.IsNullOrWhiteSpace(currentAlbum.ArtistName) ? nulltext : currentAlbum.ArtistName;
                            string AlbumName  = string.IsNullOrWhiteSpace(currentAlbum.Name) ? nulltext : currentAlbum.Name;

                            LastImageSet AlbumImages = null;

                            if (GlobalVars.CensoredAlbums.Contains(new KeyValuePair <string, string>(ArtistName, AlbumName)))
                            {
                                // use the censored cover.
                                try
                                {
                                    UseLocalAvatar(client, AlbumName, ArtistName, LastFMName);
                                    return;
                                }
                                catch (Exception)
                                {
                                    UseDefaultAvatar(client);
                                }
                            }
                            else
                            {
                                AlbumImages = await lastFMService.GetAlbumImagesAsync(ArtistName, AlbumName).ConfigureAwait(false);

                                trackString = ArtistName + " - " + AlbumName + Environment.NewLine + LastFMName;
                                _logger.Log("Changed avatar to: " + trackString);

                                if (AlbumImages?.Large != null)
                                {
                                    ChangeToNewAvatar(client, AlbumImages.Large.AbsoluteUri);
                                }
                            }
                        }
                        else if (randavmode == 3)
                        {
                            PageResponse <LastAlbum> albums = await lastFMService.GetTopAlbumsAsync(LastFMName, LastStatsTimeSpan.Overall, 1).ConfigureAwait(false);
                            LastAlbum currentAlbum          = albums.Content[random.Next(albums.Count())];

                            string ArtistName = string.IsNullOrWhiteSpace(currentAlbum.ArtistName) ? nulltext : currentAlbum.ArtistName;
                            string AlbumName  = string.IsNullOrWhiteSpace(currentAlbum.Name) ? nulltext : currentAlbum.Name;

                            LastImageSet AlbumImages = null;

                            if (GlobalVars.CensoredAlbums.Contains(new KeyValuePair <string, string>(ArtistName, AlbumName)))
                            {
                                // use the censored cover.
                                try
                                {
                                    UseLocalAvatar(client, AlbumName, ArtistName, LastFMName);
                                }
                                catch (Exception)
                                {
                                    UseDefaultAvatar(client);
                                }
                            }
                            else
                            {
                                AlbumImages = await lastFMService.GetAlbumImagesAsync(ArtistName, AlbumName).ConfigureAwait(false);

                                trackString = ArtistName + " - " + AlbumName + Environment.NewLine + LastFMName;
                                _logger.Log("Changed avatar to: " + trackString);

                                if (AlbumImages?.Large != null)
                                {
                                    ChangeToNewAvatar(client, AlbumImages.Large.AbsoluteUri);
                                }
                            }
                        }
                        else if (randavmode == 4)
                        {
                            UseDefaultAvatar(client);
                        }
                    }
                    catch (Exception e)
                    {
                        _logger.LogException("ChangeFeaturedAvatar", e);
                    }
                }
            },
                               null,
                               TimeSpan.FromSeconds(Convert.ToDouble(ConfigData.Data.TimerInit)),    // 4) Time that message should fire after the timer is created
                               TimeSpan.FromMinutes(Convert.ToDouble(ConfigData.Data.TimerRepeat))); // 5) Time after which message should repeat (use `Timeout.Infinite` for no repeat)

            timerEnabled = true;
        }
Esempio n. 4
0
        public async Task FmFriendsRecentAsync()
        {
            User userSettings = await _userService.GetUserSettingsAsync(Context.User).ConfigureAwait(false);

            if (userSettings?.UserNameLastFM == null)
            {
                await UsernameNotSetErrorResponseAsync();

                return;
            }

            try
            {
                List <Friend> friends = await _friendsService.GetFMFriendsAsync(Context.User).ConfigureAwait(false);

                if (friends?.Any() != true)
                {
                    await ReplyAsync("We couldn't find any friends. To add friends:\n" +
                                     "`.fmaddfriends 'lastfmname/discord name'`").ConfigureAwait(false);

                    return;
                }

                EmbedAuthorBuilder eab = new EmbedAuthorBuilder
                {
                    IconUrl = Context.User.GetAvatarUrl()
                };

                EmbedBuilder builder = new EmbedBuilder();
                builder.WithAuthor(eab);
                string URI = "https://www.last.fm/user/" + userSettings.UserNameLastFM;
                builder.WithUrl(URI);
                builder.Title = await _userService.GetUserTitleAsync(Context).ConfigureAwait(false);

                string amountOfScrobbles = "Amount of scrobbles of all your friends together: ";

                if (friends.Count > 1)
                {
                    builder.WithDescription("Songs from " + friends.Count + " friends");
                }
                else
                {
                    builder.WithDescription("Songs from your friend");
                    amountOfScrobbles = "Amount of scrobbles from your friend: ";
                }

                const string  nulltext      = "[undefined]";
                int           indexval      = (friends.Count - 1);
                int           playcount     = 0;
                List <string> failedFriends = new List <string>();

                foreach (Friend friend in friends)
                {
                    try
                    {
                        string friendusername = friend.FriendUser != null ? friend.FriendUser.UserNameLastFM : friend.LastFMUserName;

                        PageResponse <LastTrack> tracks = await _lastFmService.GetRecentScrobblesAsync(friendusername, 1).ConfigureAwait(false);

                        string TrackName  = string.IsNullOrWhiteSpace(tracks.FirstOrDefault().Name) ? nulltext : tracks.FirstOrDefault().Name;
                        string ArtistName = string.IsNullOrWhiteSpace(tracks.FirstOrDefault().ArtistName) ? nulltext : tracks.FirstOrDefault().ArtistName;
                        string AlbumName  = string.IsNullOrWhiteSpace(tracks.FirstOrDefault().AlbumName) ? nulltext : tracks.FirstOrDefault().AlbumName;

                        builder.AddField(friendusername + ":", TrackName + " - " + ArtistName + " | " + AlbumName);


                        if (friends.Count <= 8)
                        {
                            LastResponse <LastUser> userinfo = await _lastFmService.GetUserInfoAsync(friendusername).ConfigureAwait(false);

                            playcount += userinfo.Content.Playcount;
                        }
                    }
                    catch
                    {
                        //failedFriends.Add(friendusername);
                    }
                }

                if (friends.Count <= 8)
                {
                    EmbedFooterBuilder efb = new EmbedFooterBuilder
                    {
                        Text = amountOfScrobbles + playcount.ToString("0")
                    };
                    builder.WithFooter(efb);
                }

                //if (failedFriends.Count > 0)
                //{
                //    await ReplyAsync("Couldn't retrieve data for one or more of the following friends:\n" +
                //        string.Join(", ", friends.Select(s => s.LastFMUserName).ToArray()))
                //        .ConfigureAwait(false);
                //}

                await Context.Channel.SendMessageAsync("", false, builder.Build()).ConfigureAwait(false);

                this._logger.LogCommandUsed(Context.Guild?.Id, Context.Channel.Id, Context.User.Id, Context.Message.Content);
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, Context.Message.Content, Context.User.Username, Context.Guild?.Name, Context.Guild?.Id);

                await ReplyAsync("Unable to show friends due to an internal error. Try removing all your current friends using `.fmremoveallfriends` and try again.").ConfigureAwait(false);
            }
        }