コード例 #1
0
    public async Task SendEpicGamesBroadcaster(long chatId)
    {
        var games = await GetFreeGamesParsed();

        var freeGames = games.FirstOrDefault();

        if (freeGames == null)
        {
            return;
        }

        var productUrl   = freeGames.ProductUrl;
        var productTitle = freeGames.ProductTitle;

        var chat = await _botClient.GetChatAsync(chatId);

        if (chat.LinkedChatId != null)
        {
            chatId = chat.LinkedChatId.Value;
        }

        var isHistoryExist = await _rssService.IsHistoryExist(chatId, productUrl);

        if (isHistoryExist)
        {
            Log.Information(
                "Seem EpicGames with Title: '{Title}' already sent to ChatId: {ChannelId}",
                productTitle,
                chatId
                );
        }
        else
        {
            await _botClient.SendPhotoAsync(
                chatId : chatId,
                photo : freeGames.Images.ToString(),
                caption : freeGames.Detail,
                parseMode : ParseMode.Html
                );

            await _rssService.SaveRssHistoryAsync(
                new RssHistory()
            {
                ChatId      = chatId,
                Title       = productTitle,
                Url         = productUrl,
                PublishDate = DateTime.UtcNow,
                Author      = "EpicGames Free",
                CreatedAt   = DateTime.UtcNow,
                RssSource   = "https://store.epicgames.com"
            }
                );
        }
    }
