본문 바로가기
개발언어/C#

텔레그램 봇 생성 및 C#을 이용한 간단한 챗봇 로직 작성하기

by 후쮸아빠 2023. 7. 6.

안녕하세요, 여러분! 오늘은 텔레그램 봇을 만들고, 간단한 C# 챗봇 로직을 작성하는 방법에 대해 알아보려고 합니다. 텔레그램 봇은 API를 통해 메시지를 보내거나 받는 등 다양한 기능을 구현할 수 있습니다. 그럼 바로 시작해보죠!

 


텔레그램 봇 생성 및 Chat ID 확인하기

 

텔레그램 봇 생성

1. 텔레그램에서 @BotFather를 검색해 대화창을 엽니다.

2."/newbot" 명령어를 보내면 봇 생성을 시작하게 됩니다.

3. 봇의 이름과 사용자 이름을 입력하면, 봇이 생성됩니다. 여기서 봇의 사용자 이름은 반드시 'bot'으로 끝나야 합니다.

4. 이제 봇 토큰을 받게 됩니다. 이 토큰은 나중에 봇을 제어하는 데 사용되므로 안전하게 보관하세요.

 

사용자 Chat ID 확인하기

메시지를 보낼 대상인 Chat ID를 확인하는 방법은 다음과 같습니다.

 

1. 텔레그램에서 @userinfobot를 검색하고 대화를 시작하세요.


2. '/start' 명령을 보내면, 봇이 응답합니다. 그 후 임의의 메시지를 보내세요.


3. 봇이 당신의 정보를 보내줍니다. 이 정보에 포함된 'Id'가 바로 Chat ID입니다.

 

C#을 이용한 텔레그램 봇 로직 작성하기

Telegram.Bot 라이브러리의 19버전부터는 Update Handlers를 사용하는 방식으로 변경되었습니다. 

아래는 MessageHandler를 사용하여 메시지를 처리하는 간단한 예제입니다.

 

사전에 Nuget 패키지 관리에서 Telegram.Bot를 설치합니다. 

using System;
using System.Threading;
using Telegram.Bot;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Extensions.Polling;
using Telegram.Bot.Types;

class Program
{
    static TelegramBotClient botClient;

    public static async void Main(string[] args)
    {
        botClient = new TelegramBotClient("YOUR_BOT_TOKEN");

        var cts = new CancellationTokenSource();

        // StartReceiving does not block the caller thread. Receiving is done on the ThreadPool.
        botClient.StartReceiving(
            new DefaultUpdateHandler(HandleUpdateAsync, HandleErrorAsync),
            cts.Token
        );

        Console.WriteLine("Press any key to shutdown this bot");
        Console.ReadKey();

        // Send cancellation request to stop bot
        cts.Cancel();
    }

    public static async Task HandleUpdateAsync(ITelegramBotClient botClient, Updateupdate, CancellationToken cancellationToken)
    {
        // Only handle Message types
        if (update.Type != UpdateType.Message)
            return;

        var message = update.Message;

        if (message.Type == MessageType.Text)
        {
            await botClient.SendTextMessageAsync(
                chatId: message.Chat.Id,
                text: $"You said:\n{message.Text}"
            );
        }
    }

    public static async Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
    {
        if (exception is ApiRequestException apiRequestException)
        {
            await Console.Out.WriteLineAsync($"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}");
        }
        else
        {
            await Console.Out.WriteLineAsync(exception.ToString());
        }
    }
}

위 코드에서 YOUR_BOT_TOKEN을 봇 토큰으로 바꿔주시면 됩니다. 이 코드를 실행하고 텔레그램에서 봇에 메시지를 보내보면, 봇이 당신의 메시지를 그대로 답장하는 것을 확인할 수 있습니다.

 



이렇게 하면 간단한 텔레그램 봇이 완성되었습니다. 여러분의 창의력을 발휘해서 더 다양하고 재미있는 기능을 봇에 추가해보세요!

 

이상으로 텔레그램 봇 생성 및 간단한 C# 챗봇 로직 작성에 대해 알아봤습니다. 텔레그램 봇은 이 외에도 많은 기능을 제공하므로, 자유롭게 활용해 보세요.