텔레그램 봇을 사용해서 메시지를 보낼 수 있다길래...
닷넷과 함께 메시지를 보내보기 위해서 만들어보았다.
일단은 메시지만...
텔레그램 봇 만들기와, 봇의 토큰 알아내기, 그리고 나와의 채팅방에서 챗아이디 가져오는 방법은
다른 블로그를 통해 알아보자 ~
//텔레그램 메시지 클래스
public static class TMessage
{
static string chatID = "chatID";
static string token = "111:aaaa";
static string TelegramAPI = "https://api.telegram.org/bot{0}/sendMessage";
public static void Send(string msg)
{
string result = string.Empty;
HttpPost(string.Format(TelegramAPI, token)
, new Dictionary<string, string> {
{ "chat_id", chatID }
, { "text", msg) }
}, out result);
}
public static bool HttpPost(string url, Dictionary<string, string> paramList, out string Msg)
{
bool _flag = false;
HttpWebRequest req = WebRequest.Create(new Uri(url)) as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/json";
// Build a string with all the params, properly encoded.
// We assume that the arrays paramName and paramVal are
// of equal length:
StringBuilder paramz = new StringBuilder();
paramz.Append("{");
foreach (KeyValuePair<string, string> param in paramList)
{
paramz.AppendFormat("\"{0}\" : \"{1}\", ", param.Key, param.Value);
}
paramz = paramz.Remove(paramz.Length - 2, 2);
paramz.Append("}");
// Encode the parameters as form data:
byte[] formData = UTF8Encoding.UTF8.GetBytes(paramz.ToString());
req.ContentLength = formData.Length;
// Send the request:
using (Stream post = req.GetRequestStream())
{
post.Write(formData, 0, formData.Length);
post.Flush();
}
// Pick up the response:
using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
{
if (resp.StatusCode == HttpStatusCode.OK)
{
_flag = true;
}
StreamReader reader = new StreamReader(resp.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
Msg = reader.ReadToEnd();
}
return _flag;
}
}