티스토리 뷰
텔레그램 봇 자신에게 메시지 보내기
봇 ChatId 확인 방법 : http://petra.tistory.com/1122
참고> 콘솔 프로그램으로 만든 경우, 59행과 같이 Bot.SendTextMessageAsync()로 메시지를 보내고 프로그램을 종료하면 텔레그램에서 메시지를 못 받을 수 있으니 Consol.ReadLine() 호출해서 프로그램이 종료되지 않게 해야 텔레그램에서 메시지를 받게 된다.
1. C# 윈도우 폼 프로젝트 만들고, 프로젝트에 마우스 버튼 올린 상태에서 마우스 우측 버튼 눌러 NuGet 패키지관리 클릭한다.
2. 아래 그림처럼 찾아보기에서 'telegram' 으로 검색하면 'Telegram.Bot' 이 목록에 나오면 우측의 '설치' 버튼을 눌러 설치한다.
만약, 위 그림처럼 Telegram.Bot 목록이 안나오면 아래 그림에서 우측 위 노란색 부분처럼 '모두' 선택하고 옵션(톱니바퀴 모양) 클릭하면 옵션 창이 나오면 파란색 부분처럼 NuGet.org 가 체크되어 있는지 확인한다.
3. 아래 코드처럼 Telegram.Bot; 를 지정할 수 있다.
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.ReplyMarkups;
namespace TestTelegram
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
setTelegramEvent();
}
private Telegram.Bot.TelegramBotClient Bot = new Telegram.Bot.TelegramBotClient("4****3:AA*****J0");
private void Form1_Load(object sender, EventArgs e)
{
telegramAPIAsync();
}
private async void telegramAPIAsync()
{
var me = await Bot.GetMeAsync();
Console.WriteLine("내 이름은 {0}", me.FirstName);
}
private void setTelegramEvent()
{
Bot.OnMessage += Bot_OnMessage;
Bot.StartReceiving();
}
private async void Bot_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e)
{
var msg = e.Message;
if (msg == null || msg.Type != MessageType.TextMessage)
return;
await Bot.SendTextMessageAsync(msg.Chat.Id, msg.Text);
Console.WriteLine("받은 메시지 : {0}", msg.Text);
}
private void button1_Click(object sender, EventArgs e)
{
Bot.SendTextMessageAsync("4******1", "봤니?");
}
}
} |
cs |
4. 이탤릭체로 된 코드를 직접 입력해야 한다.
28행의 노란색 문자열은 봇 생성하고 받은 토큰 값을 입력하면 된다.
5. 폼에 버튼(button1) 추가하고 더블 클릭한 다음 59행의 코드를 입력한다. (받을 ChatId, 보낼 메시지)
6. 실행해서 버튼을 누르면 메시지가 전송된다.
참고>
me.Id 변수가 있으나 50행의 봇 ID 와는 다르다.