Ejemplo n.º 1
0
        public async Task UpdateMessages()
        {
            long offset = 0;

            while (!_stopTelegram)
            {
                var updates = _telegram.MakeRequestAsync(new GetUpdates()
                {
                    Offset = offset
                }).Result;
                if (updates != null)
                {
                    foreach (var update in updates)
                    {
                        offset = update.UpdateId + 1;
                        if (update.Message == null)
                        {
                            continue;
                        }
                        _telegramMessages.Enqueue(update);
                    }
                    await UseMessage();
                }
            }
        }
Ejemplo n.º 2
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;
                    }
                }
            }
        }
Ejemplo n.º 3
0
        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);
        }
Ejemplo n.º 4
0
        public async void UpdateMessagesWorker()
        {
            long offset = 0;
            int  delay  = 2000;

            while (!StopTelegram)
            {
                try
                {
                    var updates = await TelegramBot.MakeRequestAsync(new GetUpdates()
                    {
                        Offset = offset
                    });

                    if (updates != null)
                    {
                        if (FirstMessageUpdate)
                        {
                            if (updates.Length > 1)
                            {
                                if (updates[(updates.Length - 1)].Message == null)
                                {
                                    continue;
                                }
                                TelegramMessages.Enqueue(updates[updates.Length - 1]);
                            }
                            FirstMessageUpdate = false;
                        }
                        else if (FirstMessageUpdate == false)
                        {
                            foreach (var update in updates)
                            {
                                offset = update.UpdateId + 1;
                                if (update.Message == null)
                                {
                                    continue;
                                }
                                TelegramMessages.Enqueue(update);
                            }
                        }
                        if (delay > 2000)
                        {
                            delay = 2000;
                        }
                    }
                }
                catch (Exception ex)
                {
                    EventDispatcher.Send(new TelegramMessageEvent
                    {
                        Message = "Error during request to api.telegram.com, retry in 30 sec..."
                    });
                    Logger.Write($"[TLGRM ERROR] {ex.Message}");
                    delay = 30000;
                }
                await Task.Delay(delay);
            }
            _started = false;
        }
Ejemplo n.º 5
0
        static async Task MainLoop()
        {
            var bot = new TelegramBot(Token);
            var me  = await bot.MakeRequestAsync(new GetMe());

            Console.WriteLine("[" + DateTime.Now + "]" + " | " + "Bot: [" + me.Username + "] Started.");
            long offset = 0;

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

                    foreach (var update in updates)
                    {
                        string Text = update.Message.Text;
                        string User = update.Message.From.Username;
                        if (Text.Length > 15 - 1)
                        {
                            Text = Text.Substring(0, 15) + "...";
                        }
                        if (User == null)
                        {
                            User = "******";
                        }
                        Console.WriteLine("[" + DateTime.Now + "]" + " | " + "From: [" + update.Message.From.Id + "]" + " UserName: [" + User + "]" + " Text: " + Text);
                        offset = update.UpdateId + 1;
                        switch (update.Message.Text)
                        {
                        case "/start":
                            var Request = new SendMessage(update.Message.Chat.Id, "Welcome to real-time crypto price tracker bot, You can find out at the latest price by choosing any of the following cryptocurrencies." + Environment.NewLine + "Last news at @ParsingTeam")
                            {
                                ReplyMarkup = mainMenu
                            };
                            await bot.MakeRequestAsync(Request);

                            break;

                        default:
                            Request = new SendMessage(update.Message.Chat.Id, PikMessage(update.Message.Text))
                            {
                                ReplyMarkup = mainMenu
                            };
                            await bot.MakeRequestAsync(Request);

                            break;
                        }
                    }
                    await Task.Delay(500);
                }
                catch (Exception) {
                    continue;
                }
            }
        }
Ejemplo n.º 6
0
        public async Task <IActionResult> Me()
        {
            var me = await _bot.MakeRequestAsync(new GetMe());

            return(Json(me, new JsonSerializerSettings()
            {
                Formatting = Formatting.Indented
            }));
        }
Ejemplo n.º 7
0
        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);
        }
Ejemplo n.º 8
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);
                }
            }
        }
