2024년 1월 29일 월요일

C# 텔레그램 알리미

알림중요하다..  메시지 보내는 방법이 

돈내고 보낼라면 SMS전송서비스나 카톡 API 돈내고 보내면 된다.

무료로 보낼라면 앱을 만들어서 firebase 토큰등록 하고 

어쩌고 저쩌고 해야된다..  (알림이 목적인데 앱을 만들겠냐고!!)

마켓입점비용도 내야되고..


지금 현시점에서 가장 저렴하게 알림 메시지를 보내는 방법은

텔레그램 채팅봇 이라고 생각한다.

그래서 이렇게 해서 전달하면 무료로 메시지를 전달할수 있다.


텔레그램 봇 만드는거야 인터넷에 널렸으니까 건너뛰고

(참고로 텔레그램봇은 알림보다는 채팅방에 쓰는 명령어로

적절한 응답을 하기위함이 존재의 목적이 더 크다..

그리고 봇에서 채팅하는 내용은 봇과 나와의 대화이다.

많이 사람이 그 봇 채팅방에 있다고 하더라도 다른사람의 내용은 보여지지 않는다.)

암튼 그 봇채널방에 초대링크 t.me 어쩌고 이런거 qr로 되어있으니까 

만들어서 상대방한테 줘서 초대하고 chat id 까지 받는다.

chat id는 채팅방 검색에서 get id 라는 봇이 있는데 거기서 /start 

때리면 내 채팅 아이디번호 알려준다.

그리고 bot토큰도 알아야하는데 이건 봇만든 사람이 해당 대화방에서

수정아이콘 클릭해서  봇설정 변경 누르면 봇파더 대화방으로 가는데 

거기서 API Token 버튼 누르면 다시 알려준다.

그리고 나서 C#으로 해당하는 봇에 메시지 보내는 방법은 다음처럼


static void Main(string[] args)
{
     //봇ID-토큰값
     string botid = "봇토큰";
     //메시지 전달받는사람 chat_id (쉼표로 구분하여 봇채널에있는 특정대상들에게 전송가능)
     string mychatid = "전달할사람 chat_id";    

     //전달내용
     List<string> list = new List<string>(){
         "안녕?",
         "나는 김반장이라고해"
     };
     string sendMsg = string.Join("\r\n", list);

     //전송결과
     bool bsented = SendTelegramBotMessage(botid, mychatid, sendMsg);
     Console.WriteLine("tg전송결과: " + bsented.ToString());
     Console.ReadLine();
}

//tg으로 전달하기
public static bool SendTelegramBotMessage(string botid, string chatids, string aMessage)
{
     try {
         //url
         string sendurl = string.Format("https://api.telegram.org/bot{0}/sendmessage", botid);
         string postData = "chat_id=" + chatids + "&text=" + aMessage;

         //request
         HttpWebRequest httpwebRequest = (HttpWebRequest)WebRequest.Create(sendurl);
         byte[] sendData = Encoding.UTF8.GetBytes(postData);
         httpwebRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
         httpwebRequest.Timeout = 5000;     //5초 타임아웃
         httpwebRequest.Method = "POST";
         httpwebRequest.ContentLength = sendData.Length;
         Stream requestStream = httpwebRequest.GetRequestStream();
         requestStream.Write(sendData, 0, sendData.Length);
         requestStream.Close();

         //response
         HttpWebResponse response = (HttpWebResponse)httpwebRequest.GetResponse();
         StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
         string retvalue = reader.ReadToEnd();
         HttpStatusCode statusCode = response.StatusCode;
         reader.Close();
         response.Close();

         //
         if (statusCode != HttpStatusCode.OK)
         {
             Debug.WriteLine("메시지 전송실패!! 확인바랍니다.");
             return false;
         } else {
             Debug.WriteLine("메시지 전송성공!!");
             return true;
         }
     } catch (Exception ex) {
         Debug.WriteLine(ex.Message);
         return false;
     }
}

요로코롬 하면된다..

댓글 없음:

댓글 쓰기