Exemple #1
0
        /// <summary>
        /// Создание бота (только телеграм)
        /// </summary>
        /// <param name="model"></param>
        /// <param name="masterId"></param>
        /// <returns></returns>
        public async Task <bool> CreateBotAsync(CreateBotViewModel model, Models.User user)
        {
            if (user.ConfirmEmail && user.BotCount < 3 && (await context.Bots.FirstOrDefaultAsync(b => b.Key == model.Key || b.Name == model.Name)) == null)
            {
                TelegramBot bot = new TelegramBot(model.Name, model.Key)
                {
                    DateOfReg    = DateTime.Now,
                    LastActivity = DateTime.Now,
                    MasterId     = user.Id,
                    IsActive     = true,
                };
                await bot.GetClient();

                Bot bot_ = bot.TakeAsParent();
                context.Bots.Add(bot_);
                user.BotCount++;
                await context.SaveChangesAsync();

                bot.Id = bot_.Id;
                Directory.CreateDirectory(AppConfig.UsersPath + $"/{user.Id}/bots/{bot.Id}/functional");
                bot.PhysicalPath = bot_.PhysicalPath = AppConfig.UsersPath + $"/{bot.MasterId}/bots/{bot_.Id}";
                await bot_.SaveFunctionalAsync(new Functional()
                {
                    BotId            = bot.Id,
                    CommandFunctions = bot.Functions
                });

                await context.SaveChangesAsync();

                return(true);
            }
            return(false);
        }
Exemple #2
0
        public MainClass()
        {
            _handler += new MainClass.EventHandler(Handler);
            AppDomain.CurrentDomain.ProcessExit += (s, e) => { OnProcessExit(s, new EventType {
                    msg = "Quit"
                }); };
            SetConsoleCtrlHandler(_handler, true);
            settings   = new SettingsData();
            controller = new Controller(settings);

            Sheet = new GSheet(controller);
            RigEx.WriteLineColors($"servise:\tGoogle Sheet\t- {Sheet != null}".AddTimeStamp(), Sheet != null ? ConsoleColor.DarkGreen : ConsoleColor.Red);
            bool initBiosDone = controller.TelegramUser.Any() && controller.ServerList.Any();

            RigEx.WriteLineColors($"servise:\tGoogle Reader\t- {initBiosDone}".AddTimeStamp(), initBiosDone ? ConsoleColor.DarkGreen : ConsoleColor.Red);
            sensors = new SensorService(controller);
            RigEx.WriteLineColors($"servise:\tSensors\t\t- {sensors != null}".AddTimeStamp(), sensors != null ? ConsoleColor.DarkGreen : ConsoleColor.Red);
            alarmSensors = new AlarmData(controller);
            RigEx.WriteLineColors($"servise:\tAlarmSensors\t- {alarmSensors != null}".AddTimeStamp(), alarmSensors != null ? ConsoleColor.DarkGreen : ConsoleColor.Red);
            tbot = new TelegramBot(controller);
            RigEx.WriteLineColors($"servise:\tTelegramBot\t- {tbot != null}".AddTimeStamp(), tbot != null ? ConsoleColor.DarkGreen : ConsoleColor.Red);
            difficulty = new MineDifficulty(controller);
            RigEx.WriteLineColors($"servise:\tWhat To Mine\t- {difficulty != null}".AddTimeStamp(), difficulty != null ? ConsoleColor.DarkGreen : ConsoleColor.Red);
            miner = new Miner(controller);
            RigEx.WriteLineColors($"servise:\tMiner \t- {miner != null}".AddTimeStamp(), miner != null ? ConsoleColor.DarkGreen : ConsoleColor.Red);
        }
        internal void UnregisterAccount(Message message, string text)
        {
            Bot = new TelegramBot(accessToken: ConfigurationManager.AppSettings[name: "accessKey"]);

            // set up regex sequence matcher
            var address = new Regex(
                pattern: @"[Nn]{1,1}[a-zA-Z0-9]{39,39}");

            // extract any valid addresses
            var result = address.Matches(input: StringUtils.GetResultsWithoutHyphen(text)).Cast <Match>().Select(selector: m => m.Value).ToList();

            var userNodes = NodeUtils.GetNodeByUser(chatId: message.Chat.Id);

            foreach (var acc in result)
            {
                SummaryUtils.DeleteHbSummaryForUser(account: acc, chatId: message.Chat.Id);
                SummaryUtils.DeleteTxSummaryForUser(account: acc, chatId: message.Chat.Id);
            }

            // delete any valid addresses
            AccountUtils.DeleteAccount(chatId: message.Chat.Id,
                                       accounts: result.Where(predicate: x => userNodes.All(predicate: y => y.IP != x))
                                       .ToList());

            // notify user
            var reqAction = new SendMessage(chatId: message.Chat.Id, text: result.Aggregate(seed: "Addresses unregistered: \n", func: (current, n) => current + StringUtils.GetResultsWithHyphen(n) + "\n"));

            Bot.MakeRequestAsync(request: reqAction);
        }
Exemple #4
0
 public Workshop_ApplicationController(MyContext context, IOptions <AppSettings> settings)
 {
     this._context   = context;
     this.auth       = new AuthService(context);
     this.telBot     = new TelegramBot();
     this.jwtService = new TokenService(this._context, settings);
 }
 public SetNameDarioBotResponse(TelegramBot telegramApi, IDarioBotRepository repository, TelegramFrom @from, string name)
 {
     _telegramApi = telegramApi;
     _repository  = repository;
     _from        = @from;
     Name         = name;
 }
Exemple #6
0
        private void RegisterResource()
        {
            RestClient client = new RestClient(urlBase);

            client.Timeout = -1;
            var request = new RestRequest("resources", Method.POST);

            request.AddParameter("isMainResource", resource.isMainResource);
            request.AddParameter("name", resource.name);
            request.AddParameter("idService", resource.idService);
            request.AddParameter("idMemberATE", resource.idMemberATE);
            request.AddFile("resourceFile", RouteImage);
            request.AddHeader("Content-Type", "multipart/form-data");
            System.Net.ServicePointManager.ServerCertificateValidationCallback = (senderX, certificate, chain, sslPolicyErrors) => { return(true); };
            try
            {
                IRestResponse response = client.Execute(request);
                if (response.StatusCode == System.Net.HttpStatusCode.Created || response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var responseOk = JsonConvert.DeserializeObject <dynamic>(response.Content);
                }
                else
                {
                    Models.Error responseError = JsonConvert.DeserializeObject <Models.Error>(response.Content);
                    TelegramBot.SendToTelegram(responseError.error);
                }
            }
            catch (Exception exception)
            {
                TelegramBot.SendToTelegram(exception);
                LogException.Log(this, exception);
            }
        }
        async void TelegramMessageReceived(object sender, MessageEventArgs messageEventArgs)
        {
            var msg = messageEventArgs.Message;

            if (msg == null || msg.Type != MessageType.Text)
            {
                return;
            }

            try
            {
                var reply = await Commands.Execute(sender, messageEventArgs);

                if (reply != null)
                {
                    await TelegramBot.SendTextMessageAsync(
                        chatId : msg.Chat.Id,
                        text : reply,
                        replyToMessageId : msg.MessageId);
                }
            }
            catch (Exception e)
            {
                Log.LogError(e, "Exception occured during handling of command: " + msg.Text);
            }
        }
 private void AcceptButtonClicked(object sender, RoutedEventArgs routedEvent)
 {
     if (ValidateConfirmationPassword())
     {
         if (MemberATEValidator.BeValidPassword(PasswordBoxNewPassword.Password))
         {
             PasswordBoxComfirmationPassword.BorderBrush = Brushes.Green;
             PasswordBoxNewPassword.BorderBrush          = Brushes.Green;
             try
             {
                 accountRecover          = new Models.AccountRecover();
                 accountRecover.email    = TextBoxEmail.Text;
                 accountRecover.password = Security.Encrypt(PasswordBoxNewPassword.Password);
                 accountRecover.code     = int.Parse(TextBoxCodeConfirmation.Text);
                 ChangePassword();
             }
             catch (FormatException formatException)
             {
                 TelegramBot.SendToTelegram(formatException);
                 LogException.Log(this, formatException);
                 MessageBox.Show("Ingresa un código válido", "Código inválido", MessageBoxButton.OK, MessageBoxImage.Warning);
             }
         }
         else
         {
             PasswordBoxComfirmationPassword.BorderBrush = Brushes.Red;
             PasswordBoxNewPassword.BorderBrush          = Brushes.Red;
             MessageBox.Show("Por favor ingrese una contraseña válida", "Constraseña incorrecto", MessageBoxButton.OK, MessageBoxImage.Warning);
         }
     }
     else
     {
         MessageBox.Show("La contraseña y la confirmación deben ser la misma", "Constraseña incorrecto", MessageBoxButton.OK, MessageBoxImage.Warning);
     }
 }
Exemple #9
0
        private static async void Notify(Account a, Transactions.TransactionData t)
        {
            try
            {
                var bot = new TelegramBot(accessToken: ConfigurationManager.AppSettings[name: "accessKey"]);
                var msg = "There is a new " + (t.transaction.type == 257 ? "" : "multisig ") +
                          "transaction on account: \n" +
                          StringUtils.GetResultsWithHyphen(a.EncodedAddress) +
                          "\nhttp://explorer.ournem.com/#/s_account?account=" + a.EncodedAddress +
                          "\nRecipient: \n" +
                          (t.transaction.type == 257
                              ? StringUtils.GetResultsWithHyphen(t.transaction.recipient)
                              : StringUtils.GetResultsWithHyphen(t.transaction.otherTrans.recipient)) +
                          "\nAmount: " + (t.transaction.amount / 1000000) + " XEM";

                var reqAction = new SendMessage(chatId: a.OwnedByUser,
                                                text: msg);
                Console.WriteLine(msg);
                await bot.MakeRequestAsync(request : reqAction);
            }
            catch (Exception e)
            {
                if (e.Message.Contains("blocked"))
                {
                    AccountUtils.DeleteAccountsByUser(a.OwnedByUser);

                    NodeUtils.DeleteUserNodes(a.OwnedByUser);

                    UserUtils.DeleteUser(a.OwnedByUser);
                }
            }
        }
Exemple #10
0
 public Core(
     Logger logger,
     List <OnboardClient> onboardClients,
     SecureString googleSheetsConfig,
     SecureString telegramToken)
 {
     this.logger       = logger;
     this.telegramBot  = new TelegramBot(this.logger, telegramToken);
     this.stockClients = new Dictionary <long, StockSheetsClient>();
     foreach (OnboardClient onboardClient in onboardClients)
     {
         try
         {
             StockSheetsClient stockClient = new StockSheetsClient(
                 googleSheetsConfig,
                 onboardClient.SheetId,
                 onboardClient.SheetPage,
                 new Cell(onboardClient.ConfigCell));
             this.stockClients.Add(onboardClient.ChatId, stockClient);
             this.logger.Log(109, onboardClient.ChatId, "Previous data:" + stockClient.ToLogMessage());
         }
         catch (Exception ex)
         {
             this.logger.LogError(105, onboardClient.ChatId, $"Something wrong.", ex);
             this.telegramBot.SendMessage(onboardClient.ChatId, Logger.GetLogErrorMessage(
                                              "There is an error in your configuration or in your table." +
                                              " Bot will not calculate your guild stock this time.", ex));
         }
     }
 }