Ejemplo n.º 9
0
        private async static Task RunBot()
        {
            var mybot = new TelegramBot(Token);
            var me    = await mybot.MakeRequestAsync(new GetMe());

            Console.WriteLine("username : "******"while count = {whileCount}");
                whileCount += 1;
                var updates = await mybot.MakeRequestAsync(new GetUpdates()
                {
                    Offset = offset
                });

                Write($"update count = {updates.Length}\n----------");

                try
                {
                    foreach (Update u in updates)
                    {
                        offset = u.UpdateId + 1;
                        var msg = u.Message.Text;
                        if (msg == "/start")
                        {
                            var req = new SendMessage(u.Message.Chat.Id, "this the response to /start");
                            req.ReplyMarkup = rkstart;
                            await mybot.MakeRequestAsync(req);
                        }
                        else if (msg != null && msg == "salam")
                        {
                            var req = new SendMessage(u.Message.Chat.Id, "this is the response to salam");
                            req.ReplyMarkup = rkstart;
                            await mybot.MakeRequestAsync(req);
                        }
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
Ejemplo n.º 10
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            var botName      = Configuration["BotName"];
            var apiToken     = Configuration["ApiToken"];
            var webhookRoute = $"{botName.ToLower()}/{apiToken}";

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }

            app.UseMvc(routes =>
            {
                routes.MapRoute(botName, webhookRoute + "/{action}",
                                new
                {
                    Controller = nameof(BirthdayzBotController).Replace("Controller", ""),
                    Action     = nameof(BirthdayzBotController.ProcessUpdate)
                });
            });
            var info        = _bot.MakeRequestAsync(new GetWebhookInfo()).Result;
            var certificate = Configuration.GetValue <string>("Certificate");
            var hostName    = Configuration.GetValue <string>("HostName");

            if (Configuration.GetValue <bool>("UseWebhook") && !string.IsNullOrEmpty(certificate) && !string.IsNullOrEmpty(hostName))
            {
                var  url = $"https://{hostName}/{webhookRoute}";
                bool isWebhookSet;
                if (env.IsDevelopment())
                {
                    url          = ""; // Cancel webhooks for development
                    isWebhookSet = _bot.MakeRequestAsync(new SetWebhook(url)).Result;
                }
                else
                {
                    isWebhookSet = _bot.MakeRequestAsync(new SetWebhook(url, new FileToSend(new FileStream(certificate, FileMode.Open), "certificate.pem"))).Result;
                }
                // todo : log the result
            }
        }
Ejemplo n.º 11
0
        public async void UpdateMessagesWorker()
        {
            long offset = 0;

            while (!StopTelegram)
            {
                var updates = await TelegramBot.MakeRequestAsync(new GetUpdates()
                {
                    Offset = offset
                });

                if (updates != null)
                {
                    if (FirstMessageUpdate)
                    {
                        if (updates.Length > 1)
                        {
                            if (updates[(updates.Length - 1)].Message == null)
                            {
                                continue;
                            }
                            TelegramMessages.Enqueue(updates[updates.Length - 1]);
                        }
                        FirstMessageUpdate = false;
                    }
                    else if (FirstMessageUpdate == false)
                    {
                        foreach (var update in updates)
                        {
                            offset = update.UpdateId + 1;
                            if (update.Message == null)
                            {
                                continue;
                            }
                            TelegramMessages.Enqueue(update);
                        }
                    }
                }
                await Task.Delay(1000);
            }
            _started = false;
        }
Ejemplo n.º 12
0
        static async Task Main(string[] args)
        {
            WebProxy proxyObject = new WebProxy("http://10.3.239.2:3128/", true);

            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            // ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
            TelegramBot bot = new TelegramBot("1333442954:AAEA2Zn5jkvRc3ag6Cv8qdJyX2Bo8G3Fb68");
            var         req = new GetMe();

            bot.WebProxy = proxyObject;
            var me = await bot.MakeRequestAsync(req);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Start Tlgrm bot
        /// </summary>
        /// <param name="accessToken">API KEY</param>
        public async void Start(string accessToken)
        {
            if (_started)
            {
                return;
            }
            StopTelegram = false;
            if (string.IsNullOrEmpty(accessToken))
            {
                EventDispatcher.Send(new TelegramMessageEvent
                {
                    Message = "Error: Please enter Telegram HTTP API token."
                });
                return;
            }

            TelegramBot = new TelegramBot(accessToken)
            {
                WebProxy = WebRequest.DefaultWebProxy
            };
            TelegramBot.WebProxy.Credentials = CredentialCache.DefaultCredentials;
            try
            {
                var me = await TelegramBot.MakeRequestAsync(new GetMe());

                if (me == null)
                {
                    EventDispatcher.Send(new TelegramMessageEvent
                    {
                        Message = "Error: Please enter Telegram HTTP API token."
                    });
                    return;
                }
                EventDispatcher.Send(new TelegramMessageEvent
                {
                    Message = "Telegram Started Successfuly with account: @" + me.Username
                });
                UpdateMessagesWorker();
                ReadMessagesWorker();
                _started = true;
            }
            catch (Exception)
            {
                EventDispatcher.Send(new TelegramMessageEvent
                {
                    Message = "Error during request"
                });
            }
        }
Ejemplo n.º 14
0
        internal static void OptInTx(Message message)
        {
            var address = new Regex(
                pattern: @"[Nn]{1,1}[a-zA-Z0-9]{39,39}");

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

            var userAccounts = AccountUtils.GetAccountByUser(chatId: message.Chat.Id)
                               .Where(predicate: e => result.Any(predicate: i => i == e.EncodedAddress)).ToList();

            foreach (var acc in userAccounts)
            {
                acc.CheckTxs = true;

                AccountUtils.UpdateAccount(usrAcc: acc);
            }

            var reqAction = new SendMessage(chatId: message.Chat.Id,
                                            text:
                                            userAccounts.Aggregate(seed: "Opted into tx notification for accounts: \n \n",
                                                                   func: (current, n) => current + StringUtils.GetResultsWithHyphen(n.EncodedAddress) + "\n"));

            bot.MakeRequestAsync(request: reqAction);
        }
Ejemplo n.º 15
0
        public virtual async Task <T> SendAsync <T>(RequestBase <T> message)
        {
            if (logger.IsEnabled(LogLevel.Debug))
            {
                logger.LogDebug($"Sending {message.GetType().Name}...");
            }

            var reply = await botApi.MakeRequestAsync(message);

            if (reply is Message replyMessage)
            {
                await storageService.SaveLogAsync(Id, replyMessage);
            }

            return(reply);
        }
Ejemplo n.º 16
0
        public async void Start(string accessToken)
        {
            if (string.IsNullOrEmpty(accessToken))
            {
                TelegramLog("Error: Please enter Telegram HTTP API token.");
                return;
            }

            _telegram = new TelegramBot(accessToken);
            var me = await _telegram.MakeRequestAsync(new GetMe());

            if (me == null)
            {
                TelegramLog("Error: Please enter Telegram HTTP API token.");
                //Log to console  [08:56:32](TLGRM-ERR)Failed to start Telegram. Please check API Token.
                //Stops Telegram Bot From Being Used
                return;
            }
            TelegramLog("Telegram Started Successfuly with account: @" + me.Username);
            await UpdateMessages();
        }
        private static async void Notify(Account usrAcc, HarvestingData.Datum hrvData)
        {
            try
            {
                var bot = new TelegramBot(accessToken: ConfigurationManager.AppSettings[name: "accessKey"]);

                var reqAction = new SendMessage(chatId: usrAcc.OwnedByUser, text: "The account: \n" + StringUtils.GetResultsWithHyphen(usrAcc.EncodedAddress) + " harvested a new block. \n" + "http://explorer.ournem.com/#/s_block?height=" + hrvData.height + "\nFees included: " + (hrvData.totalFee / 1000000));

                await bot.MakeRequestAsync(request : reqAction);
            }
            catch (Exception e)
            {
                if (e.Message.Contains("blocked"))
                {
                    AccountUtils.DeleteAccountsByUser(usrAcc.OwnedByUser);

                    NodeUtils.DeleteUserNodes(usrAcc.OwnedByUser);

                    UserUtils.DeleteUser(usrAcc.OwnedByUser);
                }
            }
        }
Ejemplo n.º 18
0
    public static async void ServiceUpdate(Update update)
    {
        try
        {
            Console.WriteLine(
                "Hello, World! I am user {me.Id} and my name is {me.FirstName}."
                );

            Console.WriteLine(update.Message.Chat.Id.ToString() + "-" + update.Message.Text + " in ServiceUpdate");
            List <String> cityList = new List <String>();
            cityList.Add("THR");
            cityList.Add("AWZ");
            cityList.Add("SYZ");
            cityList.Add("IFN");
            cityList.Add("KIS");
            cityList.Add("ABD");
            cityList.Add("MHD");
            cityList.Add("TBZ");
            cityList.Add("YZD");
            cityList.Add("BND");
            cityList.Add("KER");
            cityList.Add("GSM");



            var reports = new ReplyKeyboardMarkup();
            reports.ResizeKeyboard = true;
            reports.Keyboard       =
                new KeyboardButton[][]
            {
                new KeyboardButton[]  //1F4B0
                {
                    new KeyboardButton("\U0001F522Route Sales Count"),
                    new KeyboardButton("\U0001F4B5Route Sales Income"),
                    new KeyboardButton("\U0001F4C8Top Agent Sales")
                },
                new KeyboardButton[]
                {
                    new KeyboardButton("\U0001F519Return")
                }
            };

            var dates = new ReplyKeyboardMarkup();
            dates.ResizeKeyboard = true;
            dates.Keyboard       =
                new KeyboardButton[][]
            {
                new KeyboardButton[]
                {
                    new KeyboardButton("Today"),
                    new KeyboardButton("Tomorrow"),
                    new KeyboardButton("Yesterday")
                },
                new KeyboardButton[]
                {
                    new KeyboardButton("\U0001F519Return")
                }
            };


            var pastDates = new ReplyKeyboardMarkup();
            pastDates.ResizeKeyboard = true;
            pastDates.Keyboard       =
                new KeyboardButton[][]
            {
                new KeyboardButton[]
                {
                    new KeyboardButton("Today"),
                    new KeyboardButton("Yesterday"),
                    new KeyboardButton("Day Before Yesterday")
                },
                new KeyboardButton[]
                {
                    new KeyboardButton("\U0001F519Return")
                }
            };



            var startOption = new ReplyKeyboardMarkup();
            startOption.ResizeKeyboard = true;
            startOption.Selective      = true;
            startOption.Keyboard       =
                new KeyboardButton[][]
            {
                new KeyboardButton[]
                {
                    new KeyboardButton("\U0001F510Login"),
                    new KeyboardButton("\U0001F519Return")
                }
            };



            var city = new ReplyKeyboardMarkup();
            city.ResizeKeyboard = true;
            city.Keyboard       =
                new KeyboardButton[][]
            {
                new KeyboardButton[]
                {
                    new KeyboardButton("THR"), new KeyboardButton("AWZ"),
                    new KeyboardButton("SYZ"), new KeyboardButton("IFN")
                },
                new KeyboardButton[]
                {
                    new KeyboardButton("KIS"), new KeyboardButton("ABD"),
                    new KeyboardButton("MHD"), new KeyboardButton("TBZ")
                },
                new KeyboardButton[]
                {
                    new KeyboardButton("YZD"), new KeyboardButton("BND"),
                    new KeyboardButton("KER"), new KeyboardButton("GSM")
                }
            };

            var generalOption = new ReplyKeyboardMarkup();
            generalOption.ResizeKeyboard = true;
            generalOption.Keyboard       =
                new KeyboardButton[][]
            {
                new KeyboardButton[]
                {
                    new KeyboardButton("\U0001F50DStart")
                }
            };

            var reportCommand = new ReplyKeyboardMarkup();
            reportCommand.ResizeKeyboard = true;

            reportCommand.Keyboard =
                new KeyboardButton[][]
            {
                new KeyboardButton[]
                {
                    new KeyboardButton("\U0001F4CAGraphical Reports"),
                    new KeyboardButton("\U0001F4CBTerminal Commands")
                }, new KeyboardButton[]
                {
                    new KeyboardButton("\U0001F519Return")
                }
            };



            string Origin      = "";
            string Destination = "";
            string Date        = "";

            //tbSystemProperty.findWhereCondition(x => x.Name.Equals("BotAddressIMG")).First().Value;
            StringBuilder log    = new StringBuilder();
            long          offset = update.UpdateId + 1;

            if ((update == null) || (update.Message == null) || (update.Message.Chat == null))
            {
                return;
            }

            String ChatID   = update.Message.Chat.Id.ToString();
            String Request  = update.Message.Text;
            var    userName = update.Message.From.Username;
            //var cellphone = update.Message.Contact.PhoneNumber;

            DateTime now = DateTime.Now;


            //static String ImgAddress = tbSystemProperty.findWhereCondition(x => x.Name.Equals("BotAddressIMG")).First().Value;



            var text = update.Message.Text;


            UserSession us = (UserSession)Session[ChatID];
            if (us == null)
            {
                us              = new UserSession();
                us.State        = "";
                Session[ChatID] = us;
            }
            if (text != null && (text.ToLower().Contains("start") || text.ToLower().Contains("return")))
            {
                log.AppendLine("ChatID: " + ChatID + " /User Text : " + text + " " + now.ToString("yyyy-MM-dd hh:mm:ss") + "\n");
                System.IO.File.AppendAllText(ImgAddress + "log" + ChatID + ".txt", log.ToString());
                log.Clear();



                us              = (UserSession)Session[ChatID];
                us.State        = "start";
                Session[ChatID] = us;

                tbBotUser userChatiId = tbBotUser.findWhereCondition(x => x.ChatID == ChatID).FirstOrDefault();


                if (userChatiId == null)
                {
                    us.State        = "firstlogin";
                    Session[ChatID] = us;
                    String response = "\U0001F4CC Welcom to NiraBot,\n \n\U0001F4DD Please choose your selection:";
                    var    req      = new SendMessage(update.Message.Chat.Id, response)
                    {
                        ReplyMarkup = startOption
                    };
                    await newBot.MakeRequestAsync(req);

                    //  Logger.logEvent("ChatID: " + ChatID + "/ State : userspec , /User Text : " + text, Logger.NORAML);

                    log.AppendLine("ChatID: " + ChatID + "/ State : userspec , /User Text : " + text);
                    System.IO.File.AppendAllText(ImgAddress + "log" + ChatID + ".txt", log.ToString());
                    log.Clear();

                    return;
                }
                else
                {
                    us.State        = "detected";
                    Session[ChatID] = us;
                    String response = "\U0001F4CC Welcom to NiraBot, dear " + userChatiId.UserID + " \n \n \U0001F4DD Please choose your selection:";
                    var    req      = new SendMessage(update.Message.Chat.Id, response)
                    {
                        ReplyMarkup = reportCommand
                    };
                    await newBot.MakeRequestAsync(req);

                    // Logger.logEvent("ChatID: " + ChatID + "/ State : userspec , /User Text : " + text, Logger.NORAML);

                    log.AppendLine("ChatID: " + ChatID + "/ State : userspec , /User Text : " + text + " " + now.ToString("yyyy-MM-dd hh:mm:ss") + "\n");
                    System.IO.File.AppendAllText(ImgAddress + "log" + ChatID + ".txt", log.ToString());
                    log.Clear();
                    return;
                }
            }
            else if (us.State == "firstlogin")
            {
                if (text.Contains("Login"))
                {
                    us.State        = "userspec";
                    Session[ChatID] = us;
                    String response = "\U0001F4DD Please enter your username and password.\n \n\U0001F50A Exam: username/password";
                    var    req      = new SendMessage(update.Message.Chat.Id, response)
                    {
                        ReplyMarkup = generalOption
                    };


                    await newBot.MakeRequestAsync(req);

                    log.AppendLine("ChatID: " + ChatID + "/ State : userspec , /User Text : " + text + " " + now.ToString("yyyy-MM-dd hh:mm:ss") + "\n");
                    System.IO.File.AppendAllText(ImgAddress + "log" + ChatID + ".txt", log.ToString());
                    log.Clear();

                    //  Logger.logEvent("ChatID: " + ChatID + "/ State : userspec , /User Text : " + text,Logger.NORAML);
                    return;
                }
                else if (text != "Return")
                {
                    us.State        = "firstlogin";
                    Session[ChatID] = us;
                    var req = new SendMessage(update.Message.Chat.Id, "\U0001F6AB Input data is incorrect, Please use the keyboard.")
                    {
                        ReplyMarkup = startOption
                    };
                    await newBot.MakeRequestAsync(req);

                    log.AppendLine("ChatID: " + ChatID + "/ State : firstlogin , /User Text : " + text + " " + now.ToString("yyyy-MM-dd hh:mm:ss") + "\n");
                    System.IO.File.AppendAllText(ImgAddress + "log" + ChatID + ".txt", log.ToString());
                    log.Clear();

                    //   Logger.logEvent("ChatID: " + ChatID + "/ State : firstlogin , /User Text : " + text, Logger.NORAML);


                    return;
                }
            }
            else if (text != null && us.State == "userspec")
            {
                if (text.Length > 6 && text.Contains("/"))
                {
                    us.State        = "login";
                    Session[ChatID] = us;
                    int index = text.IndexOf("/");


                    us.User         = text.Substring(0, index).ToString();
                    Session[ChatID] = us;
                    string passlen = text.Substring(index + 1, text.Length - (index + 1));
                    us.Password     = passlen;
                    Session[ChatID] = us;

                    tbBotUser botUser = tbBotUser.findWhereCondition(x => x.UserID.Equals(us.User)).FirstOrDefault();

                    if (botUser != null && us.Password == botUser.Password)
                    {
                        us.State        = "registered";
                        Session[ChatID] = us;

                        botUser.ChatID        = ChatID;
                        botUser.IssueDateTime = now.ToString();
                        botUser.ExtraInfo     = "Users Regidtered.";
                        if (userName != null || userName != "")
                        {
                            botUser.BotUserName = userName;
                        }
                        botUser.store();

                        AirWS  ws = new AirWS();
                        String s  = ws.SendCommand("SI" + us.User + "/" + us.Password, ChatID);



                        //String response = "Welcom " + us.User + " \U0001F44C,\n\n choose your selection.";
                        String response = "Welcom " + us.User + " \U00002708,\n\n choose your selection.";
                        var    req      = new SendMessage(update.Message.Chat.Id, response)
                        {
                            ReplyMarkup = reportCommand
                        };
                        await newBot.MakeRequestAsync(req);

                        log.AppendLine("ChatID: " + ChatID + "/ State : registered , /User Text : " + text + " " + now.ToString("yyyy-MM-dd hh:mm:ss") + "\n");
                        System.IO.File.AppendAllText(ImgAddress + "log" + ChatID + ".txt", log.ToString());
                        log.Clear();

                        //   Logger.logEvent("ChatID: " + ChatID + "/ State : registered , /User Text : " + text, Logger.NORAML);
                        return;
                    }
                    else
                    {
                        AirWS  ws = new AirWS();
                        String s  = ws.SendCommand("SI" + us.User + "/" + us.Password, ChatID);
                        if (s.Contains("Succ"))
                        {
                            botUser          = new tbBotUser();
                            botUser.UserID   = us.User;
                            botUser.Password = us.Password;
                            botUser.ChatID   = ChatID;
                            botUser.create();

                            log.AppendLine("ChatID: " + ChatID + "/ State : registered , SendCommand SI Command To Ws. /User Text : " + text + " " + now.ToString("yyyy-MM-dd hh:mm:ss") + "\n");
                            System.IO.File.AppendAllText(ImgAddress + "log" + ChatID + ".txt", log.ToString());
                            log.Clear();


                            //  Logger.logEvent("ChatID: " + ChatID + "/ State : registered , SendCommand SI Command To Ws. /User Text : " + text, Logger.NORAML);
                        }
                        else
                        {
                            us.State        = "userspec";
                            Session[ChatID] = us;
                            String response = "\U0001F6AB User or Password is wrong.\n \n \U0001F50A Exam:username/password";
                            var    req      = new SendMessage(update.Message.Chat.Id, response)
                            {
                                ReplyMarkup = startOption
                            };
                            await newBot.MakeRequestAsync(req);

                            log.AppendLine("ChatID: " + ChatID + "/ State : userspec , User or Password is wrong, /User Text : " + text + " " + now.ToString("yyyy-MM-dd hh:mm:ss") + "\n");
                            System.IO.File.AppendAllText(ImgAddress + "log" + ChatID + ".txt", log.ToString());
                            log.Clear();

                            //   Logger.logEvent("ChatID: " + ChatID + "/ State : userspec , User or Password is wrong, /User Text : " + text, Logger.NORAML);
                        }
                        return;
                    }
                }
                else
                {
                    us.State        = "userspec";
                    Session[ChatID] = us;
                    var req = new SendMessage(update.Message.Chat.Id, "\U0001F6AB Input data is incorrect ,Enter your username and password.\n\U0001F50A Exam: username/password")
                    {
                        ReplyMarkup = startOption
                    };
                    await newBot.MakeRequestAsync(req);

                    return;
                }
            }

            else if (text != null && (us.State == "registered" || us.State == "detected") && text.Contains("Graphical Reports"))
            {
                us.State        = "selectreport";
                Session[ChatID] = us;
                var req = new SendMessage(update.Message.Chat.Id, "Please select the desired report: ")
                {
                    ReplyMarkup = reports
                };
                await newBot.MakeRequestAsync(req);

                log.AppendLine("ChatID: " + ChatID + "/ State : selectreport , /User Text : " + text + " " + now.ToString("yyyy-MM-dd hh:mm:ss") + "\n");
                System.IO.File.AppendAllText(ImgAddress + "log" + ChatID + ".txt", log.ToString());
                log.Clear();


                // Logger.logEvent("ChatID: " + ChatID + "/ State : selectreport , /User Text : " + text, Logger.NORAML);
                return;
            }

            else if (us.State.Equals("selectreport") || us.State.Equals("reportdatacomplete"))
            {
                us.State        = "selectorigin";
                Session[ChatID] = us;
                //  Logger.logEvent("ChatID: " + ChatID + "/ State : selectorigin , /User Text : " + text, Logger.NORAML);
                if (text.Contains("Route Sales Count"))
                {
                    us.Report = "Count";
                }
                else if (text.Contains("Route Sales Income"))
                {
                    us.Report = "Income";
                }
                else if (text.Contains("Top Agent Sales"))
                {
                    us.Report       = "TopSales";
                    us.State        = "enterdate";
                    Session[ChatID] = us;


                    await newBot.MakeRequestAsync(new SendMessage(update.Message.Chat.Id, "\U0001F4C6 Date: \nSelect the keyboard or enter the date manually\n\U0001F50A Exam: 2018-01-01") { ReplyMarkup = pastDates });

                    log.AppendLine("ChatID: " + ChatID + "/ State : selectorigin , Report : TopSales, /User Text : " + text + "  " + now.ToString("yyyy-MM-dd hh:mm:ss") + "\n");
                    System.IO.File.AppendAllText(ImgAddress + "log" + ChatID + ".txt", log.ToString());
                    log.Clear();


                    //  Logger.logEvent("ChatID: " + ChatID + "/ State : selectorigin , Report : TopSales, /User Text : " + text, Logger.NORAML);
                    return;
                }
                else
                {
                    us.State        = "selectreport";
                    Session[ChatID] = us;
                    var req = new SendMessage(update.Message.Chat.Id, "\U0001F6AB Input data is incorrect ,Please use the keyboard.")
                    {
                        ReplyMarkup = reports
                    };

                    await newBot.MakeRequestAsync(req);

                    log.AppendLine("ChatID: " + ChatID + "/ State : selectreport , /User Text : " + text + " " + now.ToString("yyyy-MM-dd hh:mm:ss") + "\n");
                    System.IO.File.AppendAllText(ImgAddress + "log" + ChatID + ".txt", log.ToString());
                    log.Clear();

                    //  Logger.logEvent("ChatID: " + ChatID + "/ State : selectreport , /User Text : " + text, Logger.NORAML);
                    return;
                }

                Session[ChatID] = us;


                String response = "Origin:";
                var    req2     = new SendMessage(update.Message.Chat.Id, response)
                {
                    ReplyMarkup = city
                };
                await newBot.MakeRequestAsync(req2);

                return;
            }

            else if (text != null && us.State == "selectorigin")
            {
                String cityCode = "";

                foreach (string row in cityList)
                {
                    if (row.Contains(text))
                    {
                        cityCode = text;
                    }
                }

                if (cityCode != null && cityCode != "")
                {
                    us.State        = "selectdestination";
                    us.Origin       = text;
                    Session[ChatID] = us;
                    Console.WriteLine(Origin);


                    await newBot.MakeRequestAsync(new SendMessage(update.Message.Chat.Id, "Destination:") { ReplyMarkup = city });

                    log.AppendLine("ChatID: " + ChatID + "/ State : selectdestination , /User Text : " + text + " " + now.ToString("yyyy-MM-dd hh:mm:ss") + "\n");
                    System.IO.File.AppendAllText(ImgAddress + "log" + ChatID + ".txt", log.ToString());
                    log.Clear();


                    //  Logger.logEvent("ChatID: " + ChatID + "/ State : selectdestination , /User Text : " + text, Logger.NORAML);
                    return;
                }
                else
                {
                    us.State        = "selectorigin";
                    Session[ChatID] = us;
                    var req = new SendMessage(update.Message.Chat.Id, "\U0001F6AB Input data is incorrect ,Please use the keyboard.")
                    {
                        ReplyMarkup = city
                    };
                    await newBot.MakeRequestAsync(req);

                    return;
                }
            }
            else if (text != null && us.State == "selectdestination")
            {
                String cityCode = "";

                foreach (string row in cityList)
                {
                    if (row.Contains(text))
                    {
                        cityCode = text;
                    }
                }
                if (cityCode != null && cityCode != "")
                {
                    us.State        = "enterdate";
                    us.Destination  = text;
                    Session[ChatID] = us;
                    Console.WriteLine(Destination);
                    await newBot.MakeRequestAsync(new SendMessage(update.Message.Chat.Id, "\U0001F4C6 Date: \nSelect the keyboard or enter the date manually\n\U0001F50A Exam: 2018-01-01") { ReplyMarkup = dates });

                    log.AppendLine("ChatID: " + ChatID + "/ State : enterdate , /User Text : " + text + " " + now.ToString("yyyy-MM-dd hh:mm:ss") + "\n");
                    System.IO.File.AppendAllText(ImgAddress + "log" + ChatID + ".txt", log.ToString());
                    log.Clear();

                    //  Logger.logEvent("ChatID: " + ChatID + "/ State : enterdate , /User Text : " + text, Logger.NORAML);
                    return;
                }
                else
                {
                    us.State        = "selectdestination";
                    Session[ChatID] = us;
                    var req = new SendMessage(update.Message.Chat.Id, "\U0001F6AB Input data is incorrect ,Please use the keyboard.")
                    {
                        ReplyMarkup = city
                    };
                    await newBot.MakeRequestAsync(req);

                    log.AppendLine("ChatID: " + ChatID + "/ State : selectdestination , /User Text : " + text + " " + now.ToString("yyyy-MM-dd hh:mm:ss") + "\n");
                    System.IO.File.AppendAllText(ImgAddress + "log" + ChatID + ".txt", log.ToString());
                    log.Clear();

                    // Logger.logEvent("ChatID: " + ChatID + "/ State : selectdestination , /User Text : " + text, Logger.NORAML);
                    return;
                }
            }
            else if (text != null && us.State == "enterdate")
            {
                us.State        = "reportdatacomplete";
                Session[ChatID] = us;

                log.AppendLine("ChatID: " + ChatID + "/ State : reportdatacomplete , /User Text : " + text + " " + now.ToString("yyyy-MM-dd hh:mm:ss") + "\n");
                System.IO.File.AppendAllText(ImgAddress + "log" + ChatID + ".txt", log.ToString());
                log.Clear();

                // Logger.logEvent("ChatID: " + ChatID + "/ State : reportdatacomplete , /User Text : " + text, Logger.NORAML);

                if ((text.Contains("Today") || text.Contains("Tomor") || text.Contains("Yester")))
                {
                    if (text.Equals("Today"))
                    {
                        Date = now.ToString("yyyy-MM-dd");
                    }
                    if (text.Equals("Tomorrow"))
                    {
                        Date = now.AddDays(1).ToString("yyyy-MM-dd");
                    }
                    if (text.Equals("Yesterday"))
                    {
                        Date = now.AddDays(-1).ToString("yyy-MM-dd");
                    }
                    if (text.Equals("Day Before Yesterday"))
                    {
                        Date = now.AddDays(-2).ToString("yyy-MM-dd");
                    }
                }
                else if (com.nirasoftware.Validators.dateFormatValidate(text))
                {
                    Date = text;
                }
                else
                {
                    us.State        = "enterdate";
                    Session[ChatID] = us;

                    Console.WriteLine(Destination);

                    await newBot.MakeRequestAsync(new SendMessage(update.Message.Chat.Id, "\U0001F6AB Invalid input data.\nChoose date from keyboard or enter date.\nExam: 2018-01-01") { ReplyMarkup = dates });


                    return;
                }



                String Img = (now.ToString("yyyy-MM-dd hh:mm:ss").Replace(":", "-") + update.Message.Chat.Id).Replace(" ", "-");
                Console.WriteLine(Date);
                await newBot.MakeRequestAsync(new SendMessage(update.Message.Chat.Id, "Please Wait...") { ReplyMarkup = reports });

                String baseUrl = GraphicalBotReporUrl;    //tbSystemProperty.findWhereCondition(x => x.Name.Equals("GraphicalBotReporUrl")).First().Value;


                String url = baseUrl + "?Origin=" + us.Origin + "&Destination=" + us.Destination + "&Date=" + Date + "&Img=" + Img + "&Report=" + us.Report;    //+"&ReturnDate=2018-02-19&AdultQTY=1&ChildQty=0&InfantQty=0&RoundTrip=True";

                String resp = sendHttpRequest(url);

                //// Logger.logEvent("ChatID: " + ChatID + "/ State : Url1 Sent To Server Url : " + url + "/User Text : " + text, Logger.NORAML);

                log.AppendLine("ChatID: " + ChatID + "/ State : Url1 Sent To Server Url : " + url + "/User Text : " + text + " " + now.ToString("yyyy-MM-dd hh:mm:ss") + "\n");
                System.IO.File.AppendAllText(ImgAddress + "log" + ChatID + ".txt", log.ToString());
                log.Clear();

                int cnt    = 0;
                var fileId = @ImgAddress + Img + ".png";
                while ((!System.IO.File.Exists(fileId)) && (cnt < 30))
                {
                    cnt++;
                    Thread.Sleep(1000);
                }

                if (!System.IO.File.Exists(fileId))
                {
                    return;
                }
                var        stream2 = System.IO.File.Open(fileId, FileMode.Open);
                FileToSend fts     = new FileToSend(stream2, fileId.Split('\\').Last());
                await newBot.MakeRequestAsync(new SendPhoto(update.Message.Chat.Id, fts) { Caption = "Sales Report: " + us.Report + " " + us.Origin + "-" + us.Destination + " Date: " + now.ToShortDateString() });

                log.AppendLine("ChatID: " + ChatID + "/ State : Url2 Sent To Server , /User Text : " + text + " " + now.ToString("yyyy-MM-dd hh:mm:ss") + "\n");
                System.IO.File.AppendAllText(ImgAddress + "log" + ChatID + ".txt", log.ToString());
                log.Clear();

                //  Logger.logEvent("ChatID: " + ChatID + "/ State : Url2 Sent To Server , /User Text : " + text, Logger.NORAML);


                if (us.Report.Contains("TopSales"))
                {
                    String url2 = baseUrl + "?Origin=" + us.Origin + "&Destination=" + us.Destination + "&Date=" + Date + "&Img=second" + Img + "&Report=" + us.Report;    //+"&ReturnDate=2018-02-19&AdultQTY=1&ChildQty=0&InfantQty=0&RoundTrip=True";

                    String resp2 = sendHttpRequest(url2);



                    log.AppendLine("ChatID: " + ChatID + "/ State : Url Sent To Server url2 : " + url2 + "/User Text : " + text + " " + now.ToString("yyyy-MM-dd hh:mm:ss") + "\n");
                    System.IO.File.AppendAllText(ImgAddress + "log" + ChatID + ".txt", log.ToString());
                    log.Clear();


                    int cnt2    = 0;
                    var fileId2 = @ImgAddress + "second" + Img + "new" + ".png";
                    while ((!System.IO.File.Exists(fileId2)) && (cnt < 30))
                    {
                        cnt2++;
                        Thread.Sleep(1000);
                    }

                    if (!System.IO.File.Exists(fileId2))
                    {
                        return;
                    }
                    var        stream3 = System.IO.File.Open(fileId2, FileMode.Open);
                    FileToSend fts2    = new FileToSend(stream3, fileId2.Split('\\').Last());
                    await newBot.MakeRequestAsync(new SendPhoto(update.Message.Chat.Id, fts2) { Caption = "Sales Report: " + us.Report + " " + us.Origin + "-" + us.Destination + " Date: " + now.ToShortDateString() });

                    return;
                }

                return;
            }

            else if (us.State == "terminal" || text.Contains("Terminal Commands"))
            {
                try
                {
                    us.State        = "terminal";
                    Session[ChatID] = us;
                    String s = "";
                    if (text.Contains("Terminal Commands"))
                    {
                        s = "Please enter Command:";
                    }
                    else
                    {
                        AirWS ws = new AirWS();
                        s = ws.SendCommand(text, ChatID);
                        if (s.Contains("REMOTE"))
                        {
                            s = "Please Sign in using SI Command)";
                        }

                        int n = s.Length;
                        if (n > MAX_RESPONSE_LEN)
                        {
                            s = s.Substring(1, MAX_RESPONSE_LEN);
                        }
                    }
                    var req = new SendMessage(update.Message.Chat.Id, s)
                    {
                        ReplyMarkup = generalOption
                    };;
                    await newBot.MakeRequestAsync(req);
                }
                catch (Exception exe) { }

                return;
            }
            else
            {
                us.State        = "start";
                us.Origin       = "";
                us.Destination  = "";
                us.Report       = "";
                Session[ChatID] = us;

                var req = new SendMessage(update.Message.Chat.Id, "\U0001F6AB Input data is incorrect.Please use the keyboard.")
                {
                    ReplyMarkup = generalOption
                };
                await newBot.MakeRequestAsync(req);

                return;
            }
        }
        catch (Exception e) { }
        return;
    }
Ejemplo n.º 19
0
    public static async Task RunBot()
    {
        try
        {
            newBot = new TelegramBot(botToken);
            //    botDetail = (User)await newBot.MakeRequestAsync(new GetMe());
            var botDetail = await newBot.MakeRequestAsync(new GetMe());

            Console.WriteLine("UserName Is {0}", botDetail.Username);

            Session = new Hashtable();



            long offset = 0;

            while (true)
            {
                try
                {
                    Update[] updates = await newBot.MakeRequestAsync(new GetUpdates()
                    {
                        Offset = offset
                    });

                    if (updates.Length == 0)
                    {
                        continue;
                    }
                    Console.WriteLine("");
                    if ((updates[0].Message != null))
                    {
                        Console.WriteLine(updates[0].Message.Chat.Id.ToString() + "-" + updates[0].Message.Text + " in Main Loop");
                    }
                    else
                    {
                        Console.WriteLine(updates[0].UpdateId);
                    }

                    foreach (var update in updates)
                    {
                        //  Console.ReadLine();
                        WorkerThread worker = new WorkerThread(update);

                        if ((update.Message != null))
                        {
                            Console.WriteLine(update.Message.Chat.Id.ToString() + "-" + update.Message.Text + " Worker Thread Created");
                        }
                        else
                        {
                            Console.WriteLine(update.UpdateId);
                        }

                        Thread t = new Thread(new ThreadStart(worker.ThreadProc));

                        if ((update.Message != null))
                        {
                            Console.WriteLine(update.Message.Chat.Id.ToString() + "-" + update.Message.Text + "  Thread Created");
                        }
                        else
                        {
                            Console.WriteLine(update.UpdateId);
                        }

                        t.Start();
                        offset = update.UpdateId + 1;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(" Exception:" + ex.Message);
                }
            }
        }
        catch (Exception e)
        { Console.WriteLine(" Exception:" + e.Message); }
    }
Ejemplo n.º 20
0
        internal async void ReturnMyDetails(Message message)
        {
            try
            {
                var Bot = new TelegramBot(accessToken: ConfigurationManager.AppSettings[name: "accessKey"]);

                var u = UserUtils.GetUser(chatId: message.From.Id);

                if (u.ChatId != message.Chat.Id)
                {
                    var req = new SendMessage(chatId: message.Chat.Id, text: "You are not registered");
                    await Bot.MakeRequestAsync(request : req);

                    return;
                }

                var nodes = NodeUtils.GetNodeByUser(chatId: message.From.Id);

                var accounts = AccountUtils.GetAccountByUser(chatId: message.From.Id);

                List <string> accountString;
                List <string> ips = new List <string>();
                try
                {
                    var client = new AccountClient(Con);

                    if (nodes.Count > 0)
                    {
                        ips = nodes.Select(selector: n => ("Alias: " + n.Alias +
                                                           "\nIP: " + n.IP +
                                                           "\nDeposit address: \n" + (accounts.All(predicate: e => e.EncodedAddress != n.DepositAddress) ? "[ACCOUNT UNREGISTERED] " : "") + StringUtils.GetResultsWithHyphen(n.DepositAddress) +
                                                           "\nBalance: " + client.EndGetAccountInfo(client.BeginGetAccountInfoFromAddress(n.DepositAddress)).Account.Balance / 1000000 +
                                                           "\nTransactions check: " + AccountUtils.GetAccount(add: n.DepositAddress, user: message.Chat.Id).CheckTxs +
                                                           "\nHarvesting check: " + AccountUtils.GetAccount(add: n.DepositAddress, user: message.Chat.Id).CheckBlocks +
                                                           "\nhttps://supernodes.nem.io/details/" + n.SNodeID +
                                                           "\nhttp://explorer.ournem.com/#/s_account?account=" + n.DepositAddress + "\n\n")).ToList();
                    }

                    var req = new SendMessage(chatId: message.Chat.Id, text: "**Your registered nodes with associated accounts**");

                    await Bot.MakeRequestAsync(request : req);

                    foreach (var s in ips)
                    {
                        req = new SendMessage(chatId: message.Chat.Id, text: s);

                        await Bot.MakeRequestAsync(request : req);
                    }


                    var a = accounts.Select(selector: acc => acc.EncodedAddress).ToList();

                    req = new SendMessage(chatId: message.Chat.Id, text: "**Your registered accounts**");

                    if (a.Count > 0)
                    {
                        await Bot.MakeRequestAsync(request : req);
                    }

                    accountString = a.Select(selector: n =>
                                             "\nAccount address: \n" + StringUtils.GetResultsWithHyphen(n) +
                                             "\nBalance: " + client.EndGetAccountInfo(client.BeginGetAccountInfoFromAddress(n)).Account.Balance / 1000000 +
                                             "\nTransactions check: " + AccountUtils.GetAccount(add: n, user: message.Chat.Id).CheckTxs +
                                             "\nHarvesting check: " + AccountUtils.GetAccount(add: n, user: message.Chat.Id).CheckBlocks +
                                             "\nhttp://explorer.ournem.com/#/s_account?account=" + n + "\n\n").ToList();
                }
                catch (Exception e)
                {
                    Console.WriteLine(value: e);

                    accountString = new List <string> {
                        "Sorry something went wrong, please try again. Possibly your node could be offline."
                    };
                }

                foreach (var s in accountString)
                {
                    var reqAction = new SendMessage(chatId: message.Chat.Id, text: s);

                    await Bot.MakeRequestAsync(request : reqAction);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 21
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 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();
                        }
                    }
                }
            }
        }
Ejemplo n.º 22
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 App.config?");
                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();
            Console.WriteLine("ATENTION! This project uses nuget package, not 'live' project in solution (because 'live' project is vNext now)");
            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 = 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[] { new KeyboardButton("/photo"), new KeyboardButton("/doc"), new KeyboardButton("/docutf8") },
                                    new[] { new KeyboardButton("/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: \r\n_" + update.Message.Text.MarkdownEncode() + "_")
                            {
                                ParseMode = SendMessage.ParseModeEnum.Markdown
                            }).Wait();
                        }
                        else
                        {
                            bot.MakeRequestAsync(new ForwardMessage(update.Message.Chat.Id, update.Message.Chat.Id, update.Message.MessageId)).Wait();
                        }
                    }
                }
            }
        }
