Hello World
前提条件 Telegramがインストールされていること
アクセストークンを取得する
TelegramのBotFatherにアクセスする
このような画面が出ます。

startと入力します。
/start

/newbotと入力し、ボットの名前を決めます。
/newbot
ボットの名前を決めます。名前の後に_bot or Botと必ず記入します。
ボットの名前に被りがなければこのような画面でてアクセストークンとアクセスURLを取得できます。

C# コンソール側
NugetからTelegram.Botパッケージをインストール
dotnet add package Telegram.Bot
アクセストークンを記入し、結果が正しく返ってきたら初期セットアップは完了です。
using System;
using System.Diagnostics;
using Telegram.Bot;
namespace TelegramApp
{
class Program
{
static async Task Main(string[] args)
{
var botClient = new TelegramBotClient("アクセストークン");
var me = await botClient.GetMeAsync();
Console.WriteLine($"Hello, World! I am user {me.Id} and my name is {me.FirstName}.");
}
}
}
Sampleを試してみる
Telegram.Bot.Extensions.PollingをNugetで追加
dotnet add package Telegram.Bot.Extensions.Polling
サンプルはここにあります
実行するとリスニング状態になります。
リンクをクリックして入ります。

using System;
using System.Diagnostics;
using Telegram.Bot;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Extensions.Polling;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
namespace TelegramApp
{
class Program
{
static async Task Main(string[] args)
{
var botClient = new TelegramBotClient("アクセストークン");
using var cts = new CancellationTokenSource();
// StartReceiving does not block the caller thread. Receiving is done on the ThreadPool.
var receiverOptions = new ReceiverOptions
{
AllowedUpdates = Array.Empty<UpdateType>() // receive all update types
};
botClient.StartReceiving(updateHandler: HandleUpdateAsync,
errorHandler: HandlePollingErrorAsync,
receiverOptions: new ReceiverOptions()
{
AllowedUpdates = Array.Empty<UpdateType>()
},
cancellationToken: cts.Token);
var me = await botClient.GetMeAsync();
Console.WriteLine($"Start listening for @{me.Username}");
Console.ReadLine();
// Send cancellation request to stop bot
cts.Cancel();
}
static async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
{
// Only process Message updates: https://core.telegram.org/bots/api#message
if (update.Type != UpdateType.Message)
return;
// Only process text messages
if (update.Message!.Type != MessageType.Text)
return;
var chatId = update.Message.Chat.Id;
var messageText = update.Message.Text;
Console.WriteLine($"Received a '{messageText}' message in chat {chatId}.");
// Echo received message text
Message sentMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "You said:\n" + messageText,
cancellationToken: cancellationToken);
}
static Task HandlePollingErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
{
var ErrorMessage = exception switch
{
ApiRequestException apiRequestException
=> $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}",
_ => exception.ToString()
};
Console.WriteLine(ErrorMessage);
return Task.CompletedTask;
}
}
}