internal static StoreManager Init(TelegramStore config) { if (config is null) { throw new StruLogConfigException($"Not found configuration for '{NAME}' store"); } if (@this == null) { @this = new TelegramSM(config); } return(@this); }
private TelegramSM(TelegramStore config) { Config = config; ProcessingQueueSize = 100_000; ProcessingQueue = new BlockingCollection <LogData>(ProcessingQueueSize); AccessAttemptsDelays_mSeconds = new int[] { 25, 45, 90, 250, 500, 1000, 3000, 5000 }; Logger = LoggersFactory.GetLogger <TelegramSM>(true); MinLogLevel = config.minLogLevel; if (Config.intensivity.enable) { Intensivity = new TelegramHandlingIntensivity { PeriodLength = Config.intensivity.period } } ; }
/// <summary> /// /// </summary> /// <param name="telegramConfig"></param> /// <param name="config"></param> /// <param name="chatIds">Must contents Ids from config</param> private static void DefineTelegramChatId(JToken telegramConfig, TelegramStore config, HashSet <long> chatIds) { ReceiveChatIdsFromBot(); //adds to chatIds if (chatIds.Count == 0) { throw new StruLogConfigException("Telegram store wasn't configure. Repeat it or turn off Telegram store in config"); } telegramConfig["chats"] = NewtonsoftJsonTools.ConvertIEnumerableToJToken(chatIds); config.chatIds = chatIds.ToImmutableList(); void ReceiveChatIdsFromBot() { TelegramBotClient client = new TelegramBotClient(config.token); Console.WriteLine("You enabled Telegram Store, require tuning (if it was by error, stop execution and disable telegram store using in config). \n - Send messages to your TelegramBot from required Telegram accounts. \n - StruLog will determines chatId for each account and saves this to config file. \n - For tuning finish you should send inTelegram command 'finish_tuning' OR stop execution. \n - WARNING: not only you can get access to your telegramBot now, attentionally see to current log, that only valid users got access to project logs. \n - The process of remembering of users:"); int updatesOffset = 0; while (true) { Update[] updates = null; try { updates = client.GetUpdatesAsync(offset: updatesOffset).Result; foreach (var update in updates) { Message msg = update.Message; Console.WriteLine($"Detected user @{msg.From.Username} ({msg.From.FirstName} {msg.From.LastName}) with chatId:{msg.Chat.Id}"); updatesOffset = update.Id; switch (msg.Text) { case "finish_tuning": //if (msg.Date.AddSeconds(10) >= DateTime.UtcNow) //block probable fake requests //{ // Console.WriteLine(@">>> finish_tuning applied. If you have problems with fake finish_tuning requests set true system time"); // return; //} client.GetUpdatesAsync(offset: updatesOffset + 1).Wait(); return; default: RememberNewTelegramChat(msg.Chat.Id, chatIds); break; } } } catch (Exception e) { throw new StruLogException($"Telegram Long Polling unable: {e.Message} {e.StackTrace}"); } finally { if (updates != null && updates.Length > 0) { updatesOffset++; } } } //throw new StruLogException("Unable define chatId for telegram. You must send only /start command. Leave from chat with bot and delete it, repeat."); } }
/// <summary> /// Парсинг из конфига, временное прослушивание телеграм-бота, запись настроек в конфиг /// </summary> /// <returns></returns> private static TelegramStore DefineTelegramStoreSettings() { var stores = jsonDoc.SelectToken(nameof(Config.stores)); var telegramFileConfig = stores.SelectToken(TelegramSM.NAME); var telegramStoreConfig = new TelegramStore { minLogLevel = telegramFileConfig.Value <string>(nameof(Store.minLogLevel)).StringToEnum <LogLevel>(), outputPattern = StringStoreManager.GetOutputActions(telegramFileConfig.Value <string>(nameof(TelegramStore.outputPattern))), token = telegramFileConfig.Value <string>(nameof(TelegramStore.token)), }; int sendingPeriod = telegramFileConfig.Value <int>(nameof(TelegramStore.sendingPeriod)); if (sendingPeriod < 1000) { Console.WriteLine(@"StruLog: telegram/sendingPeriod (see config) must be >= 1000, will be 3000"); telegramStoreConfig.sendingPeriod = 3000; } else { telegramStoreConfig.sendingPeriod = sendingPeriod; } var intensivity = telegramFileConfig.SelectToken(nameof(TelegramStore.intensivity)); if (intensivity?.HasValues ?? false) { telegramStoreConfig.intensivity = new TelegramStore.IntensivityControl { enable = intensivity.Value <bool>(nameof(TelegramStore.intensivity.enable)), nMessagesPerPeriod = intensivity.Value <long>(nameof(TelegramStore.intensivity.nMessagesPerPeriod)), period = TimeSpan.Parse(intensivity.Value <string>(nameof(TelegramStore.intensivity.period))) } } ; else { telegramStoreConfig.intensivity = new TelegramStore.IntensivityControl { enable = false } }; var chatIdsFromConfig = telegramFileConfig.SelectToken("chats"); HashSet <long> chatIds; if (chatIdsFromConfig.HasValues) { chatIds = NewtonsoftJsonTools.ConvertJTokenToIEnumerable <long>(chatIdsFromConfig).ToHashSet(); } else { chatIds = new HashSet <long>(); } if (chatIds.Count == 0 || (options?.AddTelegramConsumers ?? false)) { DefineTelegramChatId(telegramFileConfig, telegramStoreConfig, chatIds); SaveChangesToConfig(); } else { telegramStoreConfig.chatIds = chatIds.ToImmutableList(); } return(telegramStoreConfig); }