Ejemplo n.º 23
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();
                        }
                    }
                }
            }
        }
Ejemplo n.º 24
0
        public static void Run_Bot()
        {
            /*first
             * //Create bot
             * var bot = new TelegramBot(Token);
             * var me = bot.MakeRequestAsync(new GetMe()).Result;
             *
             *
             * //creating for each user a specific id to have it's own state
             * var userId = new Dictionary<long, int>();
             * int cnt = 0;
             *
             * long offset = 0;
             * long iid = 0;
             *
             * Tourist_BotEntities _context = new Tourist_BotEntities();
             *
             * while (true)
             * {
             *     var updates = bot.MakeRequestAsync(new GetUpdates() { Offset = offset }).Result;
             *     try
             *     {
             *         foreach (var update in updates)
             *         {
             *             Console.WriteLine(update.Message.Text);
             *             string text = update.Message.Text;
             *             long chatId = update.Message.Chat.Id;
             *             if (text == "/start")
             *             {
             *                 string message = "welcom :)";
             *                 var reg = new SendMessage(chatId, message);
             *                 bot.MakeRequestAsync(reg);
             *             }
             *             else
             *             {
             *                 City city = new City();
             *                 city.Id = iid;
             *                 city.Message = text;
             *                 _context.Cities.Add(city);
             *                 try { _context.SaveChanges(); }
             *                 catch (Exception e) { Console.WriteLine(e.Message); }
             *                 string message = "undefined request !";
             *                 var reg = new SendMessage(chatId, message);
             *                 bot.MakeRequestAsync(reg);
             *             }
             *             offset = update.UpdateId + 1;
             *             iid++;
             *         }
             *     }
             *     catch (Exception e) { Console.WriteLine(e.Message); }
             * }*/

            /*second*/
            //making the bot
            var bot = new TelegramBot(Token);
            var me  = bot.MakeRequestAsync(new GetMe()).Result;


            //creating for each user a specific id to have it's own state
            var userId = new Dictionary <long, int>();
            int cnt    = 0;

            //getting the list of person in ram
            List <Person> persons = new List <Person>();
            long          offset  = 0;
            long          iid     = 0;
            //long examIDs = 0;
            //long QuestionIDs = 0;

            Tourist_BotEntities _context = new Tourist_BotEntities();

            while (true)
            {
                var updates = bot.MakeRequestAsync(new GetUpdates()
                {
                    Offset = offset
                }).Result;
                try
                {
                    foreach (var update in updates)
                    {
                        long chatId = update.Message.Chat.Id;

                        if (!userId.ContainsKey(chatId))
                        {
                            userId.Add(chatId, cnt);
                            Person p = new Person();
                            p.ChatID = chatId;
                            p.State  = "Start";

                            //p.pic = update.Message.Photo.ToString();
                            persons.Add(p);
                            cnt++;
                        }
                        var check = _context.Users.Where(x => x.Id == chatId);
                        //Console.WriteLine(check.ToList()[0].Id);
                        if (check.Count() != 0)
                        {
                            var temp = _context.Users.FirstOrDefault(x => x.Id == chatId);
                            _context.Users.Remove(temp);
                        }
                        // _context.Users.SqlQuery("DELETE FROM[Tourist_Bot].[dbo].[User] WHERE[Tourist_Bot].[dbo].[User].Id = " + chatId);

                        User u = new User();

                        u.Id = chatId;
                        if (!persons[userId[chatId]].np_IsP)
                        {
                            u.Message = update.Message.Text;
                        }
                        else
                        {
                            u.Message = "IsPhoto";
                        }
                        u.State     = persons.Where(x => x.ChatID == chatId).ToList()[0].State;
                        u.Username  = update.Message.Chat.Username;
                        u.Firstname = update.Message.Chat.FirstName;
                        u.Lastname  = update.Message.Chat.LastName;
                        _context.Users.Add(u);



                        //    Console.WriteLine("avali");


                        //else

                        //  Console.Write("DELETE FROM[Tourist_Bot].[dbo].[User] WHERE[Tourist_Bot].[dbo].[User].Id = " + chatId);
                        //  _context.Users.SqlQuery("DELETE FROM[Tourist_Bot].[dbo].[User] WHERE[Tourist_Bot].[dbo].[User].Id = 60163330");
                        //_context.Users.S

                        //_context.Users.

                        try { _context.SaveChanges(); }
                        catch (Exception e) { Console.WriteLine(e.Message + "DB in ConnectToDB"); }


                        persons[userId[chatId]].Text = update.Message.Text;
                        //persons[userId[chatId]].Text = "Null";
                        //MemoryStream ms = new MemoryStream();
                        if (!persons[userId[chatId]].np_IsP || persons[userId[chatId]].Text == "انصراف")
                        {
                            //   Console.WriteLine("omad");
                            persons[userId[chatId]].Text = update.Message.Text;
                        }
                        else
                        {
                            persons[userId[chatId]].Pic = update.Message.Photo;
                            //persons[userId[chatId]].Pic = update.Message.GetType;
                            // Console.WriteLine(update.Message.GetType());

                            //persons[userId[chatId]].Pic.FileId = "f**k";
                            //   Console.Write("ax" + persons[userId[chatId]].Pic[0].FileId);
                            // string FUCKU = persons[userId[chatId]].Pic.FileId;
                        }
                        // Console.WriteLine(persons[userId[chatId]].State);
                        StateDesignPattern userState = new StateDesignPattern();
                        //   Console.WriteLine("mire");
                        userState.CheckState(persons[userId[chatId]], bot, _context);
                        offset = update.UpdateId + 1;
                        //  Console.WriteLine("mire2");
                        iid++;
                    }
                }
                catch (Exception e) { Console.WriteLine(e.Message + e.Source + e.GetType() + e.Data + "Base error"); }
            }
        }
