Ejemplo n.º 1
0
 private async void BotClient_OnUpdate(object sender, Telegram.Bot.Args.UpdateEventArgs e)
 {
     if (e.Update.PollAnswer != null)
     {
         //await botClient.SendTextMessageAsync(chatId: Polls.FirstOrDefault(x=>x.PollId == e.Update.PollAnswer.PollId).ChatId, text:e.Update.PollAnswer.OptionIds);
         var chatId = Polls.FirstOrDefault(x => x.PollId == e.Update.PollAnswer.PollId);
         if (e.Update.PollAnswer.OptionIds.Length != 0 && chatId != null)
         {
             if (e.Update.PollAnswer.OptionIds[0] == 0)
             {
                 List <string> answers = new List <string>();
                 answers.Add("Bye");
                 answers.Add("I`m Bad !");
                 var id = await botClient.SendPollAsync(chatId : chatId.ChatId, question : "Why are you nice ?", answers, isAnonymous : false);
             }
             else if (e.Update.PollAnswer.OptionIds[0] == 1)
             {
                 List <string> answers = new List <string>();
                 answers.Add("Bye");
                 answers.Add("I`m Nice !");
                 var id = await botClient.SendPollAsync(chatId : chatId.ChatId, question : "Why are you bad ?", answers, isAnonymous : false);
             }
         }
     }
 }
Ejemplo n.º 2
0
        private async void BotClient_OnUpdate(System.Object sender, Telegram.Bot.Args.UpdateEventArgs e)
        {
            DataBase db = Singleton.GetInstance().Context;

            if (e.Update.PreCheckoutQuery != null)
            {
                await BotClient.AnswerPreCheckoutQueryAsync(e.Update.PreCheckoutQuery.Id);

                if (e.Update.PreCheckoutQuery.InvoicePayload == "Pay is correct")
                {
                    User user = db.GetUser(e.Update.PreCheckoutQuery.From.Id);
                    user.BanDate = System.DateTime.Now;
                    db.Save();
                    IsUnBan.ThisUnBan(BotClient, user);
                    await Task.Run(() => SetIncomeChannel(e.Update.PreCheckoutQuery.From.Id, e.Update.PreCheckoutQuery.TotalAmount / 100));
                }
                else if (e.Update.PreCheckoutQuery.InvoicePayload == "Balance is correct")
                {
                    AdUser adUser = db.GetAdUser(e.Update.PreCheckoutQuery.From.Id);
                    adUser.Balance += e.Update.PreCheckoutQuery.TotalAmount / 100;
                    db.Save();
                    await Task.Run(() => SetIncomeChannel(e.Update.PreCheckoutQuery.From.Id, e.Update.PreCheckoutQuery.TotalAmount / 100));
                }
                else if (e.Update.PreCheckoutQuery.InvoicePayload == "PostTemplate is correct")
                {
                    AdUser       adUser       = db.GetAdUser(e.Update.PreCheckoutQuery.From.Id);
                    PostTemplate postTemplate = db.GetTempalte(adUser.User.ID, adUser.EditingPostTemplateId);
                    postTemplate.IsPaid = true;
                    System.Object ob = await AdController.AssemblyTemplate(BotClient, postTemplate);

                    if (ob is Message)
                    {
                        Message       mes  = (Message)ob;
                        System.String text = mes.Text;
                        await BotClient.SendTextMessageAsync(CommandText.bufferChannelId, text);
                    }
                    else
                    {
                        List <InputMediaBase> inputMedias = (List <InputMediaBase>)ob;

                        await BotClient.SendMediaGroupAsync(CommandText.bufferChannelId, inputMedias);
                    }
                    IsDataTaken.IsCheck(BotClient, e.Update.PreCheckoutQuery.From.Id, postTemplate.PostTime.ToList());
                    db.Save();

                    await Task.Run(() => SetIncomeChannel(e.Update.PreCheckoutQuery.From.Id, e.Update.PreCheckoutQuery.TotalAmount / 100, postTemplate));
                }
                else if (e.Update.PreCheckoutQuery.InvoicePayload == "Pay Confirm User")
                {
                    User user = db.GetUser(e.Update.PreCheckoutQuery.From.Id);
                    user.PayConfirm = true;
                    user.PayDate    = System.DateTime.Today.AddMonths(1);
                    db.Save();

                    await Task.Run(() => SetIncomeChannel(e.Update.PreCheckoutQuery.From.Id, e.Update.PreCheckoutQuery.TotalAmount / 100));
                }
            }
        }
