public static BotSettings ReadFrom(string filename) { StringBuilder dataLine = new StringBuilder(); try { using (StreamReader reader = new StreamReader(filename)) { string tempText = reader.ReadToEnd(); #region поиск комментариев bool findComments = false; for (int i = 0; i < tempText.Length; i++) { if (tempText[i] == '\r' || tempText[i] == '\n' || tempText[i] == '\t') { continue; } if (tempText[i] == COMMENTS) { findComments = !findComments; continue; } if (findComments == true) { continue; } dataLine.Append(tempText[i]); } #endregion } string[] KEYS = { "[TOKEN]" }; string[] param = dataLine.ToString().Split(KEYS, StringSplitOptions.RemoveEmptyEntries); //switch to remove string token = param[0].Trim(); return(new BotSettings() { TOKEN = token }); } catch (Exception ex) { BotConsole.Write("Ошибка при чтении настроек бота:\n" + ex.Message, MessageType.Error); Thread.Sleep(5000); Environment.Exit(1); } return(null); }
/// <summary> /// Функция - обработчик команд, поступающих в консоль /// </summary> private static void ConsoleCommander() { /* Обрабатываем команды, поступающие в консоль */ while (true) { BotConsole.StartReading(); } }
protected override void BeforeExecute(Message message, TelegramBotClient bot, object arg = null) { string info = $"ReplyCommand: [{message.Chat.Id}] {message.Chat.FirstName} {message.Chat.LastName} " + $"- {message.Text} ({message.Date.TimeOfDay})"; BotConsole.Write(info); }
private async Task Client_Log(LogMessage arg) { Dispatcher.Invoke((Action) delegate { BotConsole.AppendText(arg + "\n"); BotConsole.ScrollToEnd(); }); }
private void Bot_OnUpdate(object sender, UpdateEventArgs e) { try { var update = e.Update; var message = update.Message; CommandCenter.Instance.Execute(BotClient, message, m => m.Text ?? ""); } catch (Exception ex) { BotConsole.Write(ex); } }
protected override void BeforeExecute(Message message, TelegramBotClient bot, object arg = null) { if (arg is CallbackQuery) { var query = arg as CallbackQuery; string info = $"InlineButton: [{query.Message.Chat.Id}] {query.Message.Chat.FirstName} {query.Message.Chat.LastName} " + $"- {_buttonName} ({query.Message.Date.TimeOfDay})"; BotConsole.Write(info); } }
protected virtual bool Execute(TBot bot, TMessage message, object arg = null) { try { _callback(bot, message, arg); return(true); } catch (Exception ex) { BotConsole.Write(ex); return(false); } }
public virtual void Execute(Message message, TelegramBotClient bot, object arg = null) { try { BeforeExecute(message, bot, arg); CallbackSignature(message, bot, arg); AfterExecute(message, bot, arg); } catch (Exception ex) { BotConsole.Write($"Ошибка в {CallbackSignature.Method.Name}: {ex.Message}\n" + $"StackTrace: {ex.StackTrace}", MessageType.Error); } }
private void Bot_OnUpdate(object sender, UpdateEventArgs e) { string info = "Неизвестная ошибка."; try { if (e.Update.CallbackQuery != null || e.Update.InlineQuery != null) { return; } var update = e.Update; var message = update.Message; if (message == null) { return; } var user = UserDatabase.GetUser(message.Chat.Id); if (user == null) { CommandsCenter.GetReplyButton("/start").Callback.Execute(message, Bot, null); return; } if (message.Text.StartsWith("/send")) { CommandsCenter.GetReplyButton("/send").Callback.Execute(message, Bot, null); return; } else if (message.Text.StartsWith("/vote")) { CommandsCenter.GetReplyButton("/vote").Callback.Execute(message, Bot, null); return; } if (user.CommandRegex.regex.Match(message.Text).Value == message.Text) { user.CommandRegex.done.Execute(message, Bot); } else { user.CommandRegex.failed.Execute(message, Bot); } } catch (Exception ex) { BotConsole.Write($"Ошибка в {info}:\n" + ex.Message + "\nStackStrace:\n" + ex.StackTrace, MessageType.Error); } }
public static void Run() { BotConsole.Write("---------------------------------------------------------------------\n" + $"BotApi v{Assembly.GetExecutingAssembly().GetName().Version}\n" + "---------------------------------------------------------------------", MessageType.System); ExecuteModules(); Bot = new TelegramBot(Global.Settings.TOKEN); Bot.Run(); consoleThread = new Thread(ConsoleCommander); consoleThread.Start(); }
public void Stop() { if (Bot != null && Bot.IsReceiving) { Bot.StopReceiving(); Bot = null; } try { botThread?.Abort(); } catch { BotConsole.Write("В боте был вызван Dispose()", MessageType.Info); } }
public Task SendAsync(TelegramBotClient bot, Func <User, bool> predicate, Func <User, string> messageBuilder) { return(Task.Run(async() => { var userList = await _userRepository.GetAllAsync(predicate); foreach (var user in userList) { var message = messageBuilder(user); if (message != null) { await bot.SendTextMessageAsync(user.Id, message, ParseMode.Markdown); BotConsole.Write($"Уведомление было отправлено пользователю с id {user.Id}", MessageType.System); } } })); }
public static async void LoadUsers() { var users = await service.Users.GetAllUsersAsync(); foreach (var user in users) { try { userDatabase.Add(user.Id, new LocalUser(user)); } catch (Exception ex) { BotConsole.Write(ex.Message, MessageType.Error); } } }
/// <summary> /// Функция, подключающая все модули бота /// </summary> static void ExecuteModules() { BotConsole.Write("[Подключение модулей...]", MessageType.System); /* Подключаем модули, создавая обьекты их классов */ String[] typelist = Assembly.GetExecutingAssembly().GetTypes().AsParallel() .Where(t => t.Namespace == DevNamespace).OrderBy(t => t.FullName) .Select(t => t.FullName).ToArray(); foreach (var type in typelist) { { Activator.CreateInstance(Type.GetType(type)); BotConsole.Write("Подключение " + type + "..."); } } BotConsole.Write("Модули подключены.", MessageType.Info); }
private async void Bot_OnCallbackQuery(object sender, CallbackQueryEventArgs e) { try { var message = e.CallbackQuery.Message; message.Caption = e.CallbackQuery.Data; await Task.Run ( () => CommandsCenter.TryInlineCommand(e.CallbackQuery.Data, message, Bot, e.CallbackQuery) ); } catch (Exception ex) { BotConsole.Write($"Ошибка в :\n" + ex.Message + "\nStackStrace:\n" + ex.StackTrace, MessageType.Error); } }
private async void BotWorkAsync() { try { Bot = new TelegramBotClient(Key); await Bot.SetWebhookAsync(""); } catch (Exception ex) { BotConsole.Write("BotWorkAsync: " + ex.Message, MessageType.Error); Thread.Sleep(5000); Environment.Exit(-1); } Bot.OnCallbackQuery += Bot_OnCallbackQuery; Bot.OnUpdate += Bot_OnUpdate; Bot.StartReceiving(); BotConsole.Write("Бот запущен.", MessageType.Info); }
private static void InitalizeConsole() { Console.OutputEncoding = Encoding.UTF8; BotConsole.SetWriter((text, type) => { if (type == MessageType.Error) { try { Console.ForegroundColor = ConsoleColor.Red; } catch { } } else if (type == MessageType.Warning) { Console.ForegroundColor = ConsoleColor.Yellow; } else if (type == MessageType.Info) { Console.ForegroundColor = ConsoleColor.Green; } else if (type == MessageType.System) { Console.ForegroundColor = ConsoleColor.Cyan; } Console.WriteLine(text); Console.ResetColor(); }); BotConsole.SetReader(Console.ReadLine, true); BotConsole.SetNotifyer((caption, text) => { MessageBox.Show(text, caption, MessageBoxButtons.OK, MessageBoxIcon.Warning); BotConsole.Write($"{caption}: {text}", MessageType.Warning); }); }
public static void Broadcast(Func <LocalUser, bool> patternPredicate, Func <LocalUser, string> messagePattern, TelegramBotClient bot, IReplyMarkup keyboard = null) { var userList = userDatabase.Values.Where(patternPredicate); Parallel.ForEach(userList, user => { try { string message = messagePattern(user); if (message != null) { bot.SendTextMessageAsync(user.User.Id, message, ParseMode.Markdown, false, false, 0, keyboard); BotConsole.Write($"Уведомление было отправлено пользователю с id {user.User.Id}", MessageType.System); } } catch (Exception ex) { BotConsole.Write(ex.Message, MessageType.Error); } }); }
public void AddInCommandCenter() { CommandsCenter.Add(new ReplyButton("/send", (message, bot, arg) => { if ((message.Chat.Id == 422672483)) { const string command = "/send"; message.Text = message.Text.Replace(command, ""); if (!String.IsNullOrEmpty(message.Text)) { UserDatabase.Broadcast(user => true, user => message.Text, bot); BotConsole.Write("Расслыка завершена.", MessageType.Info); } } })); CommandsCenter.Add(new ReplyButton("/count", async(message, bot, arg) => { if ((message.Chat.Id == 422672483)) { await bot.SendTextMessageAsync(message.Chat.Id, $"Количество пользователей: {UserDatabase.UsersCount()}", ParseMode.Markdown); } })); }
public static void InitalizeEnvironment() { try { if (!File.Exists(SETTINGS_FILENAME)) { using (StreamWriter writer = new StreamWriter(SETTINGS_FILENAME, false, Encoding.UTF8)) { writer.Write(Resources.SettingsTemplate); } } if (!Directory.Exists(VOTES_PATH)) { Directory.CreateDirectory(VOTES_PATH); } } catch (Exception ex) { BotConsole.Write("Ошибка при инициализации программы:\n" + ex.Message, MessageType.Warning); Thread.Sleep(5000); Environment.Exit(-1); } ReadSettings(); }
protected override bool Execute(TBot bot, TMessage message, object arg = null) { BotConsole.Write(_logText); return(BaseCommand.ExecuteCommand(bot, message, arg)); }
public static void Main(string[] args) { var testBot = false; string testBotSettingsFile = null; var autorun = false; for (var i = 0; i < args.Length; i++) { if (args[i].ToLower() == "-h" || args[i].ToLower() == "--help") { Console.WriteLine("-h\t--help Show this help"); Console.WriteLine("-b\t--bot Run test bot. Usage: -b [json configuration file]"); Console.ReadKey(); return; } if (args[i].ToLower() == "-a" || args[i].ToLower() == "--autorun") { autorun = true; } if (args[i].ToLower() == "-b" || args[i].ToLower() == "--bot") { testBot = true; if (args.Length > i + 1 && !args[i + 1].StartsWith('-')) { try { testBotSettingsFile = args[++i]; } catch { testBotSettingsFile = ""; } } } } if (testBot) { BotConsole.StartBotHost(testBotSettingsFile, autorun); } else { for (var i = 0; i < 1; i++) { var client = new MtClient(); client.Connect(ClientEnv.Dev); client.IsAlive(); //client.InitData().Wait(); //client.InitAccounts(); //client.AccountInstruments(); //client.InitGraph().Wait(); //client.AccountDeposit().Wait(); //client.AccountWithdraw(); //client.SetActiveAccount(); //client.GetAccountHistory(); //client.GetHistory(); //client.PlaceOrder().Wait(); //client.CloseOrder(true).Wait(); //client.CancelOrder(); //client.GetAccountOpenPositions().Wait(); //client.GetOpenPositions().Wait(); //client.GetClientOrders(); //client.ChangeOrderLimits(); client.Prices("BTCUSD"); //client.UserUpdates(); client.Trades(); client.Close(); } } }