MS

C# 텔레그램 메시지 보내기(No 라이브러리)

콩메모 2024. 1. 4. 13:31

Nuget에 있는 Telegram.Bot 은 닷넷 4.6 이상 지원이 된다.

그래서, 닷넷4 에서는 사용할수 없다.

그래서 좀 불편하지만, 텔레그램 URL을 직접 호출해주는 식으로 구현을 한 소스를 남겨둔다.

필요하신분 테스트해보시길..

using System.Web; // HttpUtility
using System.Net; // WebClient

string apikey_발신로봇 = "~~~~"; // 발신로봇의 api-key
string chatid_수신자 = "~~~~"; // 수신자의 chat-id

string message = HttpUtility.UrlEncode(msg.Replace("\r\n", "\n").Replace("\\n", "\n"));
string url = $"https://api.telegram.org/bot{apikey_발신로봇}/sendMessage?chat_id={chatid_수신자}&text={message}&parse_mode=HTML";


ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072;
WebClient weblient = new WebClient();

string result = webclient.DownloadString(url);

 

참고로,

ServicePointManager.SecurityProtocol = (SecurityProtocolType)768 | (SecurityProtocolType)3072;

 

위 코드는 프로그램 초기에 선언해줘도 되고, 위와 같이 매번 해줘도 되는거 같다. ( 함수로 만들 때 알아서 관리하기 편한대로 하면 될듯 하다. )

저 코드가 없으면 "요청이 중단되었습니다. SSL/TLS 보안 채널을 만들 수 없습니다." 오류가 발생할 수가 있다.