Created
April 15, 2024 17:00
-
-
Save HeySreelal/3a160fa0f9b5dfc1db241640036dc99f to your computer and use it in GitHub Desktop.
Solution for this StackOverflow Question: https://stackoverflow.com/q/78325403/10006183
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:io'; | |
import 'package:televerse/televerse.dart'; | |
// Bot instance | |
final bot = Bot( | |
Platform.environment["BOT_TOKEN"]!, | |
); | |
// - Variables - // | |
// The group/chat id | |
ChatID? id; | |
// Message ID of the poll (will be set once sent) | |
int? msgId; | |
// Poll Id of the poll (not really necessary) | |
String? pollId; | |
void main(List<String> args) { | |
// Starts bot with Long Polling. | |
bot.start(); | |
// /start command handler - simply sends a poll to the group/chat where /start command is recieved | |
bot.command('start', (ctx) async { | |
await ctx.reply("Here's a poll."); | |
final msg = await ctx.replyWithPoll( | |
"Are you ready for a trip next month?", | |
["YESSSS", "Nah"], | |
); | |
// Sets the variables | |
id = msg.chat.getId(); | |
msgId = msg.messageId; | |
pollId = msg.poll?.id; | |
}); | |
// Handles the /stop command - stops the poll with `chat_id` and `message_id`. | |
bot.command('stop', (ctx) async { | |
// validation | |
if (id == null || msgId == null) { | |
await ctx.reply("Hmm, no way."); | |
return; | |
} | |
// stopPoll API call | |
await ctx.api.stopPoll(id!, msgId!); | |
}); | |
// Listens to `poll` updates. | |
bot.poll((ctx) async { | |
// Recieved poll update | |
final poll = ctx.poll!; | |
// If poll is not closed we don't have to handle anything. | |
if (!poll.isClosed) return; | |
// Poll is closed, ie, this is the final Poll update related to this particular poll. | |
await ctx.api.sendMessage( | |
id!, | |
"There we go. We finally have a poll result.", | |
); | |
// Just sorting the poll options based on the voter count. (Not necessary) | |
poll.options.sort(((a, b) => b.voterCount.compareTo(a.voterCount))); | |
// ... | |
// Most voted option. | |
final bestOption = poll.options.first; | |
await ctx.api.sendMessage( | |
id!, | |
"The best option was ${bestOption.text} with ${(bestOption.voterCount / poll.totalVoterCount) * 100}% votes.", | |
); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment