Ejemplo n.º 1
0
        public async Task fmchartAsync(string chartsize = "3x3", string time = "weekly", string titlesetting = null, IUser user = null)
        {
            if (chartsize == "help")
            {
                await ReplyAsync("fmchart '2x2-8x8' 'weekly/monthly/yearly/overall' 'notitles/titles' 'user'");

                return;
            }

            User userSettings = await _userService.GetUserSettingsAsync(Context.User);

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

                return;
            }

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

                if (!perms.AttachFiles)
                {
                    await ReplyAsync("I'm missing the 'Attach files' permission in this server, so I can't post a chart.");

                    return;
                }
            }

            // @TODO: change to intparse or the likes
            try
            {
                var loadingMsg = await ReplyAsync($"Generating a {chartsize} chart for {Context.User.Username}. Please note that this could take a while depending on the size of your chart.");

                int chartAlbums;
                int chartRows;

                switch (chartsize)
                {
                case "2x2":
                    chartAlbums = 4;
                    chartRows   = 2;
                    break;

                case "3x3":
                    chartAlbums = 9;
                    chartRows   = 3;
                    break;

                case "4x4":
                    chartAlbums = 16;
                    chartRows   = 4;
                    break;

                case "5x5":
                    chartAlbums = 25;
                    chartRows   = 5;
                    break;

                case "6x6":
                    chartAlbums = 36;
                    chartRows   = 6;
                    break;

                case "7x7":
                    chartAlbums = 49;
                    chartRows   = 7;
                    break;

                case "8x8":
                    chartAlbums = 64;
                    chartRows   = 8;
                    break;

                default:
                    await ReplyAsync("Your chart's size isn't valid. Sizes supported: 3x3-8x8");

                    return;
                }

                // Generating image
                List <Bitmap> images = new List <Bitmap>();

                var timespan = _lastFmService.StringToLastStatsTimeSpan(time);
                PageResponse <LastAlbum> albums = await _lastFmService.GetTopAlbumsAsync(userSettings.UserNameLastFM, timespan, chartAlbums).ConfigureAwait(false);

                if (albums.Count() < chartAlbums)
                {
                    await ReplyAsync($"You haven't listened to enough albums ({albums.Count()} of required {chartAlbums}) for a chart this size. Please try a smaller chart or a bigger time period (weekly/monthly/yearly/overall)'.");

                    return;
                }

                FMBotChart chart = new FMBotChart
                {
                    albums      = albums,
                    time        = time,
                    LastFMName  = userSettings.UserNameLastFM,
                    max         = chartAlbums,
                    rows        = chartRows,
                    images      = images,
                    DiscordUser = Context.User,
                    disclient   = Context.Client as DiscordSocketClient,
                    mode        = 0,
                    titles      = titlesetting == null ? userSettings.TitlesEnabled ?? true : titlesetting == "titles",
                };

                await _userService.ResetChartTimerAsync(userSettings);

                await SendChartMessage(chart);

                // Adding extra infobox
                this._embedAuthor.WithIconUrl(Context.User.GetAvatarUrl());

                this._embed.WithColor(Constants.LastFMColorRed);
                this._embed.WithAuthor(this._embedAuthor);
                var URI = "https://www.last.fm/user/" + userSettings.UserNameLastFM;
                this._embed.WithUrl(URI);
                this._embed.Title = await _userService.GetUserTitleAsync(Context);

                // @TODO: clean up
                if (time.Equals("weekly") || time.Equals("week") || time.Equals("w"))
                {
                    this._embed.WithDescription("Last.FM " + chartsize + " Weekly Chart for " + userSettings.UserNameLastFM);
                }
                else if (time.Equals("monthly") || time.Equals("month") || time.Equals("m"))
                {
                    this._embed.WithDescription("Last.FM " + chartsize + " Monthly Chart for " + userSettings.UserNameLastFM);
                }
                else if (time.Equals("yearly") || time.Equals("year") || time.Equals("y"))
                {
                    this._embed.WithDescription("Last.FM " + chartsize + " Yearly Chart for " + userSettings.UserNameLastFM);
                }
                else if (time.Equals("overall") || time.Equals("alltime") || time.Equals("o") || time.Equals("at"))
                {
                    this._embed.WithDescription("Last.FM " + chartsize + " Overall Chart for " + userSettings.UserNameLastFM);
                }
                else
                {
                    this._embed.WithDescription("Last.FM " + chartsize + " Chart for " + userSettings.UserNameLastFM);
                }

                LastResponse <LastUser> userInfo = await _lastFmService.GetUserInfoAsync(userSettings.UserNameLastFM);

                int playcount = userInfo.Content.Playcount;

                this._embedFooter.Text = userSettings.UserNameLastFM + "'s total scrobbles: " + playcount.ToString("0");
                this._embed.WithFooter(this._embedFooter);

                await Context.Channel.SendMessageAsync("", false, this._embed.Build());

                await loadingMsg.DeleteAsync();

                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("Sorry, but I was unable to generate a FMChart due to an internal error. Make sure you have scrobbles and Last.FM isn't having issues, and try again later.");
            }
        }
Ejemplo n.º 2
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;
        }