Example #1
0
        public async new Task <ActionResult> TellMeTelegram()
        {
            Stream req = Request.InputStream;

            req.Seek(0, SeekOrigin.Begin);
            string json = new StreamReader(req).ReadToEnd();

            // JSON to C# Ojbect
            TelegramWebhookUpdate result = new JavaScriptSerializer().Deserialize <TelegramWebhookUpdate>(json);

            // Save chat logs into database
            TelegramResponse response = new TelegramResponse();

            response.JsonData = "Text Message: " + result.message.text + " | JSON Response: " + json;
            db.Responses.Add(response);
            db.SaveChanges();

            // Check awaitable messages
            var awaitable = db.Awaitable.Where(i => i.UserId == result.message.from.id && i.Awaiting == true).FirstOrDefault();

            if (awaitable != null)
            {
                await ProcessAwaitableMessage(awaitable, result);

                return(null);
            }

            // Process initial messages
            await ProcessInitialMessage(result);

            return(null);
        }
        public void Run()
        {
            try
            {
                Timer timer = new Timer(6000);
                timer.AutoReset = true;
                bool timerFlag = false;
                timer.Elapsed += (x, y) => timerFlag = true;
                timer.Start();
                Console.OutputEncoding = Encoding.UTF8;
                while (true)
                {
                    TelegramResponse ResponseFromTelegram = telegramBot.GetUpdate(storage.GetLastUpdateTelegramFromStorage());
                    if (ResponseFromTelegram.result.Count > 0)
                    {
                        TelegramActions operation = new TelegramActions();

                        foreach (var result in ResponseFromTelegram.result)
                        {
                            loger.WriteLog($"Message from {result.message.from.username}\n" +
                                           $"Message Text {result.message.text} \n{DateTime.Now.ToShortTimeString()}");
                            operation.GetCommandFromMessage(result.message.text).ExecuteCommand(result, ref storage, ref telegramBot, ref viewer);
                        }
                        int MaxUpdate = ResponseFromTelegram.result.Max(X => X.update_id);
                        storage.SaveTelegramUpdateToStorage((MaxUpdate + 1).ToString());
                    }
                    if (timerFlag)
                    {
                        DevByParser  parser     = new DevByParser();
                        List <Event> currEvents = parser.GetEvents(2);
                        storage.SaveNewEventsToStorage(currEvents);
                        List <Event> newEvents = storage.GetNewEventsFromStorageForUser("0");
                        if (newEvents.Count > 0)
                        {
                            foreach (var @event in newEvents)
                            {
                                telegramBot.SendMessageMDCustom(viewer.ToMdFormat(@event),
                                                                int.Parse(ConfigurationManager.AppSettings.Get("ChatGeneral ID")));
                            }
                        }
                        timerFlag = false;
                    }
                }
            }
            catch (AggregateException ex)
            {
                foreach (var x in ex.InnerExceptions)
                {
                    loger.WriteLog(x.ToString());
                    telegramBot.SendMessageMe(x.ToString());
                }
            }
        }
Example #3
0
        /// <summary>
        /// 读取信息
        /// </summary>
        public IEnumerable <getUpdatesResponse>?getUpdates(long offset = 0)
        {
            string url     = $"{this.Url}bot{this.Token}/getUpdates?offset={offset}";
            string content = NetAgent.DownloadData(url, Encoding.UTF8);
            TelegramResponse <getUpdatesResponse[]>?response = JsonConvert.DeserializeObject <TelegramResponse <getUpdatesResponse[]> >(content);

            if (response == null || !response)
            {
                return(null);
            }
            return((getUpdatesResponse[])response);
        }
Example #4
0
        /// <summary>
        /// Make telegram API call to get messages
        /// </summary>
        private void GetMessagesFromTelegram()
        {
            try
            {
                // Check more than 5 seconds have elapsed since we last requested anything
                TimeSpan ts = _stopWatch.Elapsed;
                if (ts.Seconds < 5)
                {
                    return;
                }

                RestRequest request = new RestRequest("/bot" + _token + "/getUpdates", Method.GET);

                //Add an update id if we have one to avoid getting lots of messages back again and again
                if (!String.IsNullOrEmpty(_lastUpdateId))
                {
                    request.AddParameter("offset", (Int32.Parse(_lastUpdateId) + 1).ToString());
                }

                // Execute the request
                RestResponse response = (RestResponse)_client.Execute(request);

                // Raw content as string
                var content = response.Content;

                if (String.IsNullOrWhiteSpace(content))
                {
                    return;
                }

                TelegramResponse data = JsonConvert.DeserializeObject <TelegramResponse>(content);

                // Verify something was deserialised and that the returned data is ok
                if (data == null || !data.ok)
                {
                    return;
                }

                foreach (TelegramResult result in data.result)
                {
                    try {
                        //Check the messages are coming from the correct chat group - We only work with one group at a time
                        if (result.message.chat.id == _clientID)
                        {
                            //Store the last update id for user on the next api call
                            _lastUpdateId = result.update_id;

                            string text     = result.message.text;
                            string username = result.message.from.username;

                            TelegramPhoto[] photo = result.message.photo;

                            if (text != null)
                            {
                                _messages.Enqueue(new TelegramReadResponse(text, username));
                            }
                            else if (photo != null)
                            {
                                string filePath   = GetPhotoFilePath(photo[photo.Length - 1].file_id);
                                byte[] imageBytes = GetPhoto(filePath);

                                if (imageBytes != null)
                                {
                                    _messages.Enqueue(new TelegramReadResponse(imageBytes));
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        Console.Write(ex.StackTrace);
                    }
                }

                // Restart the stopwatch to indicate a successful read from telegram
                _stopWatch.Restart();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.Write(ex.StackTrace);
                //return $"Error when trying to get messages from Telegram. Error: {ex.Message}";
            }
        }
Example #5
0
 public TelegramApiException(string response)
     : base(response)
 {
     Response = JsonConvert.DeserializeObject <TelegramResponse>(response);
 }