본문 바로가기

취미생활/C#

[C#] 텔레그램 API를 이용한 메세지 보내기

반응형

안녕하세요

 

코딩하는 남자 "코딩연습생"입니다

 

저번 시간에 윈도우 핸들러를 통해 카카오톡PC 버전에서 메세지 보내기를 게시했는데요

 

이번에는 텔레그램 API를 통해 C#에서 메세지를 보내는 방법을 구현해 볼려고 합니다

 

요즘은 모둔 매신져들이 PC와 연계를 많이 하고 있는 추세이고 코딩에 대한 API도 많이 제공되고 있어서

 

무한한 가능성이 생겨나고 있는거 같습니다

 

다시 본론으로 돌아와서 텔레그램을 C#으로 불러오기 위해서는 몇가지 설정이 입니다

 

[사전 준비 사항]

 

1. 텔레그램 가입하기

2. Bot을 통한 나만의 Bot을 생성한다

3. API Key를 부여 받는다

 

이렇게 3가지를 사전 준비해야 합니다 방법은 아주 간단합니다

 

텔레그램을 가입하기 위해 텔레그램 싸이트 접속

: https://web.telegram.org

 

Telegram Web

Welcome to the Web application of Telegram messenger. See https://github.com/zhukov/webogram for more info.

web.telegram.org

 

위 링크로 접속하셔서 가입 or 로그인을 해줍니다

 

 

로그인 뒤에 옆 친구리시트 중에 다음과 같은 BotFather를 클릭해 줍니다

 

번역하면 봇아버지ㅋㅋ

 

그다음 봇 아버지에게 다음과 같이 말을 겁니다

 

 

/start 텔레그램을 시작하겠다는 말을 봇아버지에게 하는거죠

 

 

그다음 봇아버지에게 /newBot이라고 말은 걸면 아버지가 물어볼꺼에요 봇이름은 무엇으로 할거니?

 

라고..

 

거기에 Bot 이름을 입력해주시면 되는데

 

이름_Bot 이름 뒤에 꼭 _Bot이라고 붙여 주셔야 합니다

 

그렇게 Bot이 생성이 되면 HTTP API 라는 키를 알려줍니다

 

여기까지 되셧으면 사전 준비는 완료

 

다음은 비쥬얼 스튜디오로 가서 프로젝트를 하나 생성해 줍니다

 

그 다음 Nuget을 통해 TelegramBot을 참조 추가 해줍니다

 

 

저는 이미 설치가 되어 있으서 업데이트라고 나오는데

 

여러분은 아마 설치라고 나오실겁니다

 

 

설치하게 되면 Telegram.Bot이라는 참조가 생성이 됩니다

 

그다음 텔레그램을 제어하기 위한 Class를 생성할겁니다

 

저는 src라는 폴더 아래 TelegramBot.cs라는 파일을 생성했습니다

 

[SourceCode]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Cache;
using System.IO;

 

프로젝트 using 선언문을 선언해주고

 

    public class TelegramBot
    {
        private static readonly string _baseUrl = "https://api.telegram.org/bot";
        private static readonly string _token = "879350682:AAEgVohD-XAq6g_Fq4vEHecuiiqLCnZ6CEU";
        public static string _chatId = string.Empty;

        /// <summary>
        /// 텔레그램봇에게 메시지를 보냅니다.
        /// </summary>
        /// <param name="text">보낼 메시지</param>
        /// <param name="errorMessage">오류 메시지</param>
        /// <returns>결과</returns>
        public static bool SendMessage(string text, out string errorMessage)
        {
            return SendMessage(_chatId, text, out errorMessage);
        }

        /// <summary>
        /// 텔레그램봇에게 메시지를 보냅니다.
        /// </summary>
        /// <param name="chatId">chat id</param>
        /// <param name="text">보낼 메시지</param>
        /// <param name="errorMessage">오류 메시지</param>
        /// <returns>결과</returns>
        public static bool SendMessage(string chatId, string text, out string errorMessage)
        {
            string url = string.Format("{0}{1}/sendMessage", _baseUrl, _token);

            HttpWebRequest req = WebRequest.Create(new Uri(url)) as HttpWebRequest;
            req.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
            req.Timeout = 30 * 1000;
            req.Method = "POST";
            req.ContentType = "application/json";

            string json = String.Format("{{\"chat_id\":\"{0}\", \"text\":\"{1}\"}}", chatId, EncodeJsonChars(text));
            byte[] data = UTF8Encoding.UTF8.GetBytes(json);
            req.ContentLength = data.Length;
            using (Stream stream = req.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
                stream.Flush();
            }

            HttpWebResponse httpResponse = null;
            try
            {
                httpResponse = req.GetResponse() as HttpWebResponse;
                if (httpResponse.StatusCode == HttpStatusCode.OK)
                {
                    string responseData = null;
                    using (Stream responseStream = httpResponse.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(responseStream, UTF8Encoding.UTF8))
                        {
                            responseData = reader.ReadToEnd();
                        }
                    }

                    if (0 < responseData.IndexOf("\"ok\":true"))
                    {
                        errorMessage = String.Empty;
                        return true;
                    }
                    else
                    {
                        errorMessage = String.Format("결과 json 파싱 오류 ({0})", responseData);
                        return false;
                    }
                }
                else
                {
                    errorMessage = String.Format("Http status: {0}", httpResponse.StatusCode);
                    return false;
                }
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
                return false;
            }
            finally
            {
                if (httpResponse != null)
                    httpResponse.Close();
            }
        }

        private static string EncodeJsonChars(string text)
        {
            return text.Replace("\b", "\\\b")
                .Replace("\f", "\\\f")
                .Replace("\n", "\\\n")
                .Replace("\r", "\\\r")
                .Replace("\t", "\\\t")
                .Replace("\"", "\\\"")
                .Replace("\\", "\\\\");
        }
    }

