1 module pollbot.pollbot; 2 3 import std.typecons : Nullable; 4 import vibe.core.log : setLogLevel, logInfo, LogLevel; 5 import telega.telegram.basic : Message, Update, sendMessage; 6 import telega.telegram.poll : Poll, SendPollMethod, StopPollMethod, sendPoll, stopPoll, PollType; 7 import telega.botapi : BotApi; 8 9 class PollBot 10 { 11 private Nullable!Message currentPoll; 12 private BotApi api; 13 14 public this(BotApi api) 15 { 16 this.api = api; 17 } 18 19 public void onUpdate(ref Update u) 20 { 21 // we need all updates with text message 22 if (!u.message.isNull && !u.message.get.text.isNull) 23 { 24 this.onText(u.message.get); 25 } 26 27 if (!u.poll_answer.isNull) { 28 logInfo("Poll answer %s", u.poll_answer); 29 } 30 if (!u.poll.isNull) { 31 logInfo("Poll changed"); 32 } 33 } 34 35 private void onText(ref Message m) 36 { 37 import std.format : format; 38 39 if (m.text == "/poll") { 40 logInfo("Starting poll in %s", m.chat.id); 41 42 SendPollMethod sendPoll = { 43 chat_id: m.chat.id, 44 question: "Send /result to stop this poll", 45 is_anonymous: false, 46 type: PollType.Quiz, 47 correct_option_id: 1, 48 allows_multiple_answers: true, 49 options: [ 50 "option 1", 51 "option 2", 52 "option 3", 53 ] 54 }; 55 Message message = api.sendPoll(sendPoll); 56 currentPoll = message; 57 58 logInfo("Started poll %s", message.poll.get.id); 59 } 60 61 if (m.text == "/result") { 62 if (currentPoll.isNull) { 63 api.sendMessage(m.chat.id, "No poll was started, send /poll to start a new poll."); 64 65 return; 66 } 67 68 Poll pollResult = api.stopPoll(currentPoll.get.chat.id, currentPoll.get.id); 69 api.sendMessage( 70 currentPoll.get.chat.id, 71 "Poll results:\n Total votes: %d" 72 .format( 73 pollResult.total_voter_count 74 ) 75 ); 76 currentPoll = Nullable!Message.init; 77 logInfo("Poll %s stopped", pollResult.id); 78 } 79 } 80 }