티스토리 뷰

프로그래밍/C#

텔레그램 메시지 보내기

에어버스 2017. 11. 5. 15:52

텔레그램 봇을 사용해서 메시지를 보낼 수 있다길래...

닷넷과 함께 메시지를 보내보기 위해서 만들어보았다.


일단은 메시지만...



텔레그램 봇 만들기와, 봇의 토큰 알아내기, 그리고 나와의 채팅방에서 챗아이디 가져오는 방법은 

다른 블로그를 통해 알아보자 ~



C#=====================================

//텔레그램 메시지 클래스

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;

    }

 

}


========================

 

C++ 관련 코드들

 

TCHAR szServerName[] = _T("www.xxxxx.co.kr"); //http:// 를 빼고 넣어야 합니다.
TCHAR szFormAction[] = _T("Member.aspx");
TCHAR szHeader[500] = _T("Content-Type: application/x-www-form-urlencoded\r\n");
char szPostData[200]=("PhoneNumber=01012345678&ID=happy2012"); //유니코드 문자열이 아닙니다.
LPCWSTR accept[2]={_T("*/*"), NULL};
char szPDAPhoneNumber[50];
char szDeviceName[50];

DWORD_PTR dwContext=1;
LPTSTR m_html = NULL ;
BOOL bResult;
DWORD dwSize;

HINTERNET hInternet = InternetOpen( _T("HTTP-POST"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 );

HINTERNET hConnect = InternetConnect( hInternet, szServerName, INTERNET_DEFAULT_HTTP_PORT, NULL, _T("HTTP/1.1"), INTERNET_SERVICE_HTTP, 0, dwContext);

HINTERNET hRequest = HttpOpenRequest( hConnect, _T("POST"), szFormAction, _T("HTTP/1.1"), NULL, accept,INTERNET_FLAG_DONT_CACHE, dwContext);

WideCharToMultiByte(CP_ACP, 0, g_szPDAPhoneNumber, -1, szPDAPhoneNumber, 50, NULL, NULL);
WideCharToMultiByte(CP_ACP, 0, g_szDeviceName, -1, szDeviceName, 50, NULL, NULL);

sprintf(szPostData, "SmartPhoneNumber=%s&DeviceName=%s", szPDAPhoneNumber, szDeviceName);
//Header를 두개 이상 사용할 경우 ---
bResult = HttpAddRequestHeaders(hRequest, szHeader, _tcslen(szHeader), HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
//PostData
bResult = HttpSendRequest( hRequest, NULL, 0, (LPVOID) szPostData, strlen(szPostData));

BOOL bQuery = InternetQueryDataAvailable( hRequest, &dwSize, 0, 0 );
if ( bQuery && dwSize > 0 )
{
DWORD dwTotal = 0;
char* pData = (char*)malloc( dwTotal + dwSize + 1 );
while ( pData && dwSize )
{
DWORD dwRead = 0;
InternetReadFile( hRequest, pData+dwTotal, dwSize, &dwRead );
dwTotal += dwRead;
pData[dwTotal] = NULL;

InternetQueryDataAvailable( hRequest, &dwSize, 0, 0 );
if ( dwSize > 0 )
{
pData = (char*)realloc( pData, dwTotal + dwSize+1 );
}
}
if ( pData )
{
int len = MultiByteToWideChar( CP_UTF8, 0, pData, dwTotal, NULL, NULL );
m_html = (LPWSTR)calloc( len+1, sizeof(WCHAR) );
if ( m_html )
{
MultiByteToWideChar( CP_UTF8, 0, pData, dwTotal, m_html, len+1 );
}
free(pData);
}
}

InternetCloseHandle( hRequest );
InternetCloseHandle( hConnect );
InternetCloseHandle( hInternet );

return TRUE;
}
return (FALSE);
}

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30