LoginSignup
0
0

More than 1 year has passed since last update.

Telegram Botを使う

Last updated at Posted at 2022-05-12

Hello World

 前提条件 Telegramがインストールされていること

アクセストークンを取得する

TelegramのBotFatherにアクセスする

https://t.me/botfather

このような画面が出ます。

Screenshot from 2022-05-12 20-29-38.png

startと入力します。

/start
Screenshot from 2022-05-12 20-25-21.png

/newbotと入力し、ボットの名前を決めます。

/newbot

ボットの名前を決めます。名前の後に_bot or Botと必ず記入します。

ボットの名前に被りがなければこのような画面でてアクセストークンアクセスURLを取得できます。

Screenshot from 2022-05-12 20-25-59.png

https://t.me/決めたボットの名前_bot

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

サンプルはここにあります

実行するとリスニング状態になります。

https://t.me/決めたボットの名前_bot

リンクをクリックして入ります。

Screenshot from 2022-05-13 01-22-45.png
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;
        }
    }
}

Stellear SDKを使ってみるに続く

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0