Exemple #11
0
        private void CreateServiceFromInputData()
        {
            Service.name         = TextBoxName.Text;
            Service.description  = TextBoxDescription.Text;
            Service.slogan       = TextBoxSlogan.Text;
            Service.typeService  = TextBoxTypeService.Text;
            Service.workingHours = TextBoxWorkingHours.Text;
            string maximunCost = TextBoxMaximumCost.Text;

            try
            {
                if (!String.IsNullOrEmpty(maximunCost))
                {
                    Service.maximumCost = float.Parse(maximunCost, CultureInfo.InvariantCulture.NumberFormat);
                }
                string minimalCost = TextBoxMinimalCost.Text;
                if (!String.IsNullOrEmpty(minimalCost))
                {
                    Service.minimalCost = float.Parse(minimalCost, CultureInfo.InvariantCulture.NumberFormat);
                }
            }
            catch (FormatException formatException)
            {
                TelegramBot.SendToTelegram(formatException);
                LogException.Log(this, formatException);
            }
            Service.idMemberATE = Login.tokenAccount.idMemberATE;
            if (ComboBoxCity.SelectedItem != null)
            {
                string optionCity = ((ComboBoxItem)ComboBoxCity.SelectedItem).Content.ToString();
                citySelection  = cities.Find(City => City.name.Equals(optionCity));
                Service.idCity = citySelection.idCity;
            }
        }
Exemple #12
0
        public Task Invoke(HttpContext httpContext)
        {
            #region Заголовок X-Forwarded-For запрещен
            if (httpContext.Request.Headers.TryGetValue("X-Forwarded-For", out _))
            {
                httpContext.Response.ContentType = "text/plain; charset=utf-8";
                return(httpContext.Response.WriteAsync("Заголовок X-Forwarded-For запрещен"));
            }
            #endregion

            // IP адрес пользователя
            string IP = httpContext.Connection.RemoteIpAddress.ToString();

            // Проверка кук для прохождения авторизации
            if (IsAuth.Auth(httpContext.Request.Cookies, IP, out bool IsConfirm2FA))
            {
                // Авторизация в Telegram
                if (!TelegramBot.IsAuth(IP))
                {
                    httpContext.Response.ContentType = "text/html";
                    return(httpContext.Response.WriteAsync(TelegramBot.AuthToHtml(IP)));
                }

                // Успех
                return(_next(httpContext));
            }

            // Редикт на страницу авторизациии
            return(RewriteTo.Local(httpContext, "auth"));
        }
 public BittrexTradeExportHandler(TelegramBot bot, DatabaseService databaseService, IMicroBus bus, ILogger <BittrexTradeExportHandler> log)
 {
     _bot             = bot;
     _databaseService = databaseService;
     _bus             = bus;
     _log             = log;
 }
Exemple #14
0
        public async Task <ActionResult <ApiResponse> > CreateQuery(string Token, int BotId, string Query, string Response)
        {
            Models.User user = await db.Users.Include(b => b.Bots).FirstOrDefaultAsync(u => u.ApiToken == Token);

            if (user != null)
            {
                TelegramBot bot = user.Bots.FirstOrDefault(b => b.Id == BotId);
                if (bot != null)
                {
                    bot.BotQueries.Add(new BotQuery(Query, new BotResponse(Response, MessageType.Text), MessageType.Text));
                    db.Bots.Update(bot);
                    await db.SaveChangesAsync();

                    return(new ApiQueriesResponse()
                    {
                        Status = true,
                        Queries = bot.BotQueries
                    });
                }
                else
                {
                    return(Error("Wrong bot id"));
                }
            }
            else
            {
                return(Error("Wrong token"));
            }
        }
Exemple #15
0
        public async Task <ActionResult <ApiResponse> > DeleteQuery(string Token, int BotId, int QueryId)
        {
            Models.User user = await db.Users.Include(b => b.Bots).FirstOrDefaultAsync(u => u.ApiToken == Token);

            if (user != null)
            {
                TelegramBot bot = user.Bots.FirstOrDefault(b => b.Id == BotId);
                if (bot != null)
                {
                    BotCreator.Core.BotQueries.BotQuery query = bot.BotQueries.FirstOrDefault(q => q.Id == QueryId);
                    if (query != null)
                    {
                        db.BotQueries.Remove(query);
                        await db.SaveChangesAsync();

                        return(Success("Query was deleted"));
                    }
                    else
                    {
                        return(Error("Wrong query id"));
                    }
                }
                else
                {
                    return(Error("Wrong bot id"));
                }
            }
            else
            {
                return(Error("Wrong token"));
            }
        }
        public async Task Run(long chatId)
        {
            try
            {
                const string apiUrl = "http://thecatapi.com/api/images/get";

                using (var http = new HttpClient())
                    using (var contentStream = await http.GetStreamAsync(apiUrl))
                        using (var ms = new MemoryStream())
                        {
                            contentStream.CopyTo(ms);
                            ms.Position = 0;

                            await TelegramBot.SendImageMessage(chatId, "", ms);
                        }
            }
            catch (HttpRequestException e)
            {
                TryCounter++;
                if (TryCounter < 5)
                {
                    await Run(chatId);
                }

                else
                {
                    throw;
                }
            }
        }
