Example #1
0
        /// <summary>
        /// Use this method to send multimedia files. On success, the sent Message is returned.
        /// </summary>
        /// <param name="chat_id">Unique identifier for the message recipient — User or GroupChat id.</param>
        /// <param name="file_path">File to send. You can upload a new file using multipart/form-data.</param>
        /// <param name="type">Type of file to send.</param>
        /// <param name="reply_markup">Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user.</param>
        /// <param name="caption">Photo caption (only use with Type.Photo).</param>
        /// <param name="reply_to_message_id">If the message is a reply, ID of the original message.</param>
        /// <returns></returns>
        public Message SendMultimedia(int chat_id, string file_path, MultimediaType type, ReplyKeyboardHide reply_markup, string caption = null, int reply_to_message_id = -1)
        {
            string url = BaseUrl + "send" + type.ToString();

            byte[] file = null;
            using (var content = new MultipartFormDataContent("-------BotAPIDotNET"))
            {
                content.Add(new StringContent(string.Format("{0}", chat_id)), "chat_id");
                var fileStream = File.Open(file_path, FileMode.Open, FileAccess.Read);
                content.Add(new StreamContent(fileStream), type.ToString().ToLower(), file_path.Replace("\\", "/").Split('/').LastOrDefault());
                if (!string.IsNullOrEmpty(caption) && type == MultimediaType.Photo)
                    content.Add(new StringContent(caption), "caption");
                if (reply_to_message_id != -1)
                    content.Add(new StringContent(string.Format("{0}", reply_to_message_id)), "reply_to_message_id");
                if (reply_markup != null)
                    content.Add(new StringContent(JsonConvert.SerializeObject(reply_markup, Formatting.None)), "reply_markup");

                Stream multipart = content.ReadAsStreamAsync().Result;
                file = new byte[multipart.Length];
                multipart.Seek(0, SeekOrigin.Begin);
                multipart.Read(file, 0, (int)multipart.Length);
            }

            var request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "multipart/form-data; boundary=\"-------BotAPIDotNET\"";
            request.Method = "POST";

            using (Stream writer = request.GetRequestStream())
            {
                writer.Write(file, 0, file.Length);
            }

            var response = (HttpWebResponse)request.GetResponse();
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            return ParseResponseMessage(responseString);
        }