Beispiel #1
0
        public void Execute(IJobExecutionContext context)
        {
            TechnicalFanCoil technicalFanCoil = new TechnicalFanCoil();

            var status = technicalFanCoil.GetStatus2();

            bool machineOn = false;

            if (status[1] != 0)
            {
                machineOn = true;
            }

            if (status[2] != 0)
            {
                machineOn = true;
            }

            if (machineOn)
            {
                technicalFanCoil.TurnOffMotor1();
                technicalFanCoil.TurnOffMotor2();

                var bot = new Telegram.Bot.Api("208761880:AAHxUZCc5z0g2dJDrgbbMEWk7r1t_IoKiAw");

                var    chatIds = RecieveReportForTechnicalFanCoilChatIds();
                string report  = "Fancoil automatically switched off.";

                foreach (var id in chatIds)
                {
                    bot.SendTextMessage(id, report);
                    bot.SendTextMessage(id, technicalFanCoil.GetStatus());
                }
            }
        }
Beispiel #2
0
        static async void testApiAsync()
        {
            var Bot = new Telegram.Bot.Api("your API access Token");
            var me  = await Bot.GetMeAsync();

            System.Console.WriteLine("Hello my name is " + me.FirstName);
        }
Beispiel #3
0
 public Bot()
 {
     botApi = new Telegram.Bot.Api(TOKEN_API);
     tagvortoDoc = new XmlDocument();
     tagvorto = this.GetSingleWord();
     userList = new UserList();
     userList = this.getUsersFromFile();
     this.GetXml();
 }
Beispiel #4
0
        static void testApi()
        {
            var Bot    = new Telegram.Bot.Api("252156027:AAEwcfBNyngaR7FhGjH38JaFTyQ14M4hKhg");
            var me     = Bot.GetMeAsync().Result;
            var waaaat = Bot.GetUpdatesAsync().Result;

            //var res = Bot.SendTextMessageAsync().Result;
            System.Console.WriteLine("Hello my name is " + me.FirstName);
        }
Beispiel #5
0
        public TelegramApi(string token)
        {
            api = new Telegram.Bot.Api(token);
            api.UpdateReceived += (sender, updateEventArgs) =>
            {
                MessageReceived?.Invoke(sender, Converter.UpdateToMessage(updateEventArgs.Update));
            };

            Me = new UniveralBot.User(api.GetMe().Result.Username);
        }
Beispiel #6
0
        private static void Test()
        {
            var api = new Telegram.Bot.Api("Paste some key for debugging purposes");

            var flowEngine = new FlowEngine(api, new DatabaseStateProvider(@"Data Source=(localdb)\ProjectsV13;Initial Catalog=MafiaGM;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"), null);

            var mainMenu = flowEngine.AddCommand("start")
                           .EchoReply(new OneLanguageString("Welcome"));

            flowEngine.AddAnyInput()
            .EchoReply(new OneLanguageString("Please, type /Start to start"));
            mainMenu.AddCommand("help")
            .EchoReply(new OneLanguageString("No help for now"));
            mainMenu.AddCommand("sum")
            .EchoReply(new OneLanguageString("Provide A"))
            .AddAnyInput()
            .EchoReply(new OneLanguageString("Provide B (A is {0}"))
            .AddAnyInput()
            .AddDelegateInput(context => (int.Parse(context[0]) + int.Parse(context[1])).ToString())
            .EchoReply(new OneLanguageString("Result is {0}"))
            .Execute(context => context.Echo(context[1] + context[2], context.UserMessageIdOrZero)); //а тут сразу же показываем конкатенацию
            mainMenu.AddCommand("testPar", true)
            .EchoReply(new OneLanguageString("parameter is {0}"));
            mainMenu.AddCommandWithParameter("testAnyPar", new OneLanguageString("Please, enter value"))
            .ForEach(step => step.EchoReply(new OneLanguageString("Value is {0}")));

            int lastUpdate = 0;

            do
            {
                var updates = api.GetUpdates(lastUpdate + 1).Result;
                if (!updates.Any())
                {
                    Thread.Sleep(3000); continue;
                }
                foreach (var update in updates)
                {
                    IState state;
                    flowEngine.Process(update, null, out state);
                    ((DatabaseState)state).SaveAndDispose();
                    lastUpdate = update.Id;
                }
            } while (true);
        }
