Exemplo n.º 1
0
        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);
        }
Exemplo n.º 2
0
        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);
        }
Exemplo n.º 3
0
        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); }
        }
Exemplo n.º 4
0
        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);
            }
        }
Exemplo n.º 5
0
 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);
     }
 }
Exemplo n.º 6
0
 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);
     }
 }
Exemplo n.º 7
0
        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);
            }
        }
Exemplo n.º 8
0
        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 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);
             }
         }
     }));
 }
Exemplo n.º 10
0
 public void Stop()
 {
     if (Bot != null && Bot.IsReceiving)
     {
         Bot.StopReceiving();
         Bot = null;
     }
     try
     {
         botThread?.Abort();
     }
     catch
     {
         BotConsole.Write("В боте был вызван Dispose()", MessageType.Info);
     }
 }
Exemplo n.º 11
0
        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);
                }
            }
        }
Exemplo n.º 12
0
        /// <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);
        }
Exemplo n.º 13
0
        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);
            }
        }
Exemplo n.º 14
0
        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);
        }
Exemplo n.º 15
0
        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);
            });
        }
Exemplo n.º 16
0
 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);
         }
     }));
 }
Exemplo n.º 17
0
        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);
                }
            });
        }
Exemplo n.º 18
0
 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();
 }
Exemplo n.º 19
0
 protected override bool Execute(TBot bot, TMessage message, object arg = null)
 {
     BotConsole.Write(_logText);
     return(BaseCommand.ExecuteCommand(bot, message, arg));
 }