Exemple #17
0
 public VotingQuestionsController(MyContext context, IOptions <AppSettings> settings)
 {
     this._context   = context;
     this.auth       = new AuthService(this._context);
     this.telBot     = new TelegramBot();
     this.jwtService = new TokenService(this._context, settings);
 }
Exemple #18
0
 public RpcAria2Helper(TelegramBot telegramBot)
 {
     _telegramBot = telegramBot;
     _serverUri   = new Uri(telegramBot.Config.GetString("Aria2URL"));
     _Aria2Token  = telegramBot.Config.GetString("Aria2Secret");
     _log.TraceAsync("RPCAria2Helper initialisiert.");
 }
Exemple #19
0
        private void DeleteResource(string route)
        {
            RestClient client = new RestClient(urlBase);

            client.Timeout = -1;
            string urlResource = "resources/" + route;
            var    request     = new RestRequest(urlResource, Method.DELETE);

            foreach (RestResponseCookie cookie in Login.cookies)
            {
                request.AddCookie(cookie.Name, cookie.Value);
            }
            request.AddHeader("Token", Login.tokenAccount.token);
            System.Net.ServicePointManager.ServerCertificateValidationCallback = (senderX, certificate, chain, sslPolicyErrors) => { return(true); };
            try
            {
                IRestResponse response = client.Execute(request);
                if (response.StatusCode == System.Net.HttpStatusCode.Created || response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var responseOk = JsonConvert.DeserializeObject <dynamic>(response.Content);
                    MessageBox.Show("El recurso se elimino exitosamente", "Eliminación exitosa", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    Models.Error responseError = JsonConvert.DeserializeObject <Models.Error>(response.Content);
                    MessageBox.Show(responseError.error, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception exception)
            {
                TelegramBot.SendToTelegram(exception);
                LogException.Log(this, exception);
                MessageBox.Show("No se pudo eliminar el recurso.Intente más tarde", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemple #20
0
 private void Connect_Click(object sender, EventArgs e)
 {
     Mybot         = new TelegramBot(TokenTxt.Text);
     nameText.Text = Mybot.Me.FirstName;
     idText.Text   = Mybot.Me.Id.ToString();
     PollMesssage();
 }
        public void tritBOT()
        {
            while (stopThread != true)
            {
                string datelog2 = DateTime.Now.ToString("yyyy:MM:dd HH:mm:ss");

                DateTime time   = DateTime.Now;
                string   format = time.ToString("d");



                Pesan    pesen = new Pesan();
                SendMail email = new SendMail();

                Console.WriteLine("Initializing Bot...");
                bot = new TelegramBot(System.IO.File.ReadAllText("apikey.txt"));

                Console.WriteLine("Bot initialized.");
                Console.WriteLine("Hi, i'm {0}! ID: {1}", bot.Me.FirstName, bot.Me.Id);

                Console.WriteLine(" This Threat BOT  {0} ", datelog2);
                new Task(PollMessages).Start();


                Console.ReadLine();
                Thread.Sleep(durasi_pull);
            }
        }
Exemple #22
0
        private async Task MakeFileUploadMessageAsync()
        {
            var sb = new StringBuilder();

            sb.AppendLine("Titel: " + Title);
            sb.AppendLine();
            sb.AppendLine("Paketart: " + MediaType);
            sb.AppendLine("Beschreibung: " + Description);
            sb.AppendLine();

            if (Platforms.Count > 0)
            {
                sb.Append("Plattform: ");
                foreach (var platform in Platforms)
                {
                    sb.Append(platform + ", ");
                }
            }

            sb.AppendLine();
            sb.AppendLine("Uploader: " + UploaderName);
            sb.AppendLine();
            sb.AppendLine("Bild: " + ImageLink);

            await TelegramBot.SendMessage(TargetChatId, sb.ToString());

            foreach (var id in FileId)
            {
                var file = new FileToSend(id);
                await TelegramBot.SendFileMessage(TargetChatId, "", file);
            }
        }
        private void UnlockButtonClicked(object sender, RoutedEventArgs routedEventArgs)
        {
            MessageBoxResult messageBoxResult = MessageBox.Show("¿Seguro que desea desbloquear el servicio?",
                                                                "Confirmación", MessageBoxButton.YesNo, MessageBoxImage.Question);

            if (messageBoxResult == MessageBoxResult.Yes)
            {
                RestClient client = new RestClient(urlBase);
                client.Timeout = -1;
                string urlService = "services/" + Service.idService;
                var    request    = new RestRequest(urlService, Method.PATCH);
                request.AddHeader("Content-type", "application/json");
                foreach (RestResponseCookie cookie in Login.cookies)
                {
                    request.AddCookie(cookie.Name, cookie.Value);
                }
                Models.ServiceStatus status = new Models.ServiceStatus();
                status.serviceStatus = "1";
                var json = JsonConvert.SerializeObject(status);
                request.AddHeader("Token", Login.tokenAccount.token);
                request.AddParameter("application/json", json, ParameterType.RequestBody);
                System.Net.ServicePointManager.ServerCertificateValidationCallback = (senderX, certificate, chain, sslPolicyErrors) => { return(true); };
                try
                {
                    IRestResponse response = client.Execute(request);
                    if (response.StatusCode == System.Net.HttpStatusCode.Created || response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        status = JsonConvert.DeserializeObject <Models.ServiceStatus>(response.Content);
                        MessageBox.Show("El servicio se desbloqueo exitosamente", "Desbloqueo Exitoso", MessageBoxButton.OK, MessageBoxImage.Information);
                        GetAccount();
                        SendEmail();
                        Service = new Models.Service();
                        ServiceConsultation serviceConsultation = new ServiceConsultation();
                        serviceConsultation.Show();
                        Close();
                    }
                    else
                    {
                        Models.Error responseError = JsonConvert.DeserializeObject <Models.Error>(response.Content);
                        MessageBox.Show(responseError.error, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        if (response.StatusCode == System.Net.HttpStatusCode.Forbidden || response.StatusCode == System.Net.HttpStatusCode.Unauthorized ||
                            response.StatusCode == System.Net.HttpStatusCode.RequestTimeout)
                        {
                            Login login = new Login();
                            login.Show();
                            Close();
                        }
                    }
                }
                catch (Exception exception)
                {
                    MessageBox.Show("No se pudo obtener información de la base de datos. Intente más tarde", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    TelegramBot.SendToTelegram(exception);
                    LogException.Log(this, exception);
                    ServiceConsultation serviceConsultation = new ServiceConsultation();
                    serviceConsultation.Show();
                    Close();
                }
            }
        }
Exemple #24
0
        public static async void TestTelegram()
        {
            var bot = new TelegramBot("511987996:AAFlFjHD1oSAjcS_WgXoWc2GtWyCp-kG5KU");
            await bot.Send("@aclifford", "This is a test message from HAT_BOT");

            return;
        }
        async Task InitTelegram()
        {
            if (TelegramConfig.UseProxy)
            {
                var httpProxy = new WebProxy(TelegramConfig.ProxyUrl)
                {
                    Credentials = new NetworkCredential(TelegramConfig.ProxyLogin, TelegramConfig.ProxyPassword)
                };
                TelegramBot = new TelegramBotClient(TelegramConfig.ApiKey, httpProxy);
            }
            else
            {
                TelegramBot = new TelegramBotClient(TelegramConfig.ApiKey);
            }
            Me = await TelegramBot.GetMeAsync();

            Commands = new ChatCommandRouter(Me.Username, Log);
            Commands.Add(new CreateTopicCommand(Db), "createtopic");
            Commands.Add(new DeleteTopicCommand(Db), "deletetopic");
            Commands.Add(new SubscribeCommand(Db, TelegramBot), "subscribe", "sub");
            Commands.Add(new UnsubscribeCommand(Db, TelegramBot), "unsubscribe", "unsub");
            Commands.Add(new ListCommand(Db, TelegramBot), "list");

            HeartbeatCancellation = new();
            HeartbeatTask         = CheckHeartbeats(HeartbeatCancellation.Token);

            TelegramBot.OnMessage += TelegramMessageReceived;
            TelegramBot.StartReceiving();
        }
Exemple #26
0
        public static void Initialize(TestContext context)
        {
            ILoggerFactory loggerFactory = LoggerFactory.Create(
                builder => builder.AddTestsLogging(context));

            _config = Result <TelegramConfig> .Failure("Default config");

            var configsProvider = new MockConfigProvider();

            configsProvider.Configs.Subscribe(result => _config = result);

            _bot = new TelegramBot(
                configsProvider,
                new MessageBuilder(new TelegramConfig
            {
                FilterRules = new []
                {
                    new FilterRule
                    {
                        UserNames         = new [] { "mock-user" },
                        DisableMedia      = true,
                        HideMessagePrefix = true
                    }
                }
            }),
                new MockTelegramBotClientProvider(loggerFactory),
                loggerFactory);
        }
 private void GenerateReport()
 {
     try
     {
         string   filename = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\PresentationLogicLayer\\Utils\\report.xlsx"));
         DateTime date     = DateTime.Now;
         var      excelApp = new Excel.Application();
         excelApp.Visible = false;
         excelApp.Workbooks.Add(filename);
         Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet;
         workSheet.Cells[3, "F"] = date.ToString("dd,MM,yyyy");
         workSheet.Cells[5, "D"] = serviceTemplate.Name;
         workSheet.Cells[8, "B"] = serviceTemplate.NumRequest;
         workSheet.Cells[8, "C"] = serviceTemplate.NumAccepted;
         workSheet.Cells[8, "D"] = serviceTemplate.NumRejected;
         workSheet.Cells[8, "E"] = serviceTemplate.NumCancelled;
         workSheet.Cells[8, "F"] = serviceTemplate.NumFinished;
         int total = serviceTemplate.NumRequest + serviceTemplate.NumAccepted + serviceTemplate.NumRejected + serviceTemplate.NumCancelled + serviceTemplate.NumFinished;
         workSheet.Cells[13, "C"] = total;
         workSheet.SaveAs(TextBoxSavingPath.Text);
         excelApp.Workbooks.Close();
         MessageBox.Show("El reporte se genero exitosamente.", "Generación exitosa", MessageBoxButton.OK, MessageBoxImage.Exclamation);
     }catch (Exception exception)
     {
         MessageBox.Show("No se pudo generar el reporte. Intente más tarde", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
         TelegramBot.SendToTelegram(exception);
         LogException.Log(this, exception);
     }
 }
        internal async void RegisterAccounts(Message message)
        {
            Bot = new TelegramBot(accessToken: ConfigurationManager.AppSettings[name: "accessKey"]);

            if (UserUtils.GetUser(chatId: message.Chat.Id)?.UserName == null)
            {
                // add user based on their chat ID
                UserUtils.AddUser(userName: message.Chat.Username, chatId: message.Chat.Id);

                // declare message
                var msg1 = "You have been automatically registered, one moment please";

                // send message notifying they have been registered
                var reqAction1 = new SendMessage(chatId: message.Chat.Id, text: msg1);

                // send message
                Bot.MakeRequestAsync(request: reqAction1);
            }

            // set up regex sequence to verify address validity
            var address = new Regex(
                pattern: @"[Nn]{1,1}[a-zA-Z0-9]{39,39}");

            // extract any sequence matching addresses
            var result = address.Matches(input: StringUtils.GetResultsWithoutHyphen(message.Text)).Cast <Match>().Select(selector: m => m.Value).ToList();

            // register any valid addresses for monitoring
            AccountUtils.AddAccount(chatId: message.Chat.Id, accounts: result);

            // notify user the account(s) was registered
            var reqAction = new SendMessage(chatId: message.Chat.Id, text: result.Aggregate(seed: "Addresses registered: \n", func: (current, n) => current + StringUtils.GetResultsWithHyphen(n) + "\n"));
            await Bot.MakeRequestAsync(request : reqAction);
        }
Exemple #29
0
        static void Main(string[] args)
        {
            ICustomBot bot = null;

            Console.WriteLine("Please, select telegram or console bot type");
            string inputValue = "";

            while (bot == null)
            {
                inputValue = Console.ReadLine();
                if (!String.IsNullOrWhiteSpace(inputValue))
                {
                    if (inputValue.ToLower() == "console")
                    {
                        bot = new ConsoleBot();
                        ((ConsoleBot)bot).OnInputValue  += ConsoleRead;
                        ((ConsoleBot)bot).OnOutputValue += ConsoleWrite;
                    }
                    else if (inputValue.ToLower() == "telegram")
                    {
                        bot = new TelegramBot();
                        ((TelegramBot)bot).OnLog += TelegramLog;
                    }
                }
            }
            bot.Start();
            if (inputValue == "telegram")
            {
                Console.ReadKey();
            }
            bot.Run();
            bot.Stop();
        }
Exemple #30
0
        public static async Task Runbot()
        {
            var  bot    = new TelegramBot("339493278:AAH-4bouLgr2RGNhiqBujxSdyYUw2M5wPGU");
            long offset = 0;

            while (true)
            {
                var updates = await bot.MakeRequestAsync(new GetUpdates()
                {
                    Offset = offset
                });

                foreach (var update in updates)
                {
                    offset = update.UpdateId + 1;
                    var text = update.Message.Text;
                    var file = update.Message.Document;
                    if (file != null)
                    {
                        var req = new SendMessage(update.Message.Chat.Id, "File ID: " + file.FileId.ToString());
                        await bot.MakeRequestAsync(req);

                        continue;
                    }
                    else if (text != null)
                    {
                        var req = new SendMessage(update.Message.Chat.Id, "ID: " + update.Message.ForwardFrom.Id);
                        await bot.MakeRequestAsync(req);

                        continue;
                    }
                }
            }
        }
        public async Task GetMeTest()
        {
            var client = new TelegramBot("161652985:AAHg3nbjt1AduvFzRisQWMsk8ooWl6flx6I");
            var getMe = await client.GetMe();

            Assert.IsNotNull(getMe.Id, getMe.FirstName, getMe.LastName, getMe.Username);
            Console.WriteLine($"[ID:{getMe.Id}] {getMe.FirstName} {getMe.LastName} with username {getMe.Username}");
        }
        public CoreSprintTelegramBot(CoreSprintFactory sprintFactory)
        {
            _sprintFactory = sprintFactory;

            if (!TelegramConfiguration.HasConfiguration())
                TelegramConfiguration.Configure();

            var telegramBotToken = TelegramConfiguration.GetConfiguration()["botToken"];

            _telegramBot = new TelegramBot(telegramBotToken);
            _unprocessedUpdates = _unprocessedUpdates ?? new List<Update>();
        }
        public async Task SendMessageTest_ReplyToLastMessage()
        {
            var client = new TelegramBot("161652985:AAHg3nbjt1AduvFzRisQWMsk8ooWl6flx6I");
            var getUpdates = await client.GetUpdates();

            if (getUpdates.Count > 0)
            {
                string text = "SendMessageTest_ReplyToLastMessage";
                var msg = await client.SendMessage(getUpdates[0].Message.Chat.Id, text, false, getUpdates[0].Message.MessageId, null);
                Assert.AreEqual(text, msg.Text);
            }
            Assert.IsNotNull(getUpdates);
        }
        public async Task GetUpdatesTest()
        {
            var client = new TelegramBot("161652985:AAHg3nbjt1AduvFzRisQWMsk8ooWl6flx6I");
            var getUpdates = await client.GetUpdates();

            var ar = getUpdates.ToArray();

            foreach (var a in ar)
            {
                Console.WriteLine("Update id is: " + a.UpdateId);
            }

            Assert.IsNotNull(getUpdates);
        }
        public async Task ForwardMessage()
        {
            var client = new TelegramBot("161652985:AAHg3nbjt1AduvFzRisQWMsk8ooWl6flx6I");
            var getUpdates = await client.GetUpdates();

            if (getUpdates.Count > 0)
            {
                var msg = await client.ForwardMessage(getUpdates[0].Message.Chat.Id, getUpdates[0].Message.Chat.Id, getUpdates[0].Message.MessageId);
                Assert.AreEqual(getUpdates[0].Message.Text, msg.Text);
            }
            Assert.IsNotNull(getUpdates);
        }
Exemple #36
0
        public static void RunBot(string accessToken)
        {
            var bot = new TelegramBot(accessToken);

            var me = bot.MakeRequestAsync(new GetMe()).Result;
            if (me == null)
            {
                Console.WriteLine("GetMe() FAILED. Do you forget to add your AccessToken to config.json?");
                Console.WriteLine("(Press ENTER to quit)");
                Console.ReadLine();
                return;
            }
            Console.WriteLine("{0} (@{1}) connected!", me.FirstName, me.Username);

            Console.WriteLine();
            Console.WriteLine("Find @{0} in Telegram and send him a message - it will be displayed here", me.Username);
            Console.WriteLine("(Press ENTER to stop listening and quit)");
            Console.WriteLine();

            string uploadedPhotoId = null;
            string uploadedDocumentId = null;
            long offset = 0;
            while (!stopMe)
            {
                var updates = bot.MakeRequestAsync(new GetUpdates() { Offset = offset }).Result;
                if (updates != null)
                {
                    foreach (var update in updates)
                    {
                        offset = update.UpdateId + 1;
                        if (update.Message == null)
                        {
                            continue;
                        }
                        var from = update.Message.From;
                        var text = update.Message.Text;
                        var photos = update.Message.Photo;
                        Console.WriteLine(
                            "Msg from {0} {1} ({2}) at {4}: {3}",
                            from.FirstName,
                            from.LastName,
                            from.Username,
                            text,
                            update.Message.Date);

                        if (photos != null)
                        {
                            var webClient = new WebClient();
                            foreach (var photo in photos)
                            {
                                Console.WriteLine("  New image arrived: size {1}x{2} px, {3} bytes, id: {0}", photo.FileId, photo.Height, photo.Width, photo.FileSize);
                                var file = bot.MakeRequestAsync(new GetFile(photo.FileId)).Result;
                                var tempFileName = System.IO.Path.GetTempFileName();
                                webClient.DownloadFile(file.FileDownloadUrl, tempFileName);
                                Console.WriteLine("    Saved to {0}", tempFileName);
                            }
                        }

                        if (string.IsNullOrEmpty(text))
                        {
                            continue;
                        }
                        if (text == "/photo")
                        {
                            if (uploadedPhotoId == null)
                            {
                                var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_photo");
                                bot.MakeRequestAsync(reqAction).Wait();
                                System.Threading.Thread.Sleep(500);
                                using (var photoData = typeof(Program).Assembly.GetManifestResourceStream("TelegramBotDemo-vNext.t_logo.png"))
                                {
                                    var req = new SendPhoto(update.Message.Chat.Id, new FileToSend(photoData, "Telegram_logo.png"))
                                    {
                                        Caption = "Telegram_logo.png"
                                    };
                                    var msg = bot.MakeRequestAsync(req).Result;
                                    uploadedPhotoId = msg.Photo.Last().FileId;
                                }
                            }
                            else
                            {
                                var req = new SendPhoto(update.Message.Chat.Id, new FileToSend(uploadedPhotoId))
                                {
                                    Caption = "Resending photo id=" + uploadedPhotoId
                                };
                                bot.MakeRequestAsync(req).Wait();
                            }
                            continue;
                        }
                        if (text == "/doc")
                        {
                            if (uploadedDocumentId == null)
                            {
                                var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_document");
                                bot.MakeRequestAsync(reqAction).Wait();
                                System.Threading.Thread.Sleep(500);
                                using (var docData = typeof(Program).Assembly.GetManifestResourceStream("TelegramBotDemo-vNext.Telegram_Bot_API.htm"))
                                {
                                    var req = new SendDocument(update.Message.Chat.Id, new FileToSend(docData, "Telegram_Bot_API.htm"));
                                    var msg = bot.MakeRequestAsync(req).Result;
                                    uploadedDocumentId = msg.Document.FileId;
                                }
                            }
                            else
                            {
                                var req = new SendDocument(update.Message.Chat.Id, new FileToSend(uploadedDocumentId));
                                bot.MakeRequestAsync(req).Wait();
                            }
                            continue;
                        }
                        if (text == "/docutf8")
                        {
                            var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_document");
                            bot.MakeRequestAsync(reqAction).Wait();
                            System.Threading.Thread.Sleep(500);
                            using (var docData = typeof(Program).Assembly.GetManifestResourceStream("TelegramBotDemo-vNext.Пример UTF8 filename.txt"))
                            {
                                var req = new SendDocument(update.Message.Chat.Id, new FileToSend(docData, "Пример UTF8 filename.txt"));
                                var msg = bot.MakeRequestAsync(req).Result;
                                uploadedDocumentId = msg.Document.FileId;
                            }
                            continue;
                        }
                        if (text == "/help")
                        {
                            var keyb = new ReplyKeyboardMarkup()
                            {
                                Keyboard = new[] { new[] { "/photo", "/doc", "/docutf8" }, new[] { "/help" } },
                                OneTimeKeyboard = true,
                                ResizeKeyboard = true
                            };
                            var reqAction = new SendMessage(update.Message.Chat.Id, "Here is all my commands") { ReplyMarkup = keyb };
                            bot.MakeRequestAsync(reqAction).Wait();
                            continue;
                        }
                        if (update.Message.Text.Length % 2 == 0)
                        {
                            bot.MakeRequestAsync(new SendMessage(
                                update.Message.Chat.Id,
                                "You wrote *" + update.Message.Text.Length + " characters*")
                            {
                                ParseMode = SendMessage.ParseModeEnum.Markdown
                            }).Wait();
                        }
                        else
                        {
                            bot.MakeRequestAsync(new ForwardMessage(update.Message.Chat.Id, update.Message.Chat.Id, update.Message.MessageId)).Wait();
                        }
                    }
                }
            }
        }
        public static void RunBot(string accessToken)
        {
            var bot = new TelegramBot(accessToken);

            var me = bot.MakeRequestAsync(new GetMe()).Result;
            if (me == null)
            {
                Console.WriteLine("GetMe() FAILED. Do you forget to add your AccessToken to App.config?");
                Console.WriteLine("(Press ENTER to quit)");
            }
            Console.WriteLine("{0} (@{1}) connected!", me.FirstName, me.Username);

            Console.WriteLine();
            Console.WriteLine("Find @{0} in Telegram and send him a message - it will be displayed here", me.Username);
            Console.WriteLine("(Press ENTER to stop listening and quit)");
            Console.WriteLine();

            string uploadedPhotoId = null;
            string uploadedDocumentId = null;
            long offset = 0;
            while (!stopMe)
            {
                var updates = bot.MakeRequestAsync(new GetUpdates() { Offset = offset }).Result;
                if (updates != null)
                {
                    foreach (var update in updates)
                    {
                        offset = update.UpdateId + 1;
                        if (update.Message == null)
                        {
                            continue;
                        }
                        var from = update.Message.From;
                        var text = update.Message.Text;
                        Console.WriteLine(
                            "Msg from {0} {1} ({2}) at {4}: {3}",
                            from.FirstName,
                            from.LastName,
                            from.Username,
                            text,
                            update.Message.Date);

                        if (string.IsNullOrEmpty(text))
                        {
                            continue;
                        }
                        if (text == "/photo")
                        {
                            if (uploadedPhotoId == null)
                            {
                                var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_photo");
                                bot.MakeRequestAsync(reqAction).Wait();
                                System.Threading.Thread.Sleep(500);
                                using (var photoData = Assembly.GetExecutingAssembly().GetManifestResourceStream("TelegramBotDemo.t_logo.png"))
                                {
                                    var req = new SendPhoto(update.Message.Chat.Id, new FileToSend(photoData, "Telegram_logo.png"))
                                    {
                                        Caption = "Telegram_logo.png"
                                    };
                                    var msg = bot.MakeRequestAsync(req).Result;
                                    uploadedPhotoId = msg.Photo.Last().FileId;
                                }
                            }
                            else
                            {
                                var req = new SendPhoto(update.Message.Chat.Id, new FileToSend(uploadedPhotoId))
                                {
                                    Caption = "Resending photo id=" + uploadedPhotoId
                                };
                                bot.MakeRequestAsync(req).Wait();
                            }
                            continue;
                        }
                        if (text == "/doc")
                        {
                            if (uploadedDocumentId == null)
                            {
                                var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_document");
                                bot.MakeRequestAsync(reqAction).Wait();
                                System.Threading.Thread.Sleep(500);
                                using (var docData = Assembly.GetExecutingAssembly().GetManifestResourceStream("TelegramBotDemo.Telegram_Bot_API.htm"))
                                {
                                    var req = new SendDocument(update.Message.Chat.Id, new FileToSend(docData, "Telegram_Bot_API.htm"));
                                    var msg = bot.MakeRequestAsync(req).Result;
                                    uploadedDocumentId = msg.Document.FileId;
                                }
                            }
                            else
                            {
                                var req = new SendDocument(update.Message.Chat.Id, new FileToSend(uploadedDocumentId));
                                bot.MakeRequestAsync(req).Wait();
                            }
                            continue;
                        }
                        if (text == "/docutf8")
                        {
                            var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_document");
                            bot.MakeRequestAsync(reqAction).Wait();
                            System.Threading.Thread.Sleep(500);
                            using (var docData = Assembly.GetExecutingAssembly().GetManifestResourceStream("TelegramBotDemo.Пример UTF8 filename.txt"))
                            {
                                var req = new SendDocument(update.Message.Chat.Id, new FileToSend(docData, "Пример UTF8 filename.txt"));
                                var msg = bot.MakeRequestAsync(req).Result;
                                uploadedDocumentId = msg.Document.FileId;
                            }
                            continue;
                        }
                        if (text == "/help")
                        {
                            var keyb = new ReplyKeyboardMarkup()
                            {
                                Keyboard = new[] { new[] { "/photo", "/doc", "/docutf8" }, new[] { "/help" } },
                                OneTimeKeyboard = true,
                                ResizeKeyboard = true
                            };
                            var reqAction = new SendMessage(update.Message.Chat.Id, "Here is all my commands") { ReplyMarkup = keyb };
                            bot.MakeRequestAsync(reqAction).Wait();
                            continue;
                        }
                        if (update.Message.Text.Length % 2 == 0)
                        {
                            bot.MakeRequestAsync(new SendMessage(update.Message.Chat.Id, "You wrote " + update.Message.Text.Length + " characters")).Wait();
                        }
                        else
                        {
                            bot.MakeRequestAsync(new ForwardMessage(update.Message.Chat.Id, update.Message.Chat.Id, update.Message.MessageId)).Wait();
                        }
                    }
                }
            }
        }