Beispiel #7
0
        public async Task <HttpResponseMessage> PostMessage(JObject jsonResponce)
        {
            var TelegramResponce = jsonResponce.ToObject <Update>();

            var _Bot = new Telegram.Bot.Api(_token);
            await _Bot.SendTextMessageAsync(TelegramResponce.Message.Chat.Id, "Привет  " + TelegramResponce.Message.From.FirstName + "  im BOTTTTTT");

            Image img  = Image.FromFile("C:\\image.png");
            var   buff = new byte[100]; // ImagingHelper.ImageToByteArray(img);

            System.IO.MemoryStream ms = new System.IO.MemoryStream(buff);

            await _Bot.SendPhotoAsync(TelegramResponce.Message.Chat.Id, new FileToSend("photo.png", ms));

            return(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("ok"),
            });
        }
Beispiel #8
0
        [HttpGet]                                                        // setting webhook
        public async Task <HttpResponseMessage> Get()
        {
            try
            {
                var _Bot = new Telegram.Bot.Api(_token);
                //await _Bot.SetWebhookAsync("https:/ /server.inmoloko.ru//Mall.Bot.Test/api/tbot"); // установка webHook
                await _Bot.SetWebhookAsync("https://server.inmoloko.ru/api/tbot"); // установка webHook

                return(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent("ok"),
                });
            }
            catch (Exception exc)
            {
                Logging.Logger.Error(exc);
                return(new HttpResponseMessage(HttpStatusCode.OK));
            }
        }
Beispiel #9
0
        protected void Application_Start()
        {
            try
            {
                AreaRegistration.RegisterAllAreas();
                GlobalConfiguration.Configure(WebApiConfig.Register);
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);


                Telegram.Bot.Api bot = new Telegram.Bot.Api("Your_Bot_Token");
                bot.SetWebhook("https://site.com/api/webhook").Wait();
            }
            catch
            {
                HttpRuntime.UnloadAppDomain();
                throw;
            }
        }
Beispiel #10
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            Bot = new Telegram.Bot.Api("");

            timer           = new Timer();
            timer.Interval  = 500;
            timer.Elapsed  += Timer_Elapsed;
            timer.AutoReset = false;
            timer.Start();
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById <Button>(Resource.Id.BottoneCount);

            button.Click += Button_Click;
            Button bottoneGo = FindViewById <Button>(Resource.Id.bottoneGo);

            bottoneGo.Click += BottoneGo_Click;
        }
Beispiel #11
0
        private void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            Database.SetInitializer(new MigrateDatabaseToLatestVersion <Context, Migrations.Configuration>());



            try
            {
                Telegram.Bot.Api bot = new Telegram.Bot.Api("438518161:AAG5xVKFbV4uLf_6CtbyocQhbBv7hHLyL5A");
                bot.SetWebhook("https://114c25f2.ngrok.io/api/Webhook").Wait();
                //UserConfog d = new UserConfog();
                UserConfog d = Singleton.Instance;
                d.StartTemeUser();
                MaperConfig ConfigInCtor = new MaperConfig();
            }
            catch
            {
                HttpRuntime.UnloadAppDomain();
            }
        }
Beispiel #12
0
        public async Task <HttpResponseMessage> PostMessage(JObject jsonResponce)
        {
            DateTime TimeToStartAnswer = DateTime.Now;
            var      telegramResponce  = jsonResponce.ToObject <Update>();

            Logging.Logger.Debug($"PostMessage message={jsonResponce}");

            if (telegramResponce == null)
            {
                Logging.Logger.Error("Пустой запрос");
                return(new HttpResponseMessage(HttpStatusCode.OK));
            }


            if (telegramResponce.Type == UpdateType.MessageUpdate)
            {
                var _Bot = new Telegram.Bot.Api(_token);

                await _Bot.SendChatActionAsync(telegramResponce.Message.Chat.Id, ChatAction.Typing);

                if (telegramResponce.Message.Text == null)
                {
                    await _Bot.SendTextMessageAsync(telegramResponce.Message.Chat.Id, "Простите, но я не поняла вас \U0001F614");
                }
                else
                {
                    try
                    {
                        // кэшируем
                        #region
                        string trimmedLoweredQuery = telegramResponce.Message.Text.ToLower().Trim(QueryAnaliser.splitters);
                        var    thisQuery           = new BotUserQuery {
                            IsError = 0
                        };

                        var mbFunctional    = new MallBotFunctional();
                        var mbDBHelper      = new MallBotDBHelper();
                        var mbApiFunctional = new MallBotApiTelegramFunctional();

                        string       MainCachedItemKey   = "MainDataOfBot";
                        string       RadugaCachedItemKey = "RadugaDataOfBot";
                        MallBotModel MainDataOfBot       = null;
                        MallBotModel RadugaDataOfBot     = null;

                        var dbMainContext   = new MallBotContext(); dbMainContext.Configuration.ProxyCreationEnabled = false;
                        var dbRadugaContext = new MallBotContext(1); dbMainContext.Configuration.ProxyCreationEnabled = false;

                        object MaindataFromCache   = MemoryCache.Default.Get(MainCachedItemKey, null);
                        object RadugadataFromCache = MemoryCache.Default.Get(RadugaCachedItemKey, null);

                        if (trimmedLoweredQuery == "update")
                        {
                            if (MaindataFromCache != null)
                            {
                                MemoryCache.Default.Remove(MainCachedItemKey, null);
                            }
                            if (RadugadataFromCache != null)
                            {
                                MemoryCache.Default.Remove(RadugaCachedItemKey, null);
                            }

                            MaindataFromCache   = null;
                            RadugadataFromCache = null;
                        }

                        if (MaindataFromCache == null || RadugadataFromCache == null)
                        {
                            List <int?> ids = new List <int?> {
                                3, 5
                            };
                            MainDataOfBot = new MallBotModel(dbMainContext, ids);

                            ids = new List <int?> {
                                1
                            };
                            RadugaDataOfBot = new MallBotModel(dbRadugaContext, ids);

                            string[]        TimeOfExpiration = ConfigurationManager.AppSettings["TimeOfExpiration"].ToString().Split(':');
                            CacheItemPolicy cip = new CacheItemPolicy()
                            {
                                AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddHours(int.Parse(TimeOfExpiration[0])).AddMinutes(int.Parse(TimeOfExpiration[1])).AddSeconds(int.Parse(TimeOfExpiration[2])))
                            };
                            MemoryCache.Default.Set(new CacheItem(MainCachedItemKey, (object)MainDataOfBot), cip);
                            MemoryCache.Default.Set(new CacheItem(RadugaCachedItemKey, (object)RadugaDataOfBot), cip);
                        }
                        else
                        {
                            MainDataOfBot   = (MallBotModel)MaindataFromCache;
                            RadugaDataOfBot = (MallBotModel)RadugadataFromCache;
                        }
                        #endregion
                        var botUsers = dbMainContext.BotUser.ToList();
                        var botUser  = botUsers.FirstOrDefault(x => x.BotUserTelegramID == telegramResponce.Message.Chat.Id.ToString());
                        QueryAnaliserResult answer    = null;
                        MallBotModel        DataOfBot = null;
                        var customers = MainDataOfBot.Customers;
                        customers.AddRange(RadugaDataOfBot.Customers);

                        var IsTutorial = true;
                        if (
                            #region
                            botUser == null ||
                            trimmedLoweredQuery == "place" ||
                            trimmedLoweredQuery == "место" ||
                            trimmedLoweredQuery == "сменить тц" ||
                            trimmedLoweredQuery == "тц" ||
                            botUser.CustomerName == "newuser" ||
                            trimmedLoweredQuery == "help" && (botUser.CustomerName == "newuser" || botUser.CustomerName == "empty") ||
                            trimmedLoweredQuery == "помощь" && (botUser.CustomerName == "newuser" || botUser.CustomerName == "empty")
                            #endregion
                            )
                        {
                            if (trimmedLoweredQuery == "help" || trimmedLoweredQuery == "помощь")
                            {
                                var message = MainDataOfBot.Texts.FirstOrDefault(x => x.Locale == botUser.Locale && x.Key == "%priorityhelp%").Text;
                                message = message.Replace("%place%", "/place");
                                message = BotTextHelper.SmileCodesReplace(message);
                                await _Bot.SendTextMessageAsync(telegramResponce.Message.Chat.Id, message);
                            }
                            else
                            {
                                if (botUser == null)
                                {
                                    dbMainContext = mbDBHelper.AddBotUser(ulong.Parse(telegramResponce.Message.Chat.Id.ToString()), 2, null, telegramResponce.Message.From.FirstName, telegramResponce.Message.From.LastName, 0, null, "ru_RU", false, dbMainContext);
                                    botUser       = dbMainContext.BotUser.FirstOrDefault(x => x.BotUserTelegramID == telegramResponce.Message.Chat.Id.ToString());
                                }

                                botUser.CustomerName = "empty";
                                if (botUser.LevelTutorial != 4)
                                {
                                    botUser.LevelTutorial = 0;
                                }
                                botUser.ModifiedDate = DateTime.Now;
                                dbMainContext.SaveChanges();

                                var message = MainDataOfBot.Texts.FirstOrDefault(x => x.Locale == botUser.Locale && x.Key == "%mallselect%").Text;
                                message = message.Replace("%mall1%", "1. " + customers[0].Name + "  " + customers[0].City);
                                message = message.Replace("%mall2%", "2. " + customers[1].Name + "  " + customers[1].City);
                                message = message.Replace("%mall3%", "3. " + customers[2].Name + "  " + customers[2].City);
                                message = BotTextHelper.SmileCodesReplace(message);
                                await _Bot.SendTextMessageAsync(telegramResponce.Message.Chat.Id, message);
                            }
                        }
                        else
                        {
                            if (botUser.CustomerName == "empty")
                            {
                                var qa  = new QueryAnaliser();
                                var res = mbFunctional.SearchCustomer(qa.NormalizeQuery(telegramResponce.Message.Text), customers);

                                if (res.Count != 0)
                                {
                                    var findedCustomer = customers.FirstOrDefault(x => x.CustomerID == res[0].ID);

                                    var message = MainDataOfBot.Texts.FirstOrDefault(x => x.Locale == botUser.Locale && x.Key == "%mallselectsucces%").Text;
                                    message = message.Replace("%findedmall%", findedCustomer.Name + "  " + findedCustomer.City);
                                    message = message.Replace("%place%", "/place");
                                    message = BotTextHelper.SmileCodesReplace(message);
                                    await _Bot.SendTextMessageAsync(telegramResponce.Message.Chat.Id, message);

                                    botUser.CustomerName = res[0].Name;
                                    dbMainContext.SaveChanges();
                                    if (botUser.LevelTutorial != 4)
                                    {
                                        answer = await mbApiFunctional.doTutorial(botUser, telegramResponce.Message.Text, _Bot, telegramResponce.Message.Chat.Id, dbMainContext, MainDataOfBot);
                                    }
                                }
                                else
                                {
                                    var message = MainDataOfBot.Texts.FirstOrDefault(x => x.Locale == botUser.Locale && x.Key == "%mallselectfail%").Text;
                                    message = message.Replace("%notfindedmall%", telegramResponce.Message.Text);
                                    message = BotTextHelper.SmileCodesReplace(message);
                                    await _Bot.SendTextMessageAsync(telegramResponce.Message.Chat.Id, message);
                                }
                            }
                            else
                            {
                                if (botUser.CustomerName == RadugaDataOfBot.Customers[0].Name)
                                {
                                    DataOfBot       = RadugaDataOfBot;
                                    DataOfBot.Texts = MainDataOfBot.Texts;
                                }
                                else
                                {
                                    DataOfBot = mbDBHelper.SelectData(MainDataOfBot, botUser, customers);
                                }

                                // Блок для описания команд
                                if (trimmedLoweredQuery.Contains("testfunc")) // команды для разработчиков
                                {
                                    await mbApiFunctional.doDebelopersCommands(trimmedLoweredQuery, DataOfBot, _Bot, telegramResponce.Message.Chat.Id);
                                }
                                else // команды для пользователей
                                {
                                    var message = "";
                                    switch (trimmedLoweredQuery)
                                    {
                                    case "start":
                                        message = MainDataOfBot.Texts.FirstOrDefault(x => x.Locale == botUser.Locale && x.Key == "%start%").Text;
                                        message = message.Replace("%help%", "/help");
                                        message = BotTextHelper.SmileCodesReplace(message);
                                        await _Bot.SendTextMessageAsync(telegramResponce.Message.Chat.Id, message);

                                        break;

                                    case "update":
                                        message = MainDataOfBot.Texts.FirstOrDefault(x => x.Locale == botUser.Locale && x.Key == "%cacheupdate%").Text;
                                        message = BotTextHelper.SmileCodesReplace(message);
                                        await _Bot.SendTextMessageAsync(telegramResponce.Message.Chat.Id, message);

                                        break;

                                    case "clear":
                                        botUser.LevelTutorial = 0;
                                        botUser.CustomerName  = "newuser";
                                        botUser.ModifiedDate  = DateTime.Now;
                                        dbMainContext.SaveChanges();

                                        message = MainDataOfBot.Texts.FirstOrDefault(x => x.Locale == botUser.Locale && x.Key == "%clear%").Text;
                                        message = BotTextHelper.SmileCodesReplace(message);
                                        await _Bot.SendTextMessageAsync(telegramResponce.Message.Chat.Id, message);

                                        break;

                                    case "skip":
                                        botUser.LevelTutorial = 4;
                                        botUser.ModifiedDate  = DateTime.Now;
                                        dbMainContext.SaveChanges();

                                        message = MainDataOfBot.Texts.FirstOrDefault(x => x.Locale == botUser.Locale && x.Key == "%skip%").Text;
                                        message = BotTextHelper.SmileCodesReplace(message);
                                        await _Bot.SendTextMessageAsync(telegramResponce.Message.Chat.Id, message);

                                        break;

                                    case "привет":
                                    case "hello":
                                    case "здравствуйте":
                                    case "пряффки":
                                    case "hi":

                                        message = MainDataOfBot.Texts.FirstOrDefault(x => x.Locale == botUser.Locale && x.Key == "%hello%").Text;
                                        message = BotTextHelper.SmileCodesReplace(message);
                                        await _Bot.SendTextMessageAsync(telegramResponce.Message.Chat.Id, message);

                                        break;

                                    case "пока":
                                    case "до свидания":
                                    case "спасибо":
                                    case "покеда":
                                    case "досвидули":
                                    case "большоеспасибо":
                                    case "прощай":
                                        message = MainDataOfBot.Texts.FirstOrDefault(x => x.Locale == botUser.Locale && x.Key == "%thkx%").Text;
                                        message = BotTextHelper.SmileCodesReplace(message);
                                        await _Bot.SendTextMessageAsync(telegramResponce.Message.Chat.Id, message);

                                        break;

                                    case "помощь":
                                    case "help":
                                    case "как это работает":
                                    case "хелп":
                                        message = MainDataOfBot.Texts.FirstOrDefault(x => x.Locale == botUser.Locale && x.Key == "%help%").Text;
                                        message = message.Replace("%place%", "/place");
                                        message = message.Replace("%tutorial%", "/tutorial");
                                        message = message.Replace("%help%", "/help");
                                        message = BotTextHelper.SmileCodesReplace(message);
                                        await _Bot.SendTextMessageAsync(telegramResponce.Message.Chat.Id, message);

                                        break;

                                    case "что делать":
                                    case "tutorial":
                                    case "обучение":
                                    case "туториал":
                                        answer = await mbApiFunctional.doTutorial(botUser, telegramResponce.Message.Text, _Bot, telegramResponce.Message.Chat.Id, dbMainContext, DataOfBot, true);

                                        break;

                                    default:
                                        if (botUser.LevelTutorial != 4)
                                        {
                                            answer = await mbApiFunctional.doTutorial(botUser, telegramResponce.Message.Text, _Bot, telegramResponce.Message.Chat.Id, dbMainContext, DataOfBot);
                                        }
                                        else
                                        {
                                            var mbFunctionalAnalizer = new MallBotFunctionalAnalizeTelegramHelper();
                                            answer = await mbFunctionalAnalizer.AnaliseDoWorkResult(telegramResponce.Message.Text, telegramResponce.Message.Chat.Id, DataOfBot, _Bot, botUser);

                                            IsTutorial = false;
                                        }
                                        break;
                                    }
                                }
                            }
                        }

                        //пишем  в базу запрос
                        if (botUser != null)
                        {
                            if (DataOfBot == null)
                            {
                                mbDBHelper.AddBotQuery(botUser, ulong.Parse(telegramResponce.Message.Chat.Id.ToString()), 2, answer, telegramResponce.Message.Text, IsTutorial, TimeToStartAnswer, thisQuery);
                            }
                            else
                            {
                                mbDBHelper.AddBotQuery(botUser, ulong.Parse(telegramResponce.Message.Chat.Id.ToString()), 2, answer, telegramResponce.Message.Text, IsTutorial, TimeToStartAnswer, thisQuery);
                            }
                        }

                        return(new HttpResponseMessage(HttpStatusCode.OK)
                        {
                            Content = new StringContent("ok"),
                        });
                    }
                    catch (Exception exc)
                    {
                        Logging.Logger.Error(exc);
                        return(new HttpResponseMessage(HttpStatusCode.OK));
                    }
                }
            }

            return(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("ok"),
            });
        }
Beispiel #13
0
 public Client(string _token)
 {
     token = _token;
     Api = new Telegram.Bot.Api(token);         
 }
Beispiel #14
0
 static void Main(string[] args)
 {
     Telegram.Bot.Api myBot = new Telegram.Bot.Api("139410021:AAHoQsUYiH_NiHV0vutnDWSLy1JEslIibz0");
     System.Threading.Tasks.Task<Telegram.Bot.Types.Update[]> _upd;
     _upd = myBot.GetUpdates();
 }
 private NotificationsBotInvoker()
 {
     bot = new Telegram.Bot.Api("133038323:AAFXVhA9Htj3p0a0Sl3hydt65Y7fl2AOVEI");
 }