728x90
아래와 같이 ID를 받아오면 됩니다.
class TelegramBot
{
private static readonly string _token = "받아온 토큰";
private const string CHAT_HEAD = "\"chat\":{\"id\":";
private const string CHAT_IDS_FORM = "https://api.telegram.org/bot{0}/getUpdates";
public static List<long> GetChattingRoomIDs(out string error)
{
error = "";
string url = string.Format(CHAT_IDS_FORM, _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";
Dictionary<long, long> ids = new Dictionary<long, long>();
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 (string.IsNullOrEmpty(responseData))
return ids.Keys.ToList();
int start = 0;
int index = 100000;
while (index != -1)
{
index = responseData.IndexOf(CHAT_HEAD, start);
if (index == -1) break;
start = responseData.IndexOf(",", index + CHAT_HEAD.Length);
if (start == -1) break;
string value = responseData.Substring(index + CHAT_HEAD.Length, start - (index + CHAT_HEAD.Length));
long id = 0;
if (long.TryParse(value, out id))
{
if (!ids.ContainsKey(id))
ids.Add(id, id);
}
}
}
}
}
else
{
error = string.Format("Http status : {0}", httpResponse.StatusCode);
return ids.Keys.ToList();
}
}
catch (Exception ex)
{
error = ex.Message;
return ids.Keys.ToList();
}
finally
{
if (httpResponse != null) httpResponse.Close();
}
return ids.Keys.ToList();
}
}
사용 코드는
string error = "";
List<long> ids = TelegramBot.GetChattingRoomIDs(out error);
ps : 혹시 ID를 얻어 오지 못한다면 인터넷 창에 "https://api.telegram.org/bot[봇엑세스토큰]/getUpdates" 을 넣어 보면 Json 값이 나오는데 그 Json값이 비어 나온다면
현재 봇이 참가 하고 있는 채팅 방이 있는지 확인 하시고 있는데도 비어 있다면 그 방에 봇을 내보냈다가 다시 참가 시키면 됩니다.
'Programming > Telegram Bot' 카테고리의 다른 글
TelegramBot으로 주식 분석 프로그램으로 추천 된 종목 공유하기 (0) | 2021.02.16 |
---|
댓글