Esempio n. 1
0
        public static void ActionStateSelected(UserState userState,
                                               TelegramContext db,
                                               Telegram.Bot.TelegramBotClient botClient,
                                               Update update)
        {
            switch (userState.State)
            {
            case (int)UserStatesEnum.Empty:    //Empty
                break;

            case (int)UserStatesEnum.AddBuildingName:    //AddCourse
                BuildingsManager.AddBuildingName(botClient, db, update.Message);
                break;

            case (int)UserStatesEnum.AddBuildingAddress:    //CoursesList
                BuildingsManager.AddBuildingAddress(botClient, db, update.Message, userState);
                break;

            case (int)UserStatesEnum.AddBuildingComment:    //AddCourseName
                BuildingsManager.AddBuildingComment(botClient, db, update.Message, userState);
                break;

            case (int)UserStatesEnum.AddBuildingPhoto:    //AddCourseName
                FilesManager.SaveFile(botClient, update.Message, userState.BuildingId);
                break;
            }
        }
Esempio n. 2
0
        private async void BW_TelegramLoop(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker tbw = sender as BackgroundWorker;
            var key = e.Argument as string;

            try
            {
                var bot = new Telegram.Bot.TelegramBotClient(key);
                await bot.SetWebhookAsync("");

                int offset = 0;

                while (true)
                {
                    var updates = await bot.GetUpdatesAsync(offset);

                    foreach (var update in updates)
                    {
                        bool res = await ProcessTelegramUpdate(bot, update);

                        offset = update.Id + 1;
                    }

                    System.Threading.Thread.Sleep(1000);    // to avoid CPU load
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error {ex.Message}");
                SetStatus("Работа остановлена по ошибке");
            }
        }
Esempio n. 3
0
        internal void GetUpdates()
        {
            _client = new Telegram.Bot.TelegramBotClient(_token);
            var me = _client.GetMeAsync().Result;

            if (me != null && !string.IsNullOrEmpty(me.Username))
            {
                int offset = 0;
                while (true)
                {
                    try
                    {
                        var updates = _client.GetUpdatesAsync(offset).Result;
                        if (updates != null && updates.Count() > 0)
                        {
                            foreach (var update in updates)
                            {
                                processUpdate(update);
                                offset = update.Id + 1;
                            }
                        }
                    }
                    catch (Exception ex) { Console.WriteLine(ex.Message); }

                    Thread.Sleep(1000);
                }
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Main loop of processing messages
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void TgBotWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var bgWorker = sender as BackgroundWorker;
                var bot      = new Telegram.Bot.TelegramBotClient(this.ApiKey);
                // clear webhook field
                await bot.SetWebhookAsync("");

                int offset = 0;         //TODO: need read from file or database

                while (true)
                {
                    var updates = await bot.GetUpdatesAsync(offset, allowedUpdates : new UpdateType[] { UpdateType.MessageUpdate });

                    foreach (var update in updates)
                    {
                        var resProc = await ProcessTgUpdate(bot, update);

                        offset = update.Id + 1;
                    }

                    System.Threading.Thread.Sleep(1000);
                    if (bgWorker?.CancellationPending ?? false)
                    {
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Log($"Exeption = {ex.ToString()}");
            }
        }
Esempio n. 5
0
        public async Task <MessageSendResult> Send(INeedSend message)
        {
            ChatId destId = null;
            var    user   = _dbContext.Users.SingleOrDefault(
                x => x.Username != null && x.Username.ToLower() == message.To.ToLower() ||
                x.PhoneNumber == _phoneHelper.Clear(message.To.ToLower()));

            if (user == null)
            {
                return(new MessageSendResult()
                {
                    Message = message,
                    IsSuccess = false,
                    Error = $"Не могу отправить сообщение пользователю {message.To}, т.к.он не добавил бота в телеграмме"
                });
            }
            destId = new ChatId(user.ChatId);
            var bot = new Telegram.Bot.TelegramBotClient(_configService.Config.BotApiKey);
            await bot.SendTextMessageAsync(destId, message.Text);

            return(new MessageSendResult()
            {
                Message = message,
                IsSuccess = true
            });
        }
Esempio n. 6
0
 private void button1_Click(object sender, EventArgs e)
 {
     BOT            = new Telegram.Bot.TelegramBotClient("657941583:AAGXlkhYUY6v9q71eCHb1BejDDY8Yq0yk1Y");
     BOT.OnMessage += BotOnMessageReceived;
     BOT.StartReceiving(new UpdateType[] { UpdateType.Message });
     button1.Enabled = false;
 }
Esempio n. 7
0
        public async Task <bool> Execute()
        {
            string botToken = _configuration.GetValue <string>("Bot:Token");

            Telegram.Bot.TelegramBotClient botClient = new Telegram.Bot.TelegramBotClient(botToken);
            BotSettingModel setting = LoadSetting();

            Telegram.Bot.Types.Update[] updates = await botClient.GetUpdatesAsync(setting.LastChatID + 1);

            string RegisterKey      = _configuration.GetValue <string>("Bot:RegisterKey");
            string DeleteAccountKey = _configuration.GetValue <string>("Bot:DeleteAccountKey");
            string GetResponseKey   = _configuration.GetValue <string>("Bot:GetResponseKey");

            foreach (Telegram.Bot.Types.Update update in updates)
            {
                string chatText = string.Empty;
                chatText = update?.Message?.Text ?? string.Empty;
                long chatId = update.Message.Chat.Id;

                if (chatText == RegisterKey)
                {
                    if (!setting.Receivers.Any(x => x == chatId.ToString()))
                    {
                        setting.Receivers.Add(chatId.ToString());
                        await botClient.SendTextMessageAsync(chatId, "به دریافت کنندگان اضافه شدی", replyMarkup : getKeyboard());
                    }
                    else
                    {
                        await botClient.SendTextMessageAsync(chatId, "قبلا اضافه شدی", replyMarkup : getKeyboard());
                    }
                }
                else if (chatText == DeleteAccountKey)
                {
                    if (setting.Receivers.Any(x => x == chatId.ToString()))
                    {
                        setting.Receivers.Remove(chatId.ToString());
                        await botClient.SendTextMessageAsync(chatId, "از دریافت کنندگان حذف شدی", replyMarkup : getKeyboard());
                    }
                    else
                    {
                        await botClient.SendTextMessageAsync(chatId, "توی لیست نیستی", replyMarkup : getKeyboard());
                    }
                }
                else if (chatText == "/start")
                {
                    await botClient.SendTextMessageAsync(chatId, "سلام، چیکار کنم برات ؟!", replyMarkup : getKeyboard());
                }
                else if (chatText == GetResponseKey)
                {
                    await _restApi.GetResponse(chatId);
                }
                else
                {
                    await botClient.SendTextMessageAsync(chatId, "نمیفهمم چی میگی", replyMarkup : getKeyboard());
                }
                setting.LastChatID = update.Id;
            }
            SaveSetting(setting);
            return(true);
        }
        public void ConfigureServices(IServiceCollection services)
        {
            //Usage of same ServiceCollection for telegram library and asp.net is bad idea.
            //At first I thought differently, but in practice this model was not very convenient if you need to use many bots on one server process.
            //More precisely, the problem is the common services collection between the bots themselves.
            //or use separate collections for asp and bots.
            //But in this example i use one collection to show how you can do it, because it's really can be difficult.
            //And i recommend to add bot library after all services, to override some settings in service collection.
            services
            .AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            var token = BotTokenResolver.GetToken();
            var bot   = new Telegram.Bot.TelegramBotClient(token, new QueuedHttpClient(TimeSpan.FromSeconds(1)));

            _botManager = new BotManager(bot, services);

            //Invoked synchronous.
            _botManager.ConfigureServices((servicesWrap) =>
            {
                servicesWrap.AddMvc(new Telegram.Bot.AspNetPipeline.Mvc.Builder.MvcOptions()
                {
                    //Useful for debugging.
                    CheckEqualsRouteInfo = true
                });

                //Logging service example with NLog you can see in IRO.Tests.Telegram.
            });
        }
Esempio n. 9
0
 void Button1Click(object sender, EventArgs e)
 {
     BOT            = new Telegram.Bot.TelegramBotClient("565638539:AAEBhReNYzHgTMFvhiC-OYECXjlLY4g3Xto");
     BOT.OnMessage += BotOnMessageReceived;
     BOT.StartReceiving(new UpdateType[] { UpdateType.Message });
     button1.Enabled = false;
 }
Esempio n. 10
0
 /// <summary>
 /// Process all telegram messages
 /// </summary>
 /// <param name="bot"></param>
 /// <param name="inUpd"></param>
 /// <returns></returns>
 async Task <bool> ProcessTelegramUpdate(Telegram.Bot.TelegramBotClient bot, Update inUpd)
 {
     SetStatus((inUpd.EditedMessage ?? inUpd.Message)?.From?.Id
               + ":" + inUpd.Message?.Text);
     try
     {
         #region //
         //if (inUpd.Type == Telegram.Bot.Types.Enums.UpdateType.EditedMessage)
         //{
         //    await bot.SendTextMessageAsync(inUpd.EditedMessage.Chat.Id, "Нехорошо редактировать сообщения", replyToMessageId: inUpd.EditedMessage.MessageId);
         //}
         //else if (inUpd.Message.Type == Telegram.Bot.Types.Enums.MessageType.TextMessage)
         //{
         //    await bot.SendTextMessageAsync(inUpd.Message.Chat.Id, $"Echo: {inUpd.Message.Text}", replyToMessageId: inUpd.Message.MessageId);
         //}
         #endregion
         var res = msproc.ProcessUpdate(inUpd);
         res?.ApplyToBot(bot);
     }
     catch (Exception ex)
     {
         SetStatus($"Message process error: {inUpd?.Id}");
     }
     return(true);
 }
Esempio n. 11
0
 private void button1_Click(object sender, EventArgs e)
 {
     BOT            = new Telegram.Bot.TelegramBotClient("508495921:AAHbY2MwO1Gmh6SSOkVO-YoM6oL_vqTTuKY");
     BOT.OnMessage += BotOnMassageReceived;
     BOT.StartReceiving(new UpdateType[] { UpdateType.Message });
     button1.Enabled = false;
 }
Esempio n. 12
0
 public TelegramBotControlerSender(Telegram.Bot.TelegramBotClient bot)
 {
     modelUser            = new ModelUser();
     modelVulnerabilityDB = new ModelVulnerabilityDB();
     view     = new TelegramBotView();
     this.bot = bot;
 }
Esempio n. 13
0
        public BotController(Config config)
        {
            if (string.IsNullOrEmpty((config.ProxyHost)))
            {
                _bot = new Telegram.Bot.TelegramBotClient(config.Token);
            }
            else
            {
                IWebProxy webProxy;
                if (string.IsNullOrEmpty(config.ProxyUserName))
                {
                    webProxy = new WebProxy()
                    {
                        Address = new Uri(config.ProxyHost)
                    }
                }
                ;
                else
                {
                    webProxy = new WebProxy()
                    {
                        Address = new Uri(config.ProxyHost),
                        UseDefaultCredentials = false,
                        Credentials           = new NetworkCredential(config.ProxyUserName, config.ProxyPass)
                    }
                };

                _bot = new Telegram.Bot.TelegramBotClient(config.Token, webProxy);
            }
        }
Esempio n. 14
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            var token = BotTokenResolver.GetToken();
            var bot   = new Telegram.Bot.TelegramBotClient(
                token,
                new QueuedHttpClient(TimeSpan.FromSeconds(1))
                );

            _botManager = new BotManager(bot);

            //Invoked synchronous.
            _botManager.ConfigureServices((servicesWrap) =>
            {
                //Init our LiteDB.
                servicesWrap.Services.AddLiteDataAccessLayer();
                servicesWrap.Services.AddSingleton <IGameLogicService, GameLogicService>();

                servicesWrap.AddMvc(new Telegram.Bot.AspNetPipeline.Mvc.Builder.MvcOptions()
                {
                    //Useful for debugging.
                    CheckEqualsRouteInfo = true
                });
            });
        }
Esempio n. 15
0
        public async Task <IActionResult> NewMessage([FromForm] NewTelegramMessage newTelegramMessage)
        {
            try
            {
                _logger.LogInformation($"{newTelegramMessage.ChatId} : {newTelegramMessage.Text}");

                var botClient = new Telegram.Bot.TelegramBotClient(newTelegramMessage.BotToken);
                var me        = await botClient.GetMeAsync();

                if (newTelegramMessage.File != null)
                {
                    var resultPhotoMessage = await botClient.SendPhotoAsync(newTelegramMessage.ChatId, new InputMedia(newTelegramMessage.File.OpenReadStream(), newTelegramMessage.File.FileName), newTelegramMessage.Text);

                    return(Ok(resultPhotoMessage.MessageId));
                }
                else
                {
                    var resultTextMessage = await botClient.SendTextMessageAsync(newTelegramMessage.ChatId, newTelegramMessage.Text);

                    return(Ok(resultTextMessage.MessageId));
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
                return(BadRequest(e.Message));
            }
        }
        public async Task sentTelegram(string filename, string locationStr, int locationIndex)
        {
            try
            {
                var        bot        = new Telegram.Bot.TelegramBotClient("*******************");
                List <int> ChatIDList = _context.LocationTelegram.Where(x => x.LocationIndex == locationIndex).Select(x => x.ChatID).ToList();

                foreach (int chatID in ChatIDList)
                {
                    await bot.SendTextMessageAsync(chatID, "From: SkyTech Mask Monitoring System");

                    await bot.SendTextMessageAsync(chatID, "Subject: Notification of people without mask");

                    await bot.SendTextMessageAsync(chatID, "Location: " + locationStr);

                    await bot.SendTextMessageAsync(chatID, "Date Time: " + DateTime.Now);

                    await bot.SendTextMessageAsync(chatID, "A person not wearing mask is discovered in the premises.<br/> This is a system generated email. Please do not reply.");

                    using (Stream stream = System.IO.File.OpenRead(filename))
                    {
                        await bot.SendPhotoAsync(chatID, stream);
                    }
                }
            } catch (Exception ex)
            {
                Debug.WriteLine("Send telegram");
                Debug.WriteLine(ex.InnerException);
            }
        }
        public static async Task Main()
        {
            try
            {
                while (true)
                {
                    try
                    {
                        Bot = new Telegram.Bot.TelegramBotClient("place_your_BOT_API_Token_Here");
                        BOTAuthentication = new TelegramAuthentication();

                        Bot.OnMessage       += BotOnMessageReceived;
                        Bot.OnMessageEdited += BotOnMessageReceived;
                        Bot.OnReceiveError  += BotOnReceiveError;

                        Bot.StartReceiving(Array.Empty <UpdateType>());

                        Console.ReadLine();
                    }
                    catch (Exception e)
                    {
                        Thread.Sleep(1000);
                    }
                }
            }
            catch (Exception e)
            {
                Thread.Sleep(2000);
            }
        }
        public MessageClient(String APIKey, Telegram.Bot.TelegramBotClient Client)
        {
            this.APIKey         = APIKey;
            this.TelegramClient = Client;

            Prepare();
        }
Esempio n. 19
0
        public TelegramHostedService(EmployeeProvider employeeProvider, ILogger <TelegramHostedService> logger, SqlServer sqlServer, IConfiguration config)
        {
            this._config = Startup.Config.UserBot;

            this._employeeProvider = employeeProvider;
            this._logger           = logger;
            this._sqlServer        = sqlServer;

            if (this._config.ApiUrl != null)
            {
                _httpClient = new HttpClient(new ProxyMessageHandler(this._config.ApiUrl));
            }
            else
            {
                _httpClient = new HttpClient();
            }

            this._cts       = new CancellationTokenSource();
            _telegramClient = new Telegram.Bot.TelegramBotClient(this._config.Token, _httpClient);

            if (!TimeSpan.TryParse(this._config.TimeToCancelTurns, out this._timeToCancelTurns))
            {
                this._timeToCancelTurns = TimeSpan.FromHours(6);
            }
        }
Esempio n. 20
0
 public BotCore(String ApiKey)
 {
     _apiKey = ApiKey;
     _bot    = new Telegram.Bot.TelegramBotClient(_apiKey);
     BotInit();
     Console.ReadLine();
 }
Esempio n. 21
0
        public Bottu(string Token, string baseApiAddress)
        {
            AutoResetEvent are = new AutoResetEvent(false);

            client       = new Telegram.Bot.TelegramBotClient(Token);
            MediaWikiApi = new HttpClient
            {
                BaseAddress = new Uri(baseApiAddress)
            };

            var InlineObservable = Observable.FromEventPattern <InlineQueryEventArgs>(c => client.OnInlineQuery += c, c => client.OnInlineQuery -= c);

            InlineObservable
            .Throttle(TimeSpan.FromMilliseconds(100))
            .Where(c => c?.EventArgs?.InlineQuery != null && !string.IsNullOrWhiteSpace(c.EventArgs.InlineQuery.Query))
            .Select(c => c.EventArgs.InlineQuery)
            .Select(c => Observable.FromAsync(async() => await ProcessInline(c)))
            .Concat()
            .Subscribe();

            client.StartReceiving(new[] { UpdateType.InlineQuery });

            Console.WriteLine("Started.");

            are.WaitOne();

            client.StopReceiving();
            Console.WriteLine("Stopped.");
        }
Esempio n. 22
0
 void Button1Click(object sender, EventArgs e)
 {
     BOT            = new Telegram.Bot.TelegramBotClient("455535082:AAGeMMob7ty-q_QFSN4kV2icxt-L7_7PGr0"); //"вставь сюда свой токен");
     BOT.OnMessage += BotOnMessageReceived;
     BOT.StartReceiving(new UpdateType[] { UpdateType.MessageUpdate });
     button1.Enabled = false;
     l1 = label1;
 }
Esempio n. 23
0
 public Worker(ILogger <Worker> logger, TelegramWorkerOptions telegramWorkerOptions)
 {
     _logger    = logger;
     _botClient = new Telegram.Bot.TelegramBotClient(telegramWorkerOptions.APIKey);
     _cards     = JsonImporter.JsonImporter.ReadCardsFromJson();
     _botClient.OnInlineQuery += _botClient_OnInlineQuery;
     _botClient.StartReceiving();
 }
Esempio n. 24
0
 public static void StateControl(Telegram.Bot.TelegramBotClient botClient, Update update)
 {
     using (TelegramContext db = new TelegramContext())
     {
         var userState = db.UserStates.Where(x => x.User.Id == update.Message.From.Id).SingleOrDefault();
         ActionStateSelected(userState, db, botClient, update);
     }
 }
Esempio n. 25
0
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);


            Telegram.Bot.TelegramBotClient bot = new Telegram.Bot.TelegramBotClient("438518161:AAG5xVKFbV4uLf_6CtbyocQhbBv7hHLyL5A");
            bot.SetWebhookAsync("https://f5dbfba1.ngrok.io/api/webhook").Wait();
        }
        public async static Task <bool> sendMessage(string telegram_id, string message)
        {
            var Bot = new Telegram.Bot.TelegramBotClient(bot_id);

            Telegram.Bot.Types.Message msg = await Bot.SendTextMessageAsync(244853182, message);

            return(true);
        }
    public TextMessageClient()
    {
        //Write your own logic to get the token
        //Or accept the token as an argument of constructor.
        var token = Guid.NewGuid().ToString();

        client = new Telegram.Bot.TelegramBotClient(token);
    }
Esempio n. 28
0
        public async Task <IActionResult> DeleteHook()
        {
            var token = configuration.GetValue <string>("TelegramToken");

            var client = new Telegram.Bot.TelegramBotClient(token, httpClient);
            await client.DeleteWebhookAsync();

            return(RedirectToAction("Index"));
        }
Esempio n. 29
0
 public TelegramUtil(Client client, Telegram.Bot.TelegramBotClient telegram, ISettings settings, Inventory inv)
 {
     _client = client;
     _telegram = telegram;
     _clientSettings = settings;
     _inventory = inv;
     DoLiveStats(settings);
     DoInformation();
 }
Esempio n. 30
0
 public TelegramUtil(Client client, Telegram.Bot.TelegramBotClient telegram, ISettings settings, Inventory inv)
 {
     _client         = client;
     _telegram       = telegram;
     _clientSettings = settings;
     _inventory      = inv;
     DoLiveStats(settings);
     DoInformation();
 }
Esempio n. 31
0
        public TelegrammReciever(string key)
        {
            if (key == null)
            {
                throw new NullReferenceException();
            }

            botClient = new Telegram.Bot.TelegramBotClient(key);
        }
Esempio n. 32
0
        public async Task PostToChannel(Comment comment)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(token))
                    return;

                var api = new Telegram.Bot.TelegramBotClient(token);
                
                var text = GetChannelPostText(comment);
                await api.SendTextMessageAsync(channel, text, parseMode: ParseMode.Markdown, disableWebPagePreview: true);
            }
            catch (Exception e)
            {
                log.Error(e);
                ErrorLog.GetDefault(HttpContext.Current).Log(new Error(e));
            }
        }
Esempio n. 33
0
        public TelegramUtil(Client client, Telegram.Bot.TelegramBotClient telegram, ISettings settings, Inventory inv)
        {
            instance = this;
            _client = client;
            _telegram = telegram;
            _clientSettings = settings;
            _inventory = inv;

            Array values = Enum.GetValues(typeof(TelegramUtilInformationTopics));
            foreach (TelegramUtilInformationTopics topic in values)
            {
                _informationDescription[topic] = TranslationHandler.GetString(_informationDescriptionIDs[topic], _informationDescriptionDefault[topic]);
                _information[topic] = false;
            }

            DoLiveStats(settings);
            DoInformation();
        }