Ejemplo n.º 25
0
        internal void ManageNodes(Chat chat, string text)
        {
            var Bot = new TelegramBot(accessToken: ConfigurationManager.AppSettings[name: "accessKey"]);

            // if the user is not known, add the user to the database
            if (UserUtils.GetUser(chatId: chat.Id)?.ChatId == null)
            {
                // add user based on their chat ID
                UserUtils.AddUser(userName: chat.Username, chatId: 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: chat.Id, text: msg1);

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

            // set up regex pattern matching sequences.
            var ip  = new Regex(pattern: @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");
            var ip2 = new Regex(pattern: @"[a-zA-Z0-9]{1,20}\.[a-zA-Z0-9]{1,20}\.[a-zA-Z0-9]{1,20}");
            var ip3 = new Regex(pattern: @"[a-zA-Z0-9]{1,20}\.[a-zA-Z0-9]{1,20}");

            // scan list of submitted ip's for any valid sequences
            var result = ip.Matches(input: text).Cast <Match>().Select(selector: m => m.Value)
                         .Concat(second: ip2.Matches(input: text).Cast <Match>().Select(selector: m => m.Value))
                         .Concat(second: ip3.Matches(input: text).Cast <Match>().Select(selector: m => m.Value)).ToArray();



            // declare a nodeClient to retrieve node data.
            var snodeClient = new SupernodeClient();

            // get a list of all supernodes
            snodeClient.BeginGetSupernodes(ar =>
            {
                try
                {
                    // check submitted list against the list of all supernodes
                    var validNodes = new SupernodeResponseData.Supernodes()
                    {
                        data = new List <SupernodeResponseData.Nodes>()
                    };

                    foreach (string userIp in result)
                    {
                        foreach (var node in ar.Content.data)
                        {
                            if (userIp != node.ip)
                            {
                                continue;
                            }

                            if (node.payoutAddress == null)
                            {
                                var bot = new TelegramBot(accessToken: ConfigurationManager.AppSettings[name: "accessKey"]);
                                var req = new SendMessage(chatId: chat.Id, text: "One of the nodes you have submitted is invalid, or has not been accepted into the supernode program yet, or it has not recieved its first payment. The invalid node was node registered. Please check your nodes and try again");

                                bot.MakeRequestAsync(request: req);

                                continue;
                            }

                            validNodes.data.Add(item: node);
                        }
                    }

                    // if the user wants to register a node
                    if (text.StartsWith(value: "/registerNode:") && text != "/registerNode:")
                    {
                        // automatically add the deposit account of each registered node as a monitored account
                        // nodes must be cross referenced with total supernode list to acquire the deposit address
                        // as the supernode API doesnt contain this information
                        string msg1;
                        try
                        {
                            AccountUtils.AddAccount(
                                chatId: chat.Id,
                                accounts: ar.Content.data.Where(predicate: x => validNodes.data.Any(predicate: y => y.ip == x.ip)).ToList()
                                .Select(selector: node => node.payoutAddress).ToList());

                            var nodesAdded = NodeUtils.AddNode(chatId: chat.Id, nodes: validNodes);


                            // return a message showing which accounts were registered
                            msg1 = ar.Content.data.Count > 0
                                ? nodesAdded.data.Aggregate(seed: "Nodes registered: \n \n", func: (current, n) => current + n.ip + "\n")
                                : "No nodes were added. It/they may be offline or have an invalid IP. Check your node ip's and try again";

                            // send message
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(value: e);
                            msg1 = "Something went wrong, please try again.";
                        }

                        var reqAction1 = new SendMessage(chatId: chat.Id, text: msg1);

                        Bot.MakeRequestAsync(request: reqAction1);
                    }

                    // if a user wants to unregister an account
                    if (text.StartsWith(value: "/unregisterNode:") && text != "/unregisterNode:")
                    {
                        string msg2;
                        try
                        {
                            // declare message assuming nothing goes wrong
                            msg2 = result.Length > 1 ? "Your nodes were removed" : "Your node was removed";

                            // make sure the user is registered
                            if (UserUtils.GetUser(chatId: chat.Id)?.ChatId != chat.Id)
                            {
                                // if not, tell them
                                var reqAction3 = new SendMessage(chatId: chat.Id, text: "You are not registered");
                                Bot.MakeRequestAsync(request: reqAction3);
                                return;
                            }

                            // get all user nodes
                            var userNodes = NodeUtils.GetNodeByUser(chatId: chat.Id);

                            // delete any nodes submitted
                            NodeUtils.DeleteNode(chatId: chat.Id, nodes: result.ToList());

                            // delete any associated deposit accounts that would have been automatically registered

                            AccountUtils.DeleteAccount(chatId: chat.Id,
                                                       accounts: userNodes.Where(predicate: y => AccountUtils.GetAccountByUser(chatId: chat.Id)
                                                                                 .Any(predicate: x => x.EncodedAddress == y.DepositAddress))
                                                       .Where(predicate: y => result.Any(predicate: x => x == y.IP))
                                                       .Select(selector: acc => acc.DepositAddress).ToList());
                        }
                        catch (Exception)
                        {
                            msg2 = "Something went wrong. Please try again. If the problem persists, please notify kodtycoon";
                        }

                        // send a message to notify user of any changes
                        var reqAction2 = new SendMessage(chatId: chat.Id, text: msg2);
                        Bot.MakeRequestAsync(request: reqAction2);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace);
                }
            }, 1);
        }
Ejemplo n.º 26
0
        //DBH DB = new DBH();

        // public DBHelper Db { get => db; set => db = value; }

        public void CheckState(Person person, TelegramBot bot, Tourist_BotEntities _context)
        {
            //User user = _context.Users.FirstOrDefault(x => x.Id == person.ChatID);  //comment**: if its necessary to keep track of repeated users
            //Console.WriteLine("");
            //if (user == null)
            //{
            //    //Console.WriteLine("");
            //    User newUser = new User();
            //    newUser.Id = person.ChatID;
            //    newUser.Message = person.Text;
            //    newUser.State = person.State;
            //    _context.Users.Add(newUser);
            //    try
            //    {
            //        _context.SaveChanges();
            //    }
            //    catch (Exception e) { Console.WriteLine(e.Message); }
            //}
            if (person.State == "Start" || person.Text == "Start" || person.Text == "start")
            ////////////inke dar state e city bkhahad ostan ra avaz knad dar enteha ezafe shavad.
            {
                string message = "به راهنمای ایران گردی خوش آمدید :)";
                var    reg     = new SendMessage(person.ChatID, message)
                {
                    ReplyMarkup = keyboard.StartState()
                };

                bot.MakeRequestAsync(reg);
                //   Console.WriteLine("avali");
                person.State = "Options";//taeen ink mkhahad ostan ezafe knd ya list bebinad
            }
            else if (person.State == "Options" && person.Text == "انتخاب استان")
            {
                string message = "استان مورد نظر خود را انتخاب کنید:";
                var    reg     = new SendMessage(person.ChatID, message)
                {
                    ReplyMarkup = keyboard.ProvinceState()
                };

                bot.MakeRequestAsync(reg);
                person.State = "City";
                //    Console.WriteLine("dovomi");
            }
            //else if (person.State == "City" && (person.Text == "تهران" || person.Text == "فارس"))// agar yek ostane alaki type shavad, nabaid peiqame entekhabe shahr namayesh dade shavad , ama in baiad dynamic shavad
            else if (person.State == "City" && person.Text != "انصراف")
            {
                string message = "شهر مورد نظر خود را انتخاب کنید:";
                long   proID   = _context.Provinces.Where(x => x.Name == person.Text).ToList()[0].Id;
                var    reg     = new SendMessage(person.ChatID, message)
                {
                    ReplyMarkup = keyboard.CityState(proID)
                };

                bot.MakeRequestAsync(reg);
                person.State = "Places";
                //  Console.WriteLine("dovomi");
            }

            /* else if (person.State == "Places" && person.Text == "")
             *   //////////chetori hame shahraye hame ostanaro check knm?? age ye halate koliam baram baz moshkele chert type kardan hast
             * {
             *   try
             *   {
             *       string message = "استان مورد نظر خود را انتخاب کنید:";
             *       var reg = new SendMessage(person.ChatID, message) { ReplyMarkup = keyboard.ProvinceState() };
             *
             *       bot.MakeRequestAsync(reg);
             *       person.State = "";
             *       Console.WriteLine("");
             *   }
             *   catch (Exception e)
             *   {
             *
             *       Console.WriteLine(e.Message);
             *   }
             *
             * }*///hich idei nadaram ina chian ... comment mikonam ziresh ok mikonam

            else if (person.State == "Places" && person.Text != "انصراف")
            {
                string message = "مکان های دیدنی به شرح زیر است. برای اطلاعات بیشتر مکان مورد نظر را انتخاب کنید";
                long   CitID   = _context.Cities.Where(x => x.Name == person.Text).ToList()[0].Id;
                var    reg     = new SendMessage(person.ChatID, message)
                {
                    ReplyMarkup = keyboard.PlaceState(CitID)
                };

                bot.MakeRequestAsync(reg);
                person.State = "Desc";
            }
            else if (person.State == "Desc" && person.Text != "انصراف")
            {
                string     message = _context.Places.Where(x => x.Name == person.Text).ToList()[0].Description;
                FileToSend F       = new FileToSend(_context.Places.Where(x => x.Name == person.Text).ToList()[0].Photo);
                bot.MakeRequestAsync(new SendPhoto(person.ChatID, F));
                var reg = new SendMessage(person.ChatID, message)
                {
                    ReplyMarkup = keyboard.StartState()
                };

                bot.MakeRequestAsync(reg);
                person.State = "Options";
            }
            //else if (person.State == "Places" && person.Text == "خروج")////////////in halat baarye tamame state ha baiad gozashte shavad
            else if (person.Text == "خروج")
            {
                string message = "خدانگهدار. می توانید مجدد آغاز کنید :)";
                var    reg     = new SendMessage(person.ChatID, message)
                {
                    ReplyMarkup = keyboard.OutState()
                };
                bot.MakeRequestAsync(reg);
                person.State = "Out";
                //  Console.WriteLine("sevomi");
            }
            else if (person.State == "Options" && person.Text == "اضافه کردن مکان جدید")
            {
                string message = "نام استان را وارد کنید";
                //  string message = person.pic;
                var reg = new SendMessage(person.ChatID, message)
                {
                    ReplyMarkup = keyboard.AddPlace()
                };

                bot.MakeRequestAsync(reg);
                person.State = "addPlace1";
            }
            else if (person.State == "addPlace1" && person.Text != "انصراف")

            {
                person.np_pro = person.Text;
                string message = "نام شهر را وارد کنید";
                var    reg     = new SendMessage(person.ChatID, message)
                {
                    ReplyMarkup = keyboard.AddPlace()
                };

                bot.MakeRequestAsync(reg);
                person.State = "addPlace2";
            }
            else if (person.State == "addPlace2" && person.Text != "انصراف")

            {
                person.np_city = person.Text;
                string message = "نام مکان را وارد کنید";
                var    reg     = new SendMessage(person.ChatID, message)
                {
                    ReplyMarkup = keyboard.AddPlace()
                };

                bot.MakeRequestAsync(reg);
                person.State = "addPlace3";
            }
            else if (person.State == "addPlace3" && person.Text != "انصراف")
            {
                person.np_name = person.Text;
                string message = "توضیحاتی در مورد این مکان وارد کنید";
                var    reg     = new SendMessage(person.ChatID, message)
                {
                    ReplyMarkup = keyboard.AddPlace()
                };
                bot.MakeRequestAsync(reg);
                person.State = "addPlace4";
            }

            else if (person.State == "addPlace4" && person.Text != "انصراف")
            {
                //if ok
                person.np_desc = person.Text;
                Console.WriteLine(person.np_pro + person.np_city + person.np_name + person.np_desc);

                /*  Place pl = new Place();
                 * City c = new City();
                 * Province pr = new Province();
                 * pr.Name = NewPlace.np_pro;
                 * c.Name = NewPlace.np_city;
                 * pl.Description = NewPlace.np_desc;
                 * pl.Name = NewPlace.np_name;
                 * _context.Provinces.Add(pr);
                 * try { _context.SaveChanges(); }
                 * catch (Exception e) { Console.WriteLine(e.Message); }
                 * //while(_context.Provinces.Where(x => x.Name == NewPlace.np_pro).ToList()[0].Id == 0) { }
                 * c.Province_Id = _context.Provinces.Where(x => x.Name == NewPlace.np_pro ).ToList()[0].Id;
                 * _context.Cities.Add(c);
                 * try { _context.SaveChanges(); }
                 * catch (Exception e) { Console.WriteLine(e.Message); }
                 * //while (_context.Cities.Where(x => x.Name == NewPlace.np_city).ToList()[0].Id == 0) { }
                 * pl.City_Id = _context.Cities.Where(x => x.Name == NewPlace.np_city).ToList()[0].Id;
                 * _context.Places.Add(pl);
                 */



                try { _context.SaveChanges(); }
                catch (Exception e) { Console.WriteLine(e.Message + "DB error"); }


                string message = "لطفا عکسی از مکان را ارسال کنید";
                var    reg     = new SendMessage(person.ChatID, message)
                {
                    ReplyMarkup = keyboard.AddPlace()
                };

                bot.MakeRequestAsync(reg);
                person.State  = "Pic";
                person.np_IsP = true;
            }
            else if (person.State == "Pic" && person.Text != "انصراف")
            {
                // NewPlace.np_pic = person.Pic;
                Console.WriteLine(person.np_pro + person.np_city + person.np_name + person.np_desc + person.Pic[0].FileId);
                //  _context.AddPlace("1", "2", "3", "4", "5");
                DBH.AddPlace(person.np_pro, person.np_city, person.np_name, person.np_desc, person.Pic[0].FileId);
                string message = "با تشکر از شما مکان جدید ثبت شد";
                var    reg     = new SendMessage(person.ChatID, message)
                {
                    ReplyMarkup = keyboard.StartState()
                };
                // GetChat(person.ChatID).

                bot.MakeRequestAsync(reg);
                person.State  = "Options";
                person.np_IsP = false;
            }
            else if (person.Text == "انصراف")
            {
                string message = "";
                if (person.State == "addPlace1" || person.State == "addPlace2" || person.State == "addPlace3" || person.State == "addPlace4" || person.State == "Pic")
                {
                    message = "اضافه کردن مکان جدید لغو شد";
                }
                else
                {
                    message = "جست و جو مکان لغو شد";
                }
                var reg = new SendMessage(person.ChatID, message)
                {
                    ReplyMarkup = keyboard.StartState()
                };

                bot.MakeRequestAsync(reg);
                person.State = "Options";
            }
            // user.State = person.State;          /////comment**
            //_context.SaveChanges();
        }
Ejemplo n.º 27
0
        public static async Task RunBot()
        {
            List <Person> UserList = new List <Person>();
            TelegramBot   bot      = new TelegramBot(Token);
            User          me       = await bot.MakeRequestAsync(new GetMe());

            Console.WriteLine("UserName Is: {0} And My Name Is {1}", me.Username, me.FirstName);
            long offset     = 0;
            int  whilecount = 0;

            while (true)
            {
                Console.WriteLine("WhileCount is:{0} ", whilecount);
                whilecount++;
                Update[] Updates = await bot.MakeRequestAsync(new GetUpdates()
                {
                    Offset = offset
                });

                Console.WriteLine("Update Count Is:{0}", Updates.Count());
                Console.WriteLine("--------------------------------------------");
                try
                {
                    foreach (Update Update in Updates)
                    {
                        offset = Update.UpdateId + 1;
                        string text = Update.Message.Text;
                        if (text == "/start")
                        {
                            SendMessage Message01 = new SendMessage(Update.Message.Chat.Id, "لطفا یک گزینه انتخاب کنید.")
                            {
                                ReplyMarkup = MainMenu
                            };
                            await bot.MakeRequestAsync(Message01);

                            if (!(Exist(Update.Message.Chat.Id, UserList)))
                            {
                                UserList.Add(new Person(Update.Message.Chat.FirstName, Update.Message.Chat.Username, Update.Message.Chat.Id));
                                Console.WriteLine("Name : " + Update.Message.Chat.FirstName + "\nUsername : "******"\nID: " + Update.Message.Chat.Id);
                                Console.WriteLine("---------------------------------------------");
                            }
                            continue;
                        }
                        else if (text != null && text.Contains("/aboutus") || text.Contains("📋درباره ی ما📋"))
                        {
                            SendMessage Message01 = new SendMessage(Update.Message.Chat.Id, "ربات درحال توسعه میباشد شکیبا باشید.")
                            {
                                ReplyMarkup = MainMenu
                            };
                            await bot.MakeRequestAsync(Message01);

                            continue;
                        }
                        else if (text != null && text.Contains("👤امتیاز شما👤") || text.Contains("/myscore"))
                        {
                            SendMessage Message01 = new SendMessage(Update.Message.Chat.Id, "ربات درحال توسعه میباشد شکیبا باشید.")
                            {
                                ReplyMarkup = MainMenu
                            };
                            await bot.MakeRequestAsync(Message01);

                            continue;
                        }
                        else if (text != null && text.Contains("📋درباره ی ربات📋") || text.Contains("/aboutbot"))
                        {
                            SendMessage Message01 = new SendMessage(Update.Message.Chat.Id, "\n🌐 ربات Gamealon 🌐\nما در این ربات از بروزترین ابزار برنامه نویسی بهره گرفته ایم تا بتوانیم لحظات خوشی رو برای شما به ارمغان بیاریم امیدواریم از بازی های این ربات لذت ببرید. \nهمچنین این ربات هر روز درحال ارتقا هست و تیم ما سخت در تلاش هست هر روز بخش جدیدی به این ربات اضافه کند.\nبه امید روزی که از نظر شما کاربران عزیز بهترین باشیم.")
                            {
                                ReplyMarkup = MainMenu
                            };
                            await bot.MakeRequestAsync(Message01);

                            continue;
                        }
                        else if (text != null && text.Contains("🕹شروع بازی🕹") || text.Contains("/startnewgame"))
                        {
                            SendMessage Message01 = new SendMessage(Update.Message.Chat.Id, "لطفا یک گزینه انتخاب کنید.")
                            {
                                ReplyMarkup = GameMenu
                            };
                            await bot.MakeRequestAsync(Message01);

                            continue;
                        }
                        else if (text != null && text.Contains("👥برترین کاربران👥") || text.Contains("/rank"))
                        {
                            SendMessage Message01 = new SendMessage(Update.Message.Chat.Id, "ربات درحال توسعه میباشد شکیبا باشید.")
                            {
                                ReplyMarkup = MainMenu
                            };
                            await bot.MakeRequestAsync(Message01);

                            continue;
                        }
                        if (text != null && text.Contains("👾حدس عدد👾"))
                        {
                            SendMessage Message01 = new SendMessage(Update.Message.Chat.Id, "ربات درحال حدس عدد میباشد.")
                            {
                                ReplyMarkup = MainMenu
                            };
                            await bot.MakeRequestAsync(Message01);

                            foreach (Person item in UserList)
                            {
                                if (item.ID == Update.Message.Chat.Id)
                                {
                                    item.Counter             = 0;
                                    item.ComputerGuessNumber = RandomNumber.RandomGenerator();
                                }
                                else
                                {
                                    SendMessage Message02 = new SendMessage(Update.Message.Chat.Id, "ربات را دوباره استارت کنید")
                                    {
                                        ReplyMarkup = MainMenu
                                    };
                                    await bot.MakeRequestAsync(Message02);

                                    continue;
                                }
                                foreach (Update UserGuessing in Updates)
                                {
                                    offset = UserGuessing.UpdateId + 1;
                                    string Guess = Update.Message.Text;
                                    if (Guess.Contains(item.ComputerGuessNumber) & item.Counter > 0)
                                    {
                                        item.Score = +1;
                                        SendMessage Message02 = new SendMessage(Update.Message.Chat.Id, "عدد را درست حدس زدید.")
                                        {
                                            ReplyMarkup = MainMenu
                                        };
                                        await bot.MakeRequestAsync(Message02);
                                    }
                                    else
                                    {
                                    }
                                }
                            }
                        }
                        if (text != null && text.Contains("🔙بازگشت به منوی اصلی🔙") || text.Contains("/mainmenu"))
                        {
                            SendMessage Message01 = new SendMessage(Update.Message.Chat.Id, "شما  در منوی اصلی هستید.")
                            {
                                ReplyMarkup = MainMenu
                            };
                            await bot.MakeRequestAsync(Message01);

                            continue;
                        }
                        else
                        {
                            SendMessage Message01 = new SendMessage(Update.Message.Chat.Id, "قابل مفهوم نبود.")
                            {
                                ReplyMarkup = MainMenu
                            };
                            await bot.MakeRequestAsync(Message01);

                            continue;
                        }
                    }
                }
                catch (Exception e)
                {
                    SendMessage MessageErrorForAhmad = new SendMessage(107091211, "\nسلام احمد \nربات GameAlon به مشکل بر خورده و ارور داده متن ارور: \n" + e.Message);  //SendMessage MessageErrorForAhmad = new SendMessage(107091211, "AhmadReza Robot " + me.Username + "  Error dde Matn Error ine " + e.Message + "Date : " + Date.Date + "Time : " + Date.Hour + ":" + Date.Minute + ":" + Date.Millisecond);
                    SendMessage MessageErrorForErfan = new SendMessage(107091211, "\nسلام عرفان \nربات GameAlon به مشکل بر خورده و ارور داده متن ارور: \n" + e.Message); //SendMessage MessageErrorForErfan = new SendMessage(562445249, "Erfan Robot " + me.Username + "  Error dde Matn Error ine " + e.Message + "Date : " + Date.Date + "Time : " + Date.Hour + ":" + Date.Minute + ":" + Date.Millisecond);
                    Console.WriteLine(e.Message + "Date : " + Date.Date + "Time : " + Date.Hour + ":" + Date.Minute + ":" + Date.Millisecond);
                    await bot.MakeRequestAsync(MessageErrorForAhmad);

                    await bot.MakeRequestAsync(MessageErrorForErfan);

                    throw;
                }
            }
        }
Ejemplo n.º 28
0
        public static async Task RunBot()
        {
            try
            {
                int lev = 0;

                var bot = new TelegramBot(ApiToken);
                var me  = await bot.MakeRequestAsync(new GetMe());

                Console.WriteLine($"UserName : {me.Username}");
                long offset     = 0;
                int  whileCount = 0;
                while (true)
                {
                    var updates = await bot.MakeRequestAsync(new GetUpdates()
                    {
                        Offset = offset
                    });

                    try
                    {
                        foreach (var update in updates)
                        {
                            offset = update.UpdateId + 1;
                            var text = update.Message.Text;
                            if (text.ToLower() == "/start" || text.ToLower() == "/new")
                            {
                                var chat = update.Message.Chat;
                                InsertLogedIn(chat.Username, chat.FirstName, chat.LastName);
                                var resp = new SendMessage(0, "");
                                resp = new SendMessage(update.Message.Chat.Id, $"درودبر شما به ربات انجمن علمی کامپیوتر خوش آمدید.{Environment.NewLine}لطفا یکی ار سرویس های زیر را انتخاب کنید")
                                {
                                    ReplyMarkup = serviceKeyboard
                                };
                                await bot.MakeRequestAsync(resp);
                            }
                            else if (text != null)
                            {
                                if (text.ToLower().Contains("دریافت چارت دروس رشته".Trim()))
                                {
                                    var resp = new SendMessage(update.Message.Chat.Id, "در کدام گرایش مشغول به تحصیل هستید؟")
                                    {
                                        ReplyMarkup = fieldsKeyboard
                                    };
                                    await bot.MakeRequestAsync(resp);

                                    lev = lev + 1;
                                    continue;
                                }
                                if (text.ToLower().Contains("نرم افزار".TrimEnd()))
                                {
                                    var resp1 = new SendMessage(update.Message.Chat.Id, "صبور باشید...");
                                    await bot.MakeRequestAsync(resp1);

                                    string path = AppDomain.CurrentDomain.BaseDirectory + @"\Images\Soft.jpg";
                                    path = path.Replace(@"\bin\Debug", "");
                                    using (var stream = System.IO.File.Open(path, FileMode.Open))
                                    {
                                        var resp = new SendPhoto(update.Message.Chat.Id, new FileToSend(stream, "Soft.jpg"));
                                        await bot.MakeRequestAsync(resp);

                                        continue;
                                    }
                                }
                                else if (text.ToLower().Contains("معماری سیستمهای کامپیوتری".TrimEnd()))
                                {
                                    var resp1 = new SendMessage(update.Message.Chat.Id, "صبور باشید...");
                                    await bot.MakeRequestAsync(resp1);

                                    string path = AppDomain.CurrentDomain.BaseDirectory + @"Images\Arch.jpg";
                                    path = path.Replace(@"\bin\Debug", "");
                                    using (var stream = System.IO.File.Open(path, FileMode.Open))
                                    {
                                        var resp = new SendPhoto(update.Message.Chat.Id, new FileToSend(stream, "Arch.jpg"));
                                        await bot.MakeRequestAsync(resp);

                                        continue;
                                    }
                                }
                                else if (text.ToLower().Contains("فناوری اطلاعات".ToLower()))
                                {
                                    var resp1 = new SendMessage(update.Message.Chat.Id, "صبور باشید...");
                                    await bot.MakeRequestAsync(resp1);

                                    string path = AppDomain.CurrentDomain.BaseDirectory + @"Images\IT.jpg";
                                    path = path.Replace(@"\bin\Debug", "");
                                    using (var stream = System.IO.File.Open(path, FileMode.Open))
                                    {
                                        var resp = new SendPhoto(update.Message.Chat.Id, new FileToSend(stream, "IT.jpg"));
                                        await bot.MakeRequestAsync(resp);

                                        continue;
                                    }
                                }
                                else
                                {
                                    var resp = new SendMessage(update.Message.Chat.Id, "دستور نامفهوم بود!");
                                    await bot.MakeRequestAsync(resp);

                                    continue;
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error : " + ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error : " + ex.Message);
            }
        }
Ejemplo n.º 29
0
        public static async Task RunBot()
        {
            var bot = new TelegramBot(Token) { WebProxy = new System.Net.WebProxy("127.0.0.1:6661") };
            var me = await bot.MakeRequestAsync(new GetMe());
            Console.WriteLine("usename is {0}", me.Username);
            long offset = 0;
            int whilecount = 0;
            
            


            while (true)
            {

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

                Console.WriteLine("----------------------------------------");



                try
                {
                    foreach (var update in updates)
                    {   
                        offset = update.UpdateId + 1;
                        var text = update.Message.Text;
                        Console.WriteLine(update.Message.From.FirstName + " and ID is : " + update.Message.Chat.Id + " : " + text);

                        if (text == "/start")
                        {
                            var req = new SendMessage(update.Message.Chat.Id, "چی میخوای؟");
                            await bot.MakeRequestAsync(req);
                            continue;
                        }
                        else if (text.Contains("گمشو") && update.Message.From.Username == "infeXno")
                        {
                            var req = new SendMessage(update.Message.Chat.Id, "دیگه دوستتون ندارم :(");
                            await bot.MakeRequestAsync(req);
                            var leave = new LeaveChat(update.Message.Chat.Id);
                            await bot.MakeRequestAsync(leave);
                        }
                        else if (text == "job is")
                        {
                            string xxx = Convert.ToString(job);
                            var req = new SendMessage(update.Message.Chat.Id, "job value is : " + xxx);
                            await bot.MakeRequestAsync(req);
                            continue;

                        }
                        else if (text.Contains("دلار"))
                        {

                            if (update.Message.From.Username != "infeXno")
                            {
                                    WebClient n = new WebClient();
                                    var json = n.DownloadString("http://www.tgju.org/?act=sanarateservice&client=tgju&noview&type=json");
                                    Arz a1 = JsonConvert.DeserializeObject<Arz>(json);
                                    string dollar = a1.sana_buy_usd.price;
                                    string toman = dollar.Remove(6);
                                    string nocomma = toman.Replace(",", "");

                                    var req = new SendMessage(update.Message.Chat.Id, "الان قیمت هر دلار " +nocomma + " تومن هستش");
                                    req.ReplyToMessageId = update.Message.MessageId;
                                    await bot.MakeRequestAsync(req);
                            }
                            else
                            {
                               
                                    WebClient n = new WebClient();
                                    var json = n.DownloadString("http://www.tgju.org/?act=sanarateservice&client=tgju&noview&type=json");
                                    Arz a1 = JsonConvert.DeserializeObject<Arz>(json);
                                    string dollar = a1.sana_buy_usd.price;
                                    string toman = dollar.Remove(6);
                                    string nocomma = toman.Replace(",", "");

                                    var req = new SendMessage(update.Message.Chat.Id, "ددی الان قیمت هر دلار " + nocomma + " تومن هستش ^^♥");
                                    req.ReplyToMessageId = update.Message.MessageId;
                                    await bot.MakeRequestAsync(req);
                            }
                            continue;
                        }

                        else if (text.Contains("چندمه") || text.Contains("تاریخ") || text.Contains("time") || text.Contains("ساعت چنده"))
                        {
                            PersianDateTime time = PersianDateTime.Now;
                            string h = time.Hour.ToString();
                            string m = time.Minute.ToString();
                            string s = time.Second.ToString();
                            string hms = (h + ":" + m + ":" + s);
                            string date = time.ToString("dddd d MMMM yyyy ساعت ");
                            string t = (date + hms);


                            if (update.Message.From.Username != "infeXno")
                            {
                                var req = new SendMessage(update.Message.Chat.Id, t);
                                req.ReplyToMessageId = update.Message.MessageId;
                                await bot.MakeRequestAsync(req);
                            }
                            else
                            {
                                var req = new SendMessage(update.Message.Chat.Id, "ددی امروز " + t + " هستش ♥ ");
                                req.ReplyToMessageId = update.Message.MessageId;
                                await bot.MakeRequestAsync(req);
                            }

                            continue;
                        }

                        else if (text == "/hava" || text == "/hava@petshibot")
                        {
                            string s = "با این دستور میتونم وضعیت آب و هوا رو بهت بگم  این شکلی میتونی استفاده کنی : \n /hava 'نام شهر'";
                            var req = new SendMessage(update.Message.Chat.Id, s);
                            req.ReplyToMessageId = (update.Message.MessageId);
                            await bot.MakeRequestAsync(req);
                            continue;
                        }
                        else if (text.Contains("/hava"))
                        {
                            string s1 = text;
                            char[] ch = new char[] { ' ' };
                            string[] result;
                            result = s1.Split(ch, 2);
                            string location = result[1];
                            WebClient n = new WebClient();
                            var json = n.DownloadString("http://api.apixu.com/v1/current.json?key=1c5183723cba412ab6a102839182910&q=" + location);
                            weather w1 = JsonConvert.DeserializeObject<weather>(json);
                            string temp = Convert.ToString(Convert.ToInt32(w1.current.temp_c));
                            string stat = w1.current.condition.text;

                            switch (w1.current.condition.code)
                            {
                                case 1000:
                                    string s = "امروز اونجا " + temp + " درجست و هوا صاف هستش ^^";
                                    var req = new SendMessage(update.Message.Chat.Id, s);
                                    req.ReplyToMessageId = (update.Message.MessageId);
                                    await bot.MakeRequestAsync(req); break;
                                case 1003:
                                    s = "امروز اونجا " + temp + " درجست و هوا نیمه ابری هستش ^^";
                                    req = new SendMessage(update.Message.Chat.Id, s);
                                    req.ReplyToMessageId = (update.Message.MessageId);
                                    await bot.MakeRequestAsync(req); break;
                                case 1006:
                                    s = "امروز اونجا " + temp + " درجست و هوا ابری هستش ^^";
                                    req = new SendMessage(update.Message.Chat.Id, s);
                                    req.ReplyToMessageId = (update.Message.MessageId);
                                    await bot.MakeRequestAsync(req); break;
                                case 1009:
                                    s = "امروز اونجا " + temp + " درجست و هوا کاملا ابری هستش ^^";
                                    req = new SendMessage(update.Message.Chat.Id, s);
                                    req.ReplyToMessageId = (update.Message.MessageId);
                                    await bot.MakeRequestAsync(req); break;
                                case 1030:
                                    s = "امروز اونجا " + temp + " درجست و هوا مرطوبه ^^";
                                    req = new SendMessage(update.Message.Chat.Id, s);
                                    req.ReplyToMessageId = (update.Message.MessageId);
                                    await bot.MakeRequestAsync(req); break;
                                case 1135:
                                    s = "امروز اونجا " + temp + " درجست و هوا مه آلود هستش ^^";
                                    req = new SendMessage(update.Message.Chat.Id, s);
                                    req.ReplyToMessageId = (update.Message.MessageId);
                                    await bot.MakeRequestAsync(req); break;
                                case 1183:
                                    s = "امروز اونجا " + temp + " درجست و یکم بارون میاد ^^";
                                    req = new SendMessage(update.Message.Chat.Id, s);
                                    req.ReplyToMessageId = (update.Message.MessageId);
                                    await bot.MakeRequestAsync(req); break;
                                case 1186:
                                    s = "امروز اونجا " + temp + " درجست و بعضی وقتا بارون میاد ^^";
                                    req = new SendMessage(update.Message.Chat.Id, s);
                                    req.ReplyToMessageId = (update.Message.MessageId);
                                    await bot.MakeRequestAsync(req); break;
                                case 1189:
                                    s = "امروز اونجا " + temp + " درجست و یه مقدار بارون داریم ^^";
                                    req = new SendMessage(update.Message.Chat.Id, s);
                                    req.ReplyToMessageId = (update.Message.MessageId);
                                    await bot.MakeRequestAsync(req); break;
                                case 1192:
                                    s = "امروز اونجا " + temp + " درجست و بارون زیادی داریم ^^";
                                    req = new SendMessage(update.Message.Chat.Id, s);
                                    req.ReplyToMessageId = (update.Message.MessageId);
                                    await bot.MakeRequestAsync(req); break;
                                case 1195:
                                    s = "امروز اونجا " + temp + " درجست و بارون زیادی داریم ^^";
                                    req = new SendMessage(update.Message.Chat.Id, s);
                                    req.ReplyToMessageId = (update.Message.MessageId);
                                    await bot.MakeRequestAsync(req); break;
                                default:
                                    s = "امروز اونجا " + temp + "درجست و " +stat + " هستش";
                                    req = new SendMessage(update.Message.Chat.Id, s);
                                    req.ReplyToMessageId = (update.Message.MessageId);
                                    await bot.MakeRequestAsync(req);
                                    break;
                            }








                            continue;
                        }

                        else if (text == "/mani" || text == "/mani@petshibot")
                        {
                            string s = "با این دستور میتونم معنی هر کلمه ای رو بهت بگم ^^ این شکلی میتونی استفاده کنی : \n /mani 'کلمه'";
                            var req = new SendMessage(update.Message.Chat.Id, s);
                            req.ReplyToMessageId = (update.Message.MessageId);
                            await bot.MakeRequestAsync(req);
                            continue;
                        }
                        else if (text.Contains("/mani"))
                        {
                            string s1 = text;
                            char[] ch = new char[] { ' ' };
                            string[] result;
                            result = s1.Split(ch, 2);
                            string kalame = result[1];
                            WebClient n = new WebClient();
                            var json = n.DownloadString("http://api.urbandictionary.com/v0/define?term=" + kalame);
                            mani m1 = JsonConvert.DeserializeObject<mani>(json);

                            if (m1.list.Length > 0)
                            {
                                string man = m1.list[0].definition + "\n\n Examples : \n" + m1.list[0].example;
                                string edit = man.Replace("[", "");
                                string edit1 = edit.Replace("]", "");
                                string edit2 = edit1.Replace("’", "");
                                var req = new SendMessage(update.Message.Chat.Id, edit2);
                                req.ReplyToMessageId = update.Message.MessageId;
                                await bot.MakeRequestAsync(req);
                            }
                            else
                            {
                                string man = "معنی این کلمه رو نتونستم پیدا کنم :(";
                                var req = new SendMessage(update.Message.Chat.Id, man);
                                req.ReplyToMessageId = update.Message.MessageId;
                                await bot.MakeRequestAsync(req);
                            }
                            continue;
                        }





                        ///////////////////////////////////////////////////////////////////
                        ///////////////////////////////////////////////////////////////////
                        ///////////////////////////////////////////////////////////////////

                            /////////////////SEND MY MESSAGE COMMAND PART/////////////////////

                            ///////////////////////////////////////////////////////////////////
                            ///////////////////////////////////////////////////////////////////
                            ///////////////////////////////////////////////////////////////////                        


                            ///////SEND MESSAGE FROM COMMAND CENTER/////////
                        else if (update.Message.From.Username == "infeXno" && update.Message.Chat.Id == -224286003)
                        {
                            string s1 = text;
                            char[] ch = new char[] { ' ' };
                            string[] result;
                            result = s1.Split(ch, 2);
                            long target = Convert.ToInt64(result[0]);
                            string str = result[1];
                            var req = new SendMessage(target, str); //my messages goes here !
                            await bot.MakeRequestAsync(req);
                            continue;
                        }


                        //////////////////////////PRIVATE PART/////////////////////////////
                        //////////////////////////PRIVATE PART/////////////////////////////
                        //////////////////////////PRIVATE PART/////////////////////////////
                        //////////////////////////PRIVATE PART/////////////////////////////
                        //////////////////////////PRIVATE PART/////////////////////////////
                        //////////////////////////PRIVATE PART/////////////////////////////
                        //////////////////////////PRIVATE PART/////////////////////////////
                        //////////////////////////PRIVATE PART/////////////////////////////
                        //////////////////////////PRIVATE PART/////////////////////////////
                        //////////////////////////PRIVATE PART/////////////////////////////
                        //////////////////////////PRIVATE PART/////////////////////////////
                        //recieve privates 
                        //and answer them
                        else if (update.Message.Chat.Type == "private")
                        {
                            var req = new SendMessage(-224286003, update.Message.Chat.Id + "");
                            await bot.MakeRequestAsync(req);

                            var forw = new ForwardMessage(-224286003, update.Message.Chat.Id, update.Message.MessageId);
                            await bot.MakeRequestAsync(forw);

                            //////////////////////KNOWN PEOPLE//////////////////////

                          

                        ////////////////REGULAR GROUP SETTINGS//////////////////////
                        ////////////////REGULAR GROUP SETTINGS//////////////////////
                        ////////////////REGULAR GROUP SETTINGS//////////////////////
                        ////////////////REGULAR GROUP SETTINGS//////////////////////
                        ////////////////REGULAR GROUP SETTINGS//////////////////////
                        ////////////////REGULAR GROUP SETTINGS//////////////////////
                        ////////////////REGULAR GROUP SETTINGS//////////////////////
                        else if (update.Message.Chat.Type == "supergroup" || update.Message.Chat.Type == "group")
                        {

                            if (update.Message.From.Id == 226349493) /////this is ME
                            {

                                if (text.Contains("دختر") || text.Contains("ربات"))
                                {
                                    string[] asd = new string[] { " یس ددی", "ددیم ♥", " ♥:))" };
                                    Random rnd = new Random();
                                    int rand = rnd.Next(0, 2);


                                    var jvb = new SendMessage(update.Message.Chat.Id, asd[rand]);
                                    jvb.ReplyToMessageId = update.Message.MessageId;
                                    await bot.MakeRequestAsync(jvb);
                                }

                                else if (text.Contains("/off"))
                                {
                                    var req = new SendMessage(update.Message.Chat.Id, "ربات خاموش شد.");
                                    await bot.MakeRequestAsync(req);
                                    job = 0;
                                }
                                else if (text.Contains("/on"))
                                {
                                    var req = new SendMessage(update.Message.Chat.Id, "اماده خدمت :)");
                                    await bot.MakeRequestAsync(req);
                                    job = 1;
                                }
                                else if (update.Message.ReplyToMessage.From.Id == 373634438)
                                {
                                    string[] asd = new string[] { "لاو یو ددی", ":* بوچ بوچ", "^^", "+__+" };
                                    Random rnd = new Random();
                                    int rand = rnd.Next(0, 3);

                                    var jvb = new SendMessage(update.Message.Chat.Id, asd[rand]);
                                    jvb.ReplyToMessageId = update.Message.MessageId;
                                    await bot.MakeRequestAsync(jvb);
                                }
                                else if (update.Message.ReplyToMessage.From.Id == 373634438 && text.Contains("salam") || text.Contains("سلم") || text.Contains("سلام") || text.Contains("slm"))
                                {
                                    string[] asd = new string[] { " های ددی", " سلام ددیمون", " :))", "سلام ددی ♥ :))" };
                                    Random rnd = new Random();
                                    int rand = rnd.Next(0, 3);

                                    var req = new SendMessage(update.Message.Chat.Id, asd[rand]);
                                    req.ReplyToMessageId = update.Message.MessageId;
                                    await bot.MakeRequestAsync(req);
                                }
                            }
                            else if (text.Contains("ربات"))
                            {

                                string[] asd = new string[] { "؟؟", "چیه ", " بله" };
                                Random rnd = new Random();
                                int rand = rnd.Next(0, 2);

                                var jvb = new SendMessage(update.Message.Chat.Id, asd[rand]);
                                jvb.ReplyToMessageId = update.Message.MessageId;
                                await bot.MakeRequestAsync(jvb);
                            }
                            else if (update.Message.From.Username != "infeXno" && text.Contains("خوب") || text.Contains("بد") || text.Contains("اره"))
                            {
                                if (update.Message.ReplyToMessage.From.Id == 373634438)
                                {
                                    string[] asd = new string[] { " خوبه", " خدارو شکر", " :))" };
                                    Random rnd = new Random();
                                    int rand = rnd.Next(0, 5);

                                    if (rand <= 2)
                                    {
                                        var jvb = new SendMessage(update.Message.Chat.Id, asd[rand]);
                                        jvb.ReplyToMessageId = update.Message.MessageId;

                                        await bot.MakeRequestAsync(jvb);
                                    }
                                }
                            }
                        
                            else if (update.Message.ReplyToMessage.From.Id == 373634438 && text.Contains("salam") || text.Contains("سلم") || text.Contains("سلام") || text.Contains("slm"))
                            {

                                string[] asd = new string[] { " سلام", "  سلام :))", "های" };
                                Random rnd = new Random();
                                int rand = rnd.Next(0, 2);

                                var req = new SendMessage(update.Message.Chat.Id, asd[rand]);
                                req.ReplyToMessageId = update.Message.MessageId;
                                await bot.MakeRequestAsync(req);
                                continue;

                            }
                           
                            
                        }


                    }
                }
                catch (WebException)
                {

                        foreach (var update in updates)
                        {
                            var req = new SendMessage(update.Message.Chat.Id, "پیدا نکردم :(");
                            req.ReplyToMessageId = update.Message.MessageId;
                            await bot.MakeRequestAsync(req);
                        }


                }
                catch (Exception)
                {
                    continue;
                }

            }
        }
Ejemplo n.º 30
0
        public static void RunBot(string accessToken)
        {
            var bot = new TelegramBot(accessToken, new HttpClient());

            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.OutputEncoding = System.Text.Encoding.UTF8;
            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;
                        var contact  = update.Message.Contact;
                        var location = update.Message.Location;
                        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 HttpClient();
                            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();
                                var bytes        = webClient.GetByteArrayAsync(file.FileDownloadUrl).Result;
                                System.IO.File.WriteAllBytes(tempFileName, bytes);
                                Console.WriteLine("    Saved to {0}", tempFileName);
                            }
                        }
                        if (contact != null)
                        {
                            var req = new SendContact(update.Message.Chat.Id, contact.PhoneNumber, contact.FirstName)
                            {
                                LastName = contact.LastName
                            };
                            bot.MakeRequestAsync(req).Wait();
                        }
                        if (location != null)
                        {
                            var req = new SendLocation(update.Message.Chat.Id, location.Latitude, location.Longitude);
                            bot.MakeRequestAsync(req).Wait();
                        }

                        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).GetTypeInfo().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).GetTypeInfo().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).GetTypeInfo().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[] { new KeyboardButton("/photo"), new KeyboardButton("/doc"), new KeyboardButton("/docutf8") },
                                    new[] { new KeyboardButton("/contact")
                                            {
                                                RequestContact = true
                                            }, new KeyboardButton("/location")
                                            {
                                                RequestLocation = true
                                            } },
                                    new[] { new KeyboardButton("/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 (text == "/longmsg")
                        {
                            var msg = new string('X', 10240);
                            bot.MakeRequestAsync(new SendMessage(update.Message.Chat.Id, msg)).Wait();
                            continue;
                        }
                        if (update.Message.Text.Length % 2 == 0)
                        {
                            bot.MakeRequestAsync(new SendMessage(
                                                     update.Message.Chat.Id,
                                                     "You wrote: \r\n" + update.Message.Text.MarkdownEncode())
                            {
                                ParseMode = SendMessage.ParseModeEnum.Markdown
                            }).Wait();
                        }
                        else
                        {
                            bot.MakeRequestAsync(new ForwardMessage(update.Message.Chat.Id, update.Message.Chat.Id, update.Message.MessageId)).Wait();
                        }
                    }
                }
            }
        }
Ejemplo n.º 31
0
        public static void Run_Bot()
        {
            //making the bot
            var Bot = new TelegramBot(Token);
            var me  = Bot.MakeRequestAsync(new GetMe()).Result;


            //creating for each user a specific id to have it's own state
            var UserId = new Dictionary <long, int>();
            int cnt    = 0;

            //getting the list of person in ram
            //List<Person> persons = new List<Person>();
            long offset = 0;
            long IID    = 0;

            DBTestDataContext db = new DBTestDataContext();

            while (true)
            {
                var updates = Bot.MakeRequestAsync(new GetUpdates()
                {
                    Offset = offset
                }).Result;
                try
                {
                    foreach (var update in updates)
                    {
                        Console.WriteLine(update.Message.Text);

                        /**
                         * long ChatID = update.Message.Chat.Id;
                         * if (!UserId.ContainsKey(ChatID))
                         * {
                         *  UserId.Add(ChatID, cnt);
                         *  cnt++;
                         * }
                         * else
                         * {
                         *
                         * }
                         * offset = update.UpdateId + 1;
                         * /**/
                        string text   = update.Message.Text;
                        long   ChatID = update.Message.Chat.Id;
                        if (text == "/start")
                        {
                            string message = "به بات خوش آمدید :\\";
                            var    reg     = new SendMessage(ChatID, message);
                            Bot.MakeRequestAsync(reg);
                        }
                        else
                        {
                            Test t = new Test();
                            t.Id      = IID;
                            t.Message = text;
                            db.Tests.InsertOnSubmit(t);
                            try { db.SubmitChanges(); }
                            catch (Exception e) { Console.WriteLine(e.Message); }
                            string message = "گفتی: " + text + "😐😐";
                            var    reg     = new SendMessage(ChatID, message);
                            Bot.MakeRequestAsync(reg);
                        }
                        offset = update.UpdateId + 1;
                        IID++;
                    }
                }
                catch (Exception e) { Console.WriteLine(e.Message); }
            }
        }
Ejemplo n.º 32
0
        public static async Task RunBot()
        {
            TelegramBot bot = new TelegramBot(Token);
            User        me  = await bot.MakeRequestAsync(new GetMe());

            Console.WriteLine("UserName Is: {0} And My Name Is {1}", me.Username, me.FirstName);
            long offset     = 0;
            int  whilecount = 0;

            while (true)
            {
                Console.WriteLine("WhileCount is:{0} ", whilecount);
                whilecount++;
                Update[] Updates = await bot.MakeRequestAsync(new GetUpdates()
                {
                    Offset = offset
                });

                Console.WriteLine("Update Count Is:{0}", Updates.Count());
                Console.WriteLine("--------------------------------------------");
                try
                {
                    foreach (Update Update in Updates)
                    {
                        offset = Update.UpdateId + 1;
                        string text = Update.Message.Text;
                        if (text == "/start")
                        {
                            User User = new User();
                            Console.WriteLine(User.Id);
                            SendMessage Message01 = new SendMessage(Update.Message.Chat.Id, "لطفا یک گزینه انتخاب کنید.")
                            {
                                ReplyMarkup = MainMenu
                            };
                            await bot.MakeRequestAsync(Message01);

                            continue;
                        }
                        else if (text != null && text.Contains("/aboutus") || text.Contains("📋درباره ی ما📋"))
                        {
                            SendMessage Message01 = new SendMessage(Update.Message.Chat.Id, "ربات درحال توسعه میباشد شکیبا باشید.")
                            {
                                ReplyMarkup = MainMenu
                            };
                            await bot.MakeRequestAsync(Message01);

                            continue;
                        }
                        else if (text != null && text.Contains("👥امتیاز شما👥") || text.Contains("/myscore"))
                        {
                            SendMessage Message01 = new SendMessage(Update.Message.Chat.Id, "ربات درحال توسعه میباشد شکیبا باشید.")
                            {
                                ReplyMarkup = MainMenu
                            };
                            await bot.MakeRequestAsync(Message01);

                            continue;
                        }
                        else if (text != null && text.Contains("📋درباره ی ربات📋") || text.Contains("/aboutbot"))
                        {
                            SendMessage Message01 = new SendMessage(Update.Message.Chat.Id, "\n🌐 ربات Gamealon 🌐\nما در این ربات از بروزترین ابزار برنامه نویسی بهره گرفته ایم تا بتوانیم لحظات خوشی رو برای شما به ارمغان بیاریم امیدواریم از بازی های این ربات لذت ببرید. \nهمچنین این ربات هر روز درحال ارتقا هست و تیم ما سخت در تلاش هست هر روز بخش جدیدی به این ربات اضافه کند.\nبه امید روزی که از نظر شما کاربران عزیز بهترین باشیم.")
                            {
                                ReplyMarkup = MainMenu
                            };
                            await bot.MakeRequestAsync(Message01);

                            continue;
                        }
                        else if (text != null && text.Contains("🕹شروع بازی🕹") || text.Contains("/startnewgame"))
                        {
                            SendMessage Message01 = new SendMessage(Update.Message.Chat.Id, "لطفا یک گزینه انتخاب کنید.")
                            {
                                ReplyMarkup = GameMenu
                            };
                            await bot.MakeRequestAsync(Message01);

                            continue;
                        }
                        else if (text != null && text.Contains("👥برترین کاربران👥") || text.Contains("/rank"))
                        {
                            SendMessage Message01 = new SendMessage(Update.Message.Chat.Id, "ربات درحال توسعه میباشد شکیبا باشید.")
                            {
                                ReplyMarkup = MainMenu
                            };
                            await bot.MakeRequestAsync(Message01);

                            continue;
                        }
                        if (text != null && text.Contains("👾حدس عدد👾"))
                        {
                            SendMessage Message01 = new SendMessage(Update.Message.Chat.Id, "ربات درحال توسعه میباشد شکیبا باشید.")
                            {
                                ReplyMarkup = MainMenu
                            };
                            await bot.MakeRequestAsync(Message01);

                            continue;
                        }
                        if (text != null && text.Contains("🔙بازگشت به منوی اصلی🔙") || text.Contains("/mainmenu"))
                        {
                            SendMessage Message01 = new SendMessage(Update.Message.Chat.Id, "شما  در منوی اصلی هستید.")
                            {
                                ReplyMarkup = MainMenu
                            };
                            await bot.MakeRequestAsync(Message01);

                            continue;
                        }
                        else
                        {
                            SendMessage Message01 = new SendMessage(Update.Message.Chat.Id, "قابل مفهوم نبود.")
                            {
                                ReplyMarkup = MainMenu
                            };
                            await bot.MakeRequestAsync(Message01);

                            continue;
                        }
                    }
                }
                catch (Exception e)
                {
                    SendMessage MessageErrorForAhmad = new SendMessage(107091211, "AhmadReza Robot " + me.Username + "  Error dde Matn Error ine " + e.Message + "Date : " + Date.Date + "Time : " + Date.Hour + ":" + Date.Minute + ":" + Date.Millisecond);
                    SendMessage MessageErrorForErfan = new SendMessage(562445249, "Erfan Robot " + me.Username + "  Error dde Matn Error ine " + e.Message + "Date : " + Date.Date + "Time : " + Date.Hour + ":" + Date.Minute + ":" + Date.Millisecond);
                    Console.WriteLine(e.Message + "Date : " + Date.Date + "Time : " + Date.Hour + ":" + Date.Minute + ":" + Date.Millisecond);
                    throw;
                }
            }
        }