이렇게 Class 파일을 하나생성해 줍니다

 

그 다음 메인폼으로 이동한뒤에

 

using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.ReplyMarkups;

 

Telegram.Bot을 화면에 삽입 시켜 줍니다

 

private void Telegram_Send()
        {
            string text = Messge;
            string errorMessage = null;
            bool ret = TelegramBot.SendMessage(text, out errorMessage);


            switch (TelegramBot._chatId)
            {
                case "chatId1":
                    Who = "사용자1";
                    break;
                case "chatId2":
                    Who = "사용자2";
                    break;
                case "chatId3":
                    Who = "사용자3";
                    break;
                case "chatId4":
                    Who = "사용자4";
                    break;
                case "chatId5":
                    Who = "사용자5";
                    break;
            }

            //Log 기록.
            TelegramBot._chatId = "chatId_Bot";
            text = "[" + Who + "] 전송시간 : " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            bool ret2 = TelegramBot.SendMessage(text, out errorMessage);

        }

 

이렇게 하면 전송하게 됩니다

 

여기서 chatId라는게 나오는데요

 

상대방의 고유 계정 ID라고 보시면 될거 같은데요 나의 ID를 보는 방법은 다음과 같습니다

 

친구 검색하기에서 "get id"라고 검색을 하면 아래 그림과 같은 Bot이 나오는데 추가해줍니다

 

 

추가하게 되면 친구 리스트에 다음과 같이 나오게 되겟죠?

 

대화창으로 이동한뒤 /start라고 쳐주면 

 

Your Chat ID = "xxxxxxxxx"라고 알려줍니다

 

저 코드가 chatId가 되는겁니다

 

그리고 단체그룹방에 메세지를 보고 싶을 경우에는

 

해당 그룹방에 나의 Bot을 추가한뒤에 

 

인터넷 주소창에

 

https://api.telegram.org/bot"API 토큰값"/getUpdates

 

이렇게 입력을 하게 되면

 

빨간색 테두리안에 해당 대화방의 Chatid가 나오게 됩니다

 

반응형