Ejemplo n.º 3
0
        private static void ReceiveBot_OnUpdate(object sender, Telegram.Bot.Args.UpdateEventArgs e)
        {
            string msg = e.Update.Message.Text;

            if (msg.ToUpper() == "/HELP")
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("/ord:Item:Position(1or2):Qty");
                sb.AppendLine("/app:xingapp:loginIndex(0-3)");

                var task = SendMessageAsync(sb.ToString());
            }
            else
            {
                if (msg.StartsWith("/"))
                {
                    var command = msg.Substring(1, 3).ToUpper();
                    if (command == "ORD")
                    {
                        //   /ORD:CL:1:1
                        string   commandStr   = msg.Substring(5);
                        string[] commandSplit = commandStr.Split(':');
                        string   itemCode     = commandSplit[0];
                        string   position     = commandSplit[1];
                        string   quantity     = commandSplit[2];

                        if ((itemCode.Length == 2 || itemCode.Length == 3) &&
                            position.Length == 1 &&
                            (quantity.Length > 0 && quantity.Length < 4))
                        {
                            SellBuy(itemCode, position, quantity);
                        }
                    }
                    else if (command == "APP")
                    {
                        string   commandStr   = msg.Substring(5);
                        string[] commandSplit = commandStr.Split(':');
                        string   appName      = commandSplit[0].ToUpper().Trim();
                        string   loginIndex   = commandSplit[1];
                        if (appName == "XINGAPP")
                        {
                            //C:\ABCProject\AUM\OM.PP\OM.PP.XingApp\bin\Debug\OM.PP.XingApp.exe 0
                            foreach (var process in Process.GetProcessesByName("OM.PP.XingApp"))
                            {
                                process.Kill();
                            }

                            System.Threading.Thread.Sleep(100);
                            var p = new System.Diagnostics.Process();
                            p.StartInfo.FileName  = @"C:\ABCProject\AUM\OM.PP\OM.PP.XingApp\bin\Debug\OM.PP.XingApp.exe";
                            p.StartInfo.Arguments = loginIndex;
                            p.Start();
                        }
                    }
                }
            }
        }