コード例 #2
0
        public static async Task <int> ExecBroadcasterAsync(string chatId)
        {
            Log.Information("Starting RSS Scheduler.");
            int newRssCount = 0;

            var rssService = new RssService();

            Log.Information("Getting RSS settings..");
            var rssSettings = await rssService.GetRssSettingsAsync(chatId);

            var tasks = rssSettings.Select(async rssSetting =>
            {
                // foreach (RssSetting rssSetting in rssSettings)
                // {
                var rssUrl = rssSetting.UrlFeed;

                // var rssUrl = rssSetting["url_feed"].ToString();
                // var chatId = rssSetting["chat_id"].ToString();

                ConsoleHelper.WriteLine($"Processing {rssUrl} for {chatId}.");
                try
                {
                    var rssFeeds = await FeedReader.ReadAsync(rssUrl);
                    var rssTitle = rssFeeds.Title;

                    var castLimit = 3;
                    var castStep  = 0;

                    foreach (var rssFeed in rssFeeds.Items)
                    {
                        // Prevent flood in first time;
                        if (castLimit == castStep)
                        {
                            Log.Information($"Send stopped due limit {castLimit} for prevent flooding in first time");
                            break;
                        }

                        var titleLink = $"{rssTitle} - {rssFeed.Title}".MkUrl(rssFeed.Link);
                        var category  = rssFeed.Categories.MkJoin(", ");
                        var sendText  = $"{titleLink}" +
                                        $"\nTags: {category}";

                        var where = new Dictionary <string, object>()
                        {
                            { "chat_id", chatId },
                            { "url", rssFeed.Link }
                        };

                        var isExist = await rssService.IsExistInHistory(where);
                        if (!isExist)
                        {
                            Log.Information($"Sending feed to {chatId}");

                            try
                            {
                                await Bot.Client.SendTextMessageAsync(chatId, sendText, ParseMode.Html);

                                var data = new Dictionary <string, object>()
                                {
                                    { "url", rssFeed.Link },
                                    { "rss_source", rssUrl },
                                    { "chat_id", chatId },
                                    { "title", rssFeed.Title },
                                    { "publish_date", rssFeed.PublishingDate.ToString() },
                                    { "author", rssFeed.Author }
                                };

                                Log.Information($"Writing to RSS History");
                                await rssService.SaveRssHistoryAsync(data);

                                castStep++;
                                newRssCount++;
                            }
                            catch (ChatNotFoundException chatNotFoundException)
                            {
                                Log.Information($"May Bot not added in {chatId}.");
                                Log.Error(chatNotFoundException, "Chat Not Found");
                                // ConsoleHelper.WriteLine($"May Bot not added in {chatId}." +
                                // $"\n{chatNotFoundException.Message}");
                            }
                        }
                        else
                        {
                            Log.Information($"This feed has sent to {chatId}");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Broadcasting RSS Feed.");
                    Thread.Sleep(4000);

                    // ConsoleHelper.WriteLine(ex.Message);
                    // ConsoleHelper.WriteLine(ex.ToString());
                }
                // }
            });

            await Task.WhenAll(tasks);

            Log.Information($"RSS Scheduler finished. New RSS Count: {newRssCount}");

            return(newRssCount);
        }
コード例 #3
0
    public async Task ExecuteUrlAsync(
        long chatId,
        string rssUrl
        )
    {
        Log.Information(
            "Reading feed from {ChatId}. Url: {RssUrl}",
            chatId,
            rssUrl
            );

        // var rssFeeds = await FeedReader.ReadAsync(rssUrl, autoRedirect: false);
        var rssFeeds = await RssFeedUtil.OpenSyndicationFeed(rssUrl);

        // var rssTitle = rssFeeds.Title;

        var rssTitle = rssFeeds.Title.Text;
        var rssFeed  = rssFeeds.Items.FirstOrDefault();

        var rssFeedTitle      = rssFeed.Title.Text.Trim();
        var rssPublishDate    = rssFeed.PublishDate.Year.Equals(0001) ? rssFeed.LastUpdatedTime : rssFeed.PublishDate;
        var rssPublishDateStr = rssPublishDate.ToString("yyyy-MM-dd HH:mm:ss");
        var rssFeedAuthor     = rssFeed.Authors.FirstOrDefault()?.Name;
        var rssFeedLink       = rssFeed.Links.FirstOrDefault()?.Uri.ToString();

        Log.Debug(
            "Getting last history for {ChatId} url {RssUrl}",
            chatId,
            rssUrl
            );

        Log.Debug("CurrentArticleDate: {Date}", rssPublishDate);
        Log.Debug("Prepare sending article to ChatId {ChatId}", chatId);

        var isExist = await _rssService.IsHistoryExist(chatId, rssFeedLink);

        if (isExist)
        {
            Log.Information(
                "Last article from feed '{RssUrl}' has sent to {ChatId}",
                rssUrl,
                chatId
                );

            return;
        }

        Log.Information(
            "Sending article from feed {RssUrl} to {ChatId}",
            rssUrl,
            chatId
            );

        var category    = rssFeed.Categories.Select(syndicationCategory => syndicationCategory.Name).ToList().MkJoin(", ");
        var htmlMessage = HtmlMessage.Empty;

        var disableWebPagePreview = false;

        if (rssUrl.IsGithubReleaseUrl())
        {
            var listUrlAssetsList = await _octokitApiService.GetLatestReleaseAssetsList(rssUrl);

            if (listUrlAssetsList != null)
            {
                htmlMessage.Br()
                .Append(listUrlAssetsList)
                .Br()
                .Br();
            }
            else
            {
                htmlMessage.Br();
            }

            htmlMessage.Text("#github #release");

            disableWebPagePreview = true;
        }
        else
        {
            htmlMessage.TextBr($"{rssTitle} - {rssFeedTitle}");

            htmlMessage.TextBr($"{rssFeedLink}");

            if (category.IsNotNullOrEmpty())
            {
                htmlMessage.Text($"\nTags: {category}");
            }
        }

        try
        {
            await _botClient.SendTextMessageAsync(
                chatId : chatId,
                text : htmlMessage.ToString(),
                disableWebPagePreview : disableWebPagePreview,
                parseMode : ParseMode.Html
                );

            Log.Debug(
                "Writing to RSS History for ChatId: {ChatId}, Rss: {UrlFeed}",
                chatId,
                rssUrl
                );

            await _rssService.SaveRssHistoryAsync(
                new RssHistory
            {
                Url         = rssFeedLink,
                RssSource   = rssUrl,
                ChatId      = chatId,
                Title       = rssFeedTitle,
                PublishDate = rssPublishDate,
                Author      = rssFeedAuthor ?? "N/A",
                CreatedAt   = DateTime.Now
            }
                );
        }
        catch (Exception ex)
        {
            Log.Error(
                ex.Demystify(),
                "RSS Broadcaster Error at ChatId {ChatId}. Url: {Url}",
                chatId,
                rssUrl
                );

            if (ex.Message.ContainsListStr(
                    "blocked",
                    "not found",
                    "deactivated"
                    ))
            {
                UnregisterRssFeed(chatId, rssUrl);
            }
        }
    }
コード例 #4
0
        public static async Task ExecuteUrlAsync(long chatId, string rssUrl)
        {
            int newRssCount = 0;
            var rssService  = new RssService();

            var rssFeeds = await FeedReader.ReadAsync(rssUrl)
                           .ConfigureAwait(false);

            var rssTitle = rssFeeds.Title;

            // var castLimit = 10;
            // var castStep = 0;

            foreach (var rssFeed in rssFeeds.Items)
            {
                // Prevent flood in first time;
                // if (castLimit == castStep)
                // {
                //     Log.Information($"Send stopped due limit {castLimit} for prevent flooding in first time");
                //     break;
                // }

                var whereHistory = new Dictionary <string, object>()
                {
                    ["chat_id"]    = chatId,
                    ["rss_source"] = rssUrl
                };

                var rssHistory = await rssService.GetRssHistory(whereHistory)
                                 .ConfigureAwait(false);

                var lastRssHistory = rssHistory.LastOrDefault();

                if (!rssHistory.Any())
                {
                    break;
                }

                var lastArticleDate    = DateTime.Parse(lastRssHistory.PublishDate);
                var currentArticleDate = rssFeed.PublishingDate.Value;

                if (currentArticleDate < lastArticleDate)
                {
                    Log.Information($"Current article is older than last article. Stopped.");
                    break;
                }

                Log.Information($"LastArticleDate: {lastArticleDate}");
                Log.Information($"CurrentArticleDate: {currentArticleDate}");


                Log.Information("Prepare sending article.");

                var titleLink = $"{rssTitle} - {rssFeed.Title}".MkUrl(rssFeed.Link);
                var category  = rssFeed.Categories.MkJoin(", ");
                var sendText  = $"{rssTitle} - {rssFeed.Title}" +
                                $"\n{rssFeed.Link}" +
                                $"\nTags: {category}";

                var where = new Dictionary <string, object>()
                {
                    { "chat_id", chatId },
                    { "url", rssFeed.Link }
                };

                var isExist = await rssService.IsExistInHistory(where)
                              .ConfigureAwait(false);

                if (isExist)
                {
                    Log.Information($"This feed has sent to {chatId}");
                    break;
                }

                Log.Information($"Sending feed to {chatId}");

                try
                {
                    await BotSettings.Client.SendTextMessageAsync(chatId, sendText, ParseMode.Html)
                    .ConfigureAwait(false);

                    var data = new Dictionary <string, object>()
                    {
                        { "url", rssFeed.Link },
                        { "rss_source", rssUrl },
                        { "chat_id", chatId },
                        { "title", rssFeed.Title },
                        { "publish_date", rssFeed.PublishingDate.ToString() },
                        { "author", rssFeed.Author },
                        { "created_at", DateTime.Now.ToString(CultureInfo.InvariantCulture) }
                    };

                    Log.Information($"Writing to RSS History");
                    await rssService.SaveRssHistoryAsync(data)
                    .ConfigureAwait(false);

                    // castStep++;
                    newRssCount++;
                }
                catch (ChatNotFoundException chatNotFoundException)
                {
                    Log.Information($"May Bot not added in {chatId}.");
                    Log.Error(chatNotFoundException, "Chat Not Found");
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "RSS Broadcaster error");
                }
            }
        }
コード例 #5
0
        public static async Task ExecScheduler(string chatId)
        {
            ConsoleHelper.WriteLine("Starting RSS Scheduler.");

            var rssService = new RssService();

            ConsoleHelper.WriteLine("Getting RSS settings..");
            var rssSettings = await rssService.GetRssSettingsAsync(chatId);

            foreach (RssSetting rssSetting in rssSettings)
            {
                var rssUrl = rssSetting.UrlFeed;
                // var rssUrl = rssSetting["url_feed"].ToString();
                // var chatId = rssSetting["chat_id"].ToString();

                ConsoleHelper.WriteLine($"Processing {rssUrl} for {chatId}.");
                var rssFeeds = await FeedReader.ReadAsync(rssUrl);

                var rssTitle = rssFeeds.Title;

                var rssLimit = 3;
                var rssStep  = 1;

                foreach (var rssFeed in rssFeeds.Items.Take(rssLimit))
                {
                    // if (rssStep == rssLimit)
                    // {
                    // ConsoleHelper.WriteLine($"RSS Limit to {rssLimit} in first time.");
                    // break;
                    // }

                    var titleLink = $"{rssTitle} - {rssFeed.Title}".MkUrl(rssFeed.Link);
                    var category  = rssFeed.Categories.MkJoin(", ");
                    var sendText  = $"{titleLink}" +
                                    $"\nTags: {category}";

                    var where = new Dictionary <string, object>()
                    {
                        { "chat_id", chatId },
                        { "url", rssFeed.Link }
                    };

                    var isExist = await rssService.IsExistInHistory(where);

                    if (!isExist)
                    {
                        ConsoleHelper.WriteLine($"Sending feed to {chatId}");

                        try
                        {
                            await Bot.Client.SendTextMessageAsync(chatId, sendText, ParseMode.Html);

                            var data = new Dictionary <string, object>()
                            {
                                { "url", rssFeed.Link },
                                { "chat_id", chatId },
                                { "publish_date", rssFeed.PublishingDate.ToString() },
                                { "author", rssFeed.Author }
                            };

                            ConsoleHelper.WriteLine($"Writing to RSS History");
                            await rssService.SaveRssHistoryAsync(data);

                            rssStep++;
                        }
                        catch (ChatNotFoundException chatNotFoundException)
                        {
                            ConsoleHelper.WriteLine($"May Bot not added in {chatId}." +
                                                    $"\nMessage: {chatNotFoundException.Message}");
                        }
                    }
                    else
                    {
                        ConsoleHelper.WriteLine($"This feed has sent to {chatId}");
                    }
                }
            }

            ConsoleHelper.WriteLine("RSS Scheduler finished.");
        }