今天繼續 Telegram.Bot v19 ,應該是最後一篇了,畢竟其他功能也不是常用到
這範例主要是,對於在群組中舉辦一場投票,然後可以收集票數,也可以知道誰投了那些答案
這主要是用在群組中會比較有用,當然你也可以一個一個去發不過只是搞死你自己而已..

今天主要案例是一個群組,裡面有三個人,有人說出 /vote 後,會啟動機器人發出一個投票,投票會在兩分鐘後結束
並且我們會在程式碼中得到每一次的投票結果,跟誰投了什麼票
1.你得先跟 BotFather 建立一個機器人,並且跟拿到 TOKEN ,可以參考這裡 https://sendpulse.com/knowledge-base/chatbot/telegram/create-telegram-chatbot
我就不贅述了,我之所以不得不升級就上去就是因為你建新的機器人,拿到的 token ,在 Telegram.Bot SDK v15 版本裡面會被報錯誤,非正確格式的 token
2. Nuget Library : https://www.nuget.org/packages/Telegram.Bot 目前版本為 19.0.0
3.初始化 TelegramBotClient
,因為想收到所有事件,跟之前案例不同以防萬一我就改
receiverOptions 加入 UpdateType 的全部 Type
public static void InitTelegramBotClient()
{
_TelegramBotClient = new TelegramBotClient("1234567:4TT8bAc8GHUspu3ERYn-KGcvsvGB9u_n4ddy");
ReceiverOptions receiverOptions = new()
{
AllowedUpdates = Array.Empty()
};
//我要攔截所有的事件
receiverOptions.AllowedUpdates = Enum.GetValues(typeof(UpdateType)).Cast().ToArray();
_TelegramBotClient.StartReceiving(
updateHandler: HandleUpdateVoteAsync,
pollingErrorHandler: (botClient, exception, cancellationToken) =>
{
return Task.CompletedTask;
}, receiverOptions: receiverOptions);
}
4.就是寫關於接收的事件,這邊我就寫在註解裡面了
主要可以使用 update.Type 去判斷這回應事件的類型


程式碼:
static async Task HandleUpdateVoteAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
{
//這是回報誰選的什麼答案這是第三個觸發的
if (update.Type == UpdateType.PollAnswer)
{
Console.WriteLine("收到投票-" + update.PollAnswer.PollId + ","+update.PollAnswer.User.FirstName+"回答:" + update.PollAnswer.OptionIds[0].ToString());
}
//這是回報有人投票,但是沒有誰投票的資訊,但是可以知道投票的分布
else if (update.Type == UpdateType.Poll)
{
Console.WriteLine("收到投票-" + update.Poll.Id + ",總收到多少票數:" + update.Poll.Options.Sum(x => x.VoterCount));
}
//取得一般訊息指令
else if (update.Message != null)
{
Console.WriteLine("收到訊息:" + update.Message.Text);
if (update.Message.Chat.Type == ChatType.Group)
{
if (update.Message.Text == "/vote")
{
Message pollMessage = await botClient.SendPollAsync(
chatId: update.Message.Chat.Id,
question: "今天中午要吃啥?",
//這邊不許匿名
isAnonymous: false,
closeDate: DateTime.Now.AddMinutes(2),
options: new[]
{
"0.排骨飯",
"1.蚵仔麵線",
"2.草餐店",
"3.小七",
"4.四爺"
},
cancellationToken: cancellationToken);
//這個Id 為該次投票的 Id
Console.WriteLine("Poll Id :" + pollMessage.Poll.Id);
}
}
}
return;
}
結果:
大概就先筆記到這裡吧,常用的功能都記錄 下來了,其他的應該就算是特殊應用了
reference:
https://telegrambots.github.io/book/2/send-msg/native-polls-msg.html?highlight=SendPollAsync#stop-a-poll