Ejemplo n.º 4
0
 private void TelegramService_OnUpdate(object sender, Telegram.Bot.Args.UpdateEventArgs e)
 {
     try
     {
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Process updates sent from the user.
        /// </summary>
        /// <param name="sender">The sender of the update</param>
        /// <param name="e">Event associated with the message</param>
        private static async void Client_OnUpdate(object sender, Telegram.Bot.Args.UpdateEventArgs e)
        {
            if (e is null)
            {
                FabricDi.Logger.LogErrorSource("There was an error while receiving updates");
                return;
            }

            await CoreDi.UpdateServices.ProcessUpdateAsync(e.Update.Message);
        }
Ejemplo n.º 6
0
        private void TClient_OnUpdate(object sender, Telegram.Bot.Args.UpdateEventArgs e)
        {
            Telegram.Bot.Types.Update u = e.Update;
            if (!SupportedTypes.Contains(u.Message.Type))
            {
                return;
            }
            string text = u.Message.Text;

            Console.WriteLine("Message received: " + text);
            this.OnMessageReceived(FromTelegramMessage(e.Update.Message));
        }
Ejemplo n.º 7
0
        private void OnBotUpd(object sender, Telegram.Bot.Args.UpdateEventArgs e)
        {
            long     chatId   = 0;
            string   chatName = "";
            ChatType chatType = ChatType.Private;

            UpdateType updType = e.Update.Type;

            switch (updType)
            {
            case UpdateType.ChannelPost:
                chatId   = e.Update.ChannelPost.Chat.Id;
                chatName = e.Update.ChannelPost.Chat.Title;
                chatType = ChatType.Channel;
                break;

            case UpdateType.Message:
                chatType = e.Update.Message.Chat.Type;
                chatId   = e.Update.Message.Chat.Id;
                switch (chatType)
                {
                case ChatType.Private:
                    chatName =
                        $"{e.Update.Message.Chat.FirstName} {e.Update.Message.Chat.LastName}";
                    break;

                case ChatType.Group:
                    chatName = e.Update.Message.Chat.Title;
                    break;
                }

                break;
            }

            if (chatId == 0 || telegramChannels
                .Select(channel => channel.ChatId).Contains(chatId))
            {
                return;
            }
            {
                DtoTelegramChannel channel =
                    new DtoTelegramChannel
                {
                    ChatId = chatId,
                    Name   = string.IsNullOrEmpty(chatName) ? "NoName" : chatName,
                    Type   = (int)chatType
                };

                channel.Id = (int)repository.CreateEntity(channel);
                UpdateDtoEntitiesList(telegramChannels);
            }
        }
Ejemplo n.º 8
0
        private void OnBotUpd(object sender, Telegram.Bot.Args.UpdateEventArgs e)
        {
            long       chatId   = 0;
            string     chatName = "";
            ChatType   chatType = ChatType.Private;
            UpdateType updType  = e.Update.Type;

            switch (updType)
            {
            case UpdateType.ChannelPost:
                chatId   = e.Update.ChannelPost.Chat.Id;
                chatName = e.Update.ChannelPost.Chat.Title;
                chatType = ChatType.Channel;
                break;

            case UpdateType.Message:
                chatType = e.Update.Message.Chat.Type;
                chatId   = e.Update.Message.Chat.Id;
                switch (chatType)
                {
                case ChatType.Private:
                    chatName = $"{e.Update.Message.Chat.FirstName} {e.Update.Message.Chat.LastName}";
                    break;

                case ChatType.Group:
                    chatName = e.Update.Message.Chat.Title;
                    break;
                }

                break;
            }

            if (chatId != 0 && !_telegramChannels.ContainsKey(chatId))
            {
                DtoTelegramChannel channel =
                    new DtoTelegramChannel
                {
                    ChatId = chatId,
                    Name   = string.IsNullOrEmpty(chatName) ? "NoName" : chatName,
                    Type   = (int)chatType
                };

                channel.Id = _repository.CreateEntity(channel);

                lock (this)
                {
                    _telegramChannels.TryAdd(channel.ChatId, channel);
                }
            }
        }
Ejemplo n.º 9
0
        static void Bot_OnUpdate(object sender, Telegram.Bot.Args.UpdateEventArgs e)
        {
            bool log = false;

            try
            {
                if (e.Update.Message != null)
                {
                    if (e.Update.Message?.Date == null || e.Update.Message.Date < Program.StartTime.AddSeconds(-5))
                    {
                        return;
                    }
                    Handler.HandleMessage(e.Update.Message);
                    if (e.Update.Message.From.Id != Settings.renyhp)
                    {
                        log = true;
                    }
                }
                if (e.Update.CallbackQuery != null)
                {
                    if (e.Update.CallbackQuery?.Message?.Date == null || e.Update.CallbackQuery.Message.Date < Program.StartTime.AddSeconds(-5))
                    {
                        return;
                    }
                    Handler.HandleCallback(e.Update.CallbackQuery);
                    if (e.Update.CallbackQuery.From.Id != Settings.renyhp)
                    {
                        log = true;
                    }
                }
            }
            catch (Exception ex)
            {
                LogError(ex);
            }

            if (log)
            {
                MessagesReceived++;
                LatestMessageTime = DateTime.UtcNow;
                UpdateMonitor     = true;
            }
            return;
        }
Ejemplo n.º 10
0
        private static async void On_Update(object sender, Telegram.Bot.Args.UpdateEventArgs e)
        {
            var     Client     = (TelegramBotClient)sender;
            iUpdate finder     = null;
            var     customdata = new Dictionary <string, object>();

            switch (e.Update.Type)
            {
            case UpdateType.Message:
            {
                finder = TBH.Variables.UpdatesList
                         .Where(x => x.Trigger.UpdateType == UpdateType.Message)
                         .FirstOrDefault(x => x.Trigger.TextTriggers.Any(c => c == e.Update.Message.Text.ToLower()));

                customdata.Add("LangCode", e.Update.Message.From.LanguageCode);
                break;
            }

            case UpdateType.CallbackQuery:
            {
                finder = TBH.Variables.UpdatesList
                         .Where(x => x.Trigger.UpdateType == UpdateType.CallbackQuery)
                         .FirstOrDefault(x => e.Update.CallbackQuery.Data.StartsWith(x.Trigger.TextTriggers[0]));

                customdata.Add("LangCode", e.Update.CallbackQuery.From.LanguageCode);
                break;
            }

            default:
                break;
            }

            using (Proccessor proccessor = new Proccessor(finder, Client, e.Update, customdata))
            {
                if (finder is null)
                {
                    return;
                }

                await proccessor.Proccess().ConfigureAwait(false);
            }
        }
Ejemplo n.º 11
0
        private static void ReceiveBot_OnUpdate(object sender, Telegram.Bot.Args.UpdateEventArgs e)
        {
            string msg = e.Update.Message.Text;

            var command = msg.Split(':');

            if (command.Length == 3)
            {
                string itemCode = command[0];
                string position = command[1];
                string quantity = command[2];

                if ((itemCode.Length == 2 || itemCode.Length == 3) &&
                    position.Length == 1 &&
                    (quantity.Length > 0 && quantity.Length < 4))
                {
                    SellBuy(itemCode, position, quantity);
                }
            }
        }
Ejemplo n.º 12
0
        private async void OnUpdate(Object sender, Telegram.Bot.Args.UpdateEventArgs e)
        {
            var db = Singleton.GetInstance().Context;

            if (e.Update.PreCheckoutQuery != null)
            {
                await BotClient.AnswerPreCheckoutQueryAsync(e.Update.PreCheckoutQuery.Id);

                if (e.Update.PreCheckoutQuery.InvoicePayload == "Pay is post")
                {
                    User user = db.LoadRecordById <User>("Users", e.Update.PreCheckoutQuery.From.Id);
                    Post post = db.LoadRecordById <Post>("Posts", user.PostId);
                    post.IsPay         = true;
                    post.IsPublication = true;

                    db.UpsertRecord("Posts", post.Id, post);

                    await Task.Run(() => BotClient.SendText(CommandName.Chat, post.PostText));
                }
            }
        }
Ejemplo n.º 13
0
        private static void Bot_OnUpdate(object sender, Telegram.Bot.Args.UpdateEventArgs e)
        {
            if (e.Update.ChannelPost == null)
            {
                return;
            }

            if (e.Update.ChannelPost.Text == null)
            {
                return;
            }

            string channelMsg = e.Update.ChannelPost.Text.ToLower().Trim();

            if (channelMsg.Contains("presale") || channelMsg.Contains("whitelist"))
            {
                if (DateTime.Now > lastWhitelistMsgDate.AddMinutes(3))
                {
                    //bot.SendTextMessageAsync(e.Update.ChannelPost.Chat, "in order to join our presale you have to chat with @SavixRobot and type /start to begin whitelist procedure", Telegram.Bot.Types.Enums.ParseMode.Html);
                    bot.SendTextMessageAsync(e.Update.ChannelPost.Chat, "our whitelist procedure for the presale will start soon, please watch for the relevant announcement", Telegram.Bot.Types.Enums.ParseMode.Html);
                    lastWhitelistMsgDate = DateTime.Now;
                }
            }
        }
Ejemplo n.º 14
0
 private static void Api_OnUpdate(object sender, Telegram.Bot.Args.UpdateEventArgs e)
 {
     total++;
     //do nothing at all.  We are simply clearing the update queue so the bot can catch up
 }
Ejemplo n.º 15
0
 protected void Api_OnUpdate(object sender, Telegram.Bot.Args.UpdateEventArgs e)
 {
 }
Ejemplo n.º 16
0
        private static void Client_OnUpdate(object sender, Telegram.Bot.Args.UpdateEventArgs e)
        {
            try
            {
                Update u = e.Update;
                #region Message Updates
                if (u.Message != null)
                {
                    #region Text messages
                    if (u.Message.Text != null)
                    {
                        #region Messages containing entities
                        if (u.Message.Entities.Count != 0)
                        {
                            #region Commands
                            if (u.Message.Entities[0].Type == MessageEntityType.BotCommand &&
                                u.Message.Entities[0].Offset == 0)
                            {
                                #region Commands only
                                if (u.Message.Entities[0].Length == u.Message.Text.Length)
                                {
                                    handleCommandOnly(msg: u.Message, cmd: u.Message.Text);
                                }
                                #endregion
                                #region Commands with arguments
                                else
                                {
                                    handleCommandArgs(msg: u.Message, cmd: u.Message.Text.Split(' ')[0]);
                                }
                                #endregion
                            }
                            #endregion
                        }
                        #endregion

                        #region Text messages handling
                        handleTextMessage(u.Message);
                        #endregion
                    }
                    #endregion

                    #region System messages
                    #region New member
                    if (u.Message.NewChatMember != null)
                    {
                        #region Bot added to group
                        if (u.Message.NewChatMember.Id == me.Id)
                        {
                            handleBotJoinedGroup(u.Message);
                        }
                        #endregion
                    }
                    #endregion
                    #endregion
                }
            }
            catch (Exception ex)
            {
                client.SendTextMessageAsync(flomsId, "An error has occurred: \n" + ex.ToString() + "\n"
                                            + ex.Message + "\n" + ex.StackTrace);
            }
            #endregion
        }
Ejemplo n.º 17
0
        private static void Bot_OnUpdate(object sender, Telegram.Bot.Args.UpdateEventArgs e)
        {
            string From;
            string text;
            long   ChatId;

            try
            {
                if (e.Update.Type == UpdateType.Message)
                {
                    ChatId = e.Update.Message.Chat.Id;
                    From   = e.Update.Message.From.Username;
                    text   = e.Update.Message?.Text;


                    #region Disable Repeat a Message
                    //try
                    //{
                    //    if (e.Updates.Count() > 1)
                    //    {

                    //        if (e.Update.Type == e.UpdateType.Messagee.Update)
                    //        {
                    //            if (e.Updates[0].Message.Text == e.Updates[1].Message.Text && e.Updates[0].Message.Chat.Id == e.Updates[1].Message.Chat.Id)
                    //                continue;
                    //        }
                    //    }
                    //}
                    //catch{

                    //}
                    #endregion



                    if (e.Update.Message.Type == MessageType.Text)
                    {
                        // adel :  75094324
                        if (text.ToLower().Equals("/start"))
                        {
                            Datae data = db.Dataes.AsNoTracking().FirstOrDefault();
                            using (Db d2 = new Db())
                            {
                                if (!d2.Users.Any(a => a.ChatID_bint == ChatId))
                                {
                                    Model.User us = new Model.User();
                                    try
                                    { us.Name_nvc = e.Update.Message.From.FirstName + " " + e.Update.Message.From.LastName; }
                                    catch { }
                                    try
                                    {
                                        us.UserName_nvc = e.Update.Message.From.Username;
                                    }
                                    catch { }
                                    us.StartDate_dt = DateTime.Now;
                                    us.ChatID_bint  = ChatId;
                                    d2.Users.Add(us);
                                    d2.SaveChanges();
                                }
                            }
                            SendMessageAsync(ChatId, data.About_nvc, Keyboard.Main);
                        }
                        else if (text.Equals(KeyItem.About))
                        {
                            Datae data = db.Dataes.AsNoTracking().FirstOrDefault();
                            SendMessageAsync(ChatId, data.About_nvc);
                        }
                        else if (text.Equals(KeyItem.Call))
                        {
                            Datae data = db.Dataes.AsNoTracking().FirstOrDefault();
                            SendMessageAsync(ChatId, data.Call_nvc);
                        }
                        else if (text.Equals(KeyItem.News))
                        {
                            Datae data = db.Dataes.AsNoTracking().FirstOrDefault();
                            SendMessageAsync(ChatId, data.News_nvc);
                        }
                        else if (text.Equals(KeyItem.SpecialSell))
                        {
                            SendMessageAsync(ChatId, "Special");
                        }
                        else if (text.Equals(KeyItem.PriceList))
                        {
                            SendMessageAsync(ChatId, "یکی از موارد زیر را انتخاب نمایید", Keyboard.PriceList);
                        }
                        else if (text.Equals(KeyItem.BackToMain))
                        {
                            SendMessageAsync(ChatId, "یکی از منو ها را انتخاب نمایید", Keyboard.Main);
                        }
                        else if (text.Equals(KeyItem.ViewImages))
                        {
                            int            PriceListID = db.UserCommands.Find(ChatId).PriceListID_int;
                            List <Picture> pics        = db.Pictures.Where(a => a.PriceList_int == PriceListID).ToList();
                            if (pics.Count == 0)
                            {
                                SendMessageAsync(ChatId, "هیچ تصویری برای این آیتم موجود نیست");
                            }
                            else
                            {
                                foreach (Picture p in pics)
                                {
                                    SendPhotoAsync(ChatId, p.Text_nvc, p.File_vb);
                                }
                            }
                        }
                        else if (text.Equals(KeyItem.ViewList))
                        {
                            string LastPriceList;
                            using (Db d2 = new Db()) {
                                LastPriceList = d2.UserCommands.Find(ChatId).LastPriceList_nvc;
                            }
                            PriceList pc = db.PriceLists.AsNoTracking().Where(a => a.Title_nvc.Equals(LastPriceList)).FirstOrDefault();
                            if (pc == null)
                            {
                                SendMessageAsync(ChatId, "چیزی برای نمایش یافت نشد");
                            }
                            else
                            {
                                if (pc.File_vb != null)
                                {
                                    SendDocumentAsync(ChatId, pc.Text_nvc, pc.File_vb, pc.FileName_nvc);
                                }
                                else
                                {
                                    SendMessageAsync(ChatId, pc.Title_nvc);
                                }
                            }
                        }
                        else if (text.Equals(KeyItem.Back))
                        {
                            SendMessageAsync(ChatId, "یکی از موارد زیر را انتخاب کنید", Keyboard.PriceList);
                        }
                        else
                        {
                            PriceList pc = db.PriceLists.AsNoTracking().Where(a => a.Title_nvc.Equals(text)).FirstOrDefault();
                            if (pc == null)
                            {
                                SendMessageAsync(ChatId, "چیزی برای نمایش یافت نشد");
                            }
                            else
                            {
                                UserCommand uc = db.UserCommands.Find(ChatId);
                                if (uc == null)
                                {
                                    db.UserCommands.Add(new UserCommand()
                                    {
                                        chatID_bint = ChatId, LastPriceList_nvc = text, PriceListID_int = pc.ID_int
                                    });
                                    db.SaveChanges();
                                }
                                else
                                {
                                    uc.LastPriceList_nvc = text;
                                    uc.PriceListID_int   = pc.ID_int;
                                    db.Entry(uc).State   = System.Data.Entity.EntityState.Modified;
                                    db.SaveChanges();
                                }
                                SendMessageAsync(ChatId, "یکی از گزینه های زیر را انتخاب کنید", Keyboard.Option);
                                //InlineKeyboardMarkup mark = new InlineKeyboardMarkup(new InlineKeyboardButton() { CallbackData = $"{pc.ID_int}_getimage", Text = "نمایش تصاویر" });
                                //if (pc.File_vb != null)
                                //    SendDocumentAsync(ChatId, pc.Text_nvc, pc.File_vb, pc.FileName_nvc, mark);
                                //else
                                //    SendMessageAsync(ChatId,pc.Title_nvc, mark);
                            }
                        }
                    }
                }
                //else if (e.Update.Type == UpdateType.CallbackQuery)
                //{
                //    ChatId = e.Update.CallbackQuery.From.Id;
                //    From = e.Update.CallbackQuery.From.Username;
                //    text = e.Update.CallbackQuery.Data;

                //    int PriceListID = text.Split('_')[0].ToInt();
                //    List<Picture> pics = db.Pictures.Where(a => a.PriceList_int == PriceListID).ToList();
                //    if (pics.Count == 0)
                //        SendMessageAsync(ChatId, "هیچ تصویری برای این آیتم موجود نیست");
                //    else
                //    {
                //        foreach (Picture p in pics)
                //        {
                //            SendPhotoAsync(ChatId, p.Text_nvc, p.File_vb);
                //        }
                //    }
                //}
            }
            catch (Exception c)
            {
                // ReportError(c,"Line 240,TripMethod,Recive Updates");
                OnMessageRecived(c.Message, ConsoleColor.Yellow);
            }
        }
        private async void TlBotClient_OnUpdate(object sender, Telegram.Bot.Args.UpdateEventArgs e)
        {
            try
            {
                string responseText;
                long   chatId;
                string userName;
                int    responseMessageId = 0;

                if (e.Update.CallbackQuery != null)
                {
                    responseText = e.Update.CallbackQuery.Data;
                    chatId       = e.Update.CallbackQuery.From.Id;
                    userName     = e.Update.CallbackQuery.From.Username;
                }
                else
                {
                    responseText      = e.Update.Message.Text;
                    chatId            = e.Update.Message.Chat.Id;
                    userName          = e.Update.Message.Chat.Username;
                    responseMessageId = e.Update.Message.MessageId;
                }

                var response = this.MessageProcess.TextMessageProcess(responseText, chatId.ToString(), userName, 2, MessengerType);


                if (!string.IsNullOrEmpty(response.StartMessageText))
                {
                    await _tlBotClient.SendTextMessageAsync(chatId, response.StartMessageText);
                }



                if (!string.IsNullOrEmpty(response.FilePath))
                {
                    using (var fileStream = new System.IO.FileStream(response.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        var file = new InputOnlineFile(fileStream, response.FileName);
                        switch (response.FileType)
                        {
                        case FileType.Audio:
                            await _tlBotClient.SendChatActionAsync(chatId, Telegram.Bot.Types.Enums.ChatAction.UploadAudio);

                            await _tlBotClient.SendAudioAsync(chatId, file);

                            break;

                        case FileType.Photo:
                            await _tlBotClient.SendChatActionAsync(chatId, Telegram.Bot.Types.Enums.ChatAction.UploadPhoto);

                            await _tlBotClient.SendPhotoAsync(chatId, file);

                            break;

                        case FileType.Video:
                            await _tlBotClient.SendChatActionAsync(chatId, Telegram.Bot.Types.Enums.ChatAction.UploadVideo);

                            await _tlBotClient.SendVideoAsync(chatId, file);

                            break;

                        default:
                            await _tlBotClient.SendChatActionAsync(chatId, Telegram.Bot.Types.Enums.ChatAction.UploadDocument);

                            await _tlBotClient.SendDocumentAsync(chatId, file);

                            break;
                        }
                    }
                }


                if (response.ResponseType == ResponseType.IsReply)
                {
                    await _tlBotClient.SendTextMessageAsync(chatId, response.Text, replyToMessageId : responseMessageId);
                }
                else if (response.ResponseType == ResponseType.TemplateSendMessage &&
                         response.Buttons.Count > 0)
                {
                    //if (this.MessengerType == MessengerType.Bale)
                    //{
                    //    await _tlBotClient.SendTextMessageAsync(chatId, response.Text, replyMarkup: new ReplyKeyboardMarkup(GetButtons(response.Buttons)));
                    //}
                    //else
                    //{
                    await _tlBotClient.SendTextMessageAsync(chatId, response.Text, replyMarkup : new InlineKeyboardMarkup(GetInlineButtons(response.Buttons)));

                    //}
                }
                else
                {
                    await _tlBotClient.SendTextMessageAsync(chatId, response.Text);
                }

                OnLogEvent(LogEntity.GetLogEntity(userName + " responsed" + "    " +
                                                  response.Text + "    " +
                                                  response.ResponseType + "    " +
                                                  response.Buttons.Count.ToString() ?? "0"));
            }
            catch (Exception ex)
            {
                OnLogEvent(LogEntity.GetLogEntity(ex));
            }
        }
Ejemplo n.º 19
0
 private static void Client_OnUpdate(object sender, Telegram.Bot.Args.UpdateEventArgs e)
 {
     //if (e.Update.Message != null)
     //    new Task(() => HandleUpdate(e.Update.Message)).Start();
 }
Ejemplo n.º 20
0
        private async void _telegramBotClient_OnUpdateAsync(object sender, Telegram.Bot.Args.UpdateEventArgs e)
        {
            User _usuarioTel = new User();

            Telegram.Bot.Types.Message _message = new Telegram.Bot.Types.Message();

            try
            {
                // Obtenemos
                _usuarioTel = e.Update.CallbackQuery != null ? e.Update.CallbackQuery.From : e.Update.Message.From;
                _message    = e.Update.CallbackQuery != null ? e.Update.CallbackQuery.Message : e.Update.Message;
                string valor = e.Update.CallbackQuery != null ? e.Update.CallbackQuery.Data : e.Update.Message.Text;

                if (!Directory.Exists($"C:\\bot\\{_usuarioTel.Id}"))
                {
                    Directory.CreateDirectory($"C:\\bot\\{_usuarioTel.Id}");
                }

                string ext         = string.Empty;
                string downloadUrl = string.Empty;

                lblDescargados.Text = $"Procesados: {++procesados:n2}";

                switch (_message.Type)
                {
                case MessageType.Document:
                    var  document     = _message.Document;
                    File fileDocument = await _telegramBotClient.GetFileAsync(document.FileId);

                    ext         = Path.GetExtension(fileDocument.FilePath);
                    downloadUrl = $"https://api.telegram.org/file/bot{txtToken.Text}/{fileDocument.FilePath}";
                    string documentFileName = $"C:\\bot\\{_usuarioTel.Id}\\{Guid.NewGuid()}{ext}";
                    using (WebClient webClient = new WebClient())
                    {
                        webClient.DownloadFile(new Uri(downloadUrl), documentFileName);
                    }

                    try
                    {
                        using (Stream stream = System.IO.File.OpenRead(documentFileName))
                        {
                            await _telegramBotClient.SendPhotoAsync(13707657, stream);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }

                    break;

                case MessageType.Photo:
                    PhotoSize photoSize = _message.Photo.OrderByDescending(x => x.FileSize).FirstOrDefault() ?? new PhotoSize();
                    File      filePhoto = await _telegramBotClient.GetFileAsync(photoSize.FileId);

                    ext         = Path.GetExtension(filePhoto.FilePath);
                    downloadUrl = $"https://api.telegram.org/file/bot{txtToken.Text}/{filePhoto.FilePath}";
                    string photoFilename = $"C:\\bot\\{_usuarioTel.Id}\\{Guid.NewGuid()}{ext}";
                    using (WebClient webClient = new WebClient())
                    {
                        webClient.DownloadFile(new Uri(downloadUrl), photoFilename);
                    }

                    try
                    {
                        using (Stream stream = System.IO.File.OpenRead(photoFilename))
                        {
                            await _telegramBotClient.SendPhotoAsync(13707657, stream);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }

                    break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ha ocurrido un error; {ex.Message}");
            }
        }