Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added 'MessageContext.args' #115

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion example/basic_bot.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ void main(List<String> args) {
final String token = Platform.environment["BOT_TOKEN"]!;

/// Create a bot instance
Bot bot = Bot(token);
final Bot bot = Bot(token);

/// Adds the /start command listener and starts the bot
bot.command("start", (ctx) {
Expand Down
5 changes: 3 additions & 2 deletions example/helpers_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ MessageHandler handler(String text) {
}

void main() async {
bot.onAudio(handler("audo"));
bot.onAudio(handler("audio"));
bot.onDocument(handler("document"));
bot.onPhoto(handler("photo"));
bot.onSticker(handler("sticker"));
Expand All @@ -34,7 +34,8 @@ void main() async {
bot.whenVideoChatStarted(handler("video chat started"));
bot.whenVideoChatEnded(handler("video chat ended"));
bot.whenVideoChatParticipantsInvited(
handler("video chat participants invited"));
handler("video chat participants invited"),
);
bot.onForumTopicCreated(handler("forum topic created"));
bot.onForumTopicEdited(handler("forum topic edited"));
bot.onForumTopicClosed(handler("forum topic closed"));
Expand Down
2 changes: 1 addition & 1 deletion example/local_bot.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ void main(List<String> args) {
final token = Platform.environment['BOT_TOKEN']!;

/// Use the [Bot.local] constructor to create a bot instance.
Bot bot = Bot.local(token);
final bot = Bot.local(token);

/// Start polling and setup the handler for the `/start` command.
bot.start((ctx) {
Expand Down
2 changes: 1 addition & 1 deletion example/markup_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ void main(List<String> args) {
final String token = Platform.environment["BOT_TOKEN"]!;

/// Create a bot instance
Bot bot = Bot(token);
final bot = Bot(token);

/// Adds the /test command listener
bot.command("test", (ctx) {
Expand Down
2 changes: 1 addition & 1 deletion example/televerse_example.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ void main() async {
final String token = Platform.environment["BOT_TOKEN"]!;

/// Create a new bot instance
Bot bot = Bot(token, fetcher: LongPolling());
final bot = Bot(token, fetcher: LongPolling());

/// Listen to commands
bot.command("hello", (ctx) => ctx.reply("Hello!"));
Expand Down
12 changes: 6 additions & 6 deletions example/test_bot.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import 'package:televerse/televerse.dart';
/// This is a general bot that tests different features of the library.
void main() async {
/// Creates the bot instance
final Bot bot = Bot(
final bot = Bot(
Platform.environment["BOT_TOKEN"]!,
fetcher: LongPolling.allUpdates(),
);
Expand All @@ -16,12 +16,12 @@ void main() async {

// Custom emoji
// This will only work if the bots that purchased additional usernames on Fragment
CustomEmoji emoji = CustomEmoji("👍", 5368324170671202286);
final emoji = CustomEmoji("👍", 5368324170671202286);

ctx.reply("Hello $mention! $emoji", parseMode: ParseMode.html);

ShareLink link = ShareLink("https://google.com", text: "Google");
GroupBotLink groupLink = GroupBotLink("xclairebot");
final link = ShareLink("https://google.com", text: "Google");
final groupLink = GroupBotLink("xclairebot");

final keyboard = InlineKeyboard()
.row()
Expand Down Expand Up @@ -89,7 +89,7 @@ void main() async {
});

bot.pollAnswer((ctx) {
PollAnswer pollAnswer = ctx.pollAnswer;
final pollAnswer = ctx.pollAnswer;
ctx.reply('Poll Answered: ${pollAnswer.optionIds}');
});

Expand All @@ -102,7 +102,7 @@ void main() async {
});

bot.command('testing', (ctx) async {
ctx.reply('Testing...');
await ctx.reply('Testing...');

await Future.delayed(Duration(seconds: 5));

Expand Down
16 changes: 10 additions & 6 deletions lib/src/televerse/context/message.dart
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,6 @@ class MessageContext extends Context with MessageMixin, ManagementMixin {
/// This will be automatically set when you use the [Televerse.hears] method.
List<RegExpMatch>? matches;

/// Start Parameter - Used for deep linking.
/// This will be set when your bot is started with a deep link.
/// Example: `https://t.me/MyBot?start=12345` will set `startParameter` to `12345`.
/// This will be `null` if the bot is not started with a deep link.
String? startParameter;

/// **Chat ID**
///
/// This is a shortcut for `ChatID(message.chat.id)`. So you can simply use `ctx.id` instead of repeating `ChatID(message.chat.id)`.
Expand All @@ -53,4 +47,14 @@ class MessageContext extends Context with MessageMixin, ManagementMixin {
/// User who sent the message.
/// This will be `null` if the message is sent if the message is sent on a channel or an anonymous admin.
User? get from => message.from;

/// If the message is a command, the list will be filled with the command arguments.
/// e.g. /hello @mom @dad will have a ctx.args like this: ['@mom', '@dad'].
/// This will be empty if the message is not a command or if the message doesn't contain text
/// NOTE: This is obviously also used for the deeplink start parameters.
List<String> get args {
if (!(message.text?.startsWith('/') ?? false)) return [];

return message.text!.split(' ').sublist(1);
}
}
11 changes: 0 additions & 11 deletions lib/src/televerse/televerse.dart
Original file line number Diff line number Diff line change
Expand Up @@ -177,17 +177,6 @@ class Televerse<TeleverseSession extends Session> {
for (HandlerScope scope in sub) {
Context context = scope.context(this, update);
if (scope.special) {
if (scope.isCommand) {
context as MessageContext;
String? text = context.message.text;
if (text != null) {
List<String> split = text.split(' ');
bool hasParam = split.length > 1;
if (hasParam && split.first == '/start') {
context.startParameter = split.sublist(1).join(' ');
}
}
}
if (scope.isRegExp) {
context as MessageContext;
String? text = context.message.text;
Expand Down
56 changes: 34 additions & 22 deletions test/televerse_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,24 @@ import 'package:televerse/telegram.dart';
import 'package:televerse/televerse.dart';
import 'package:test/test.dart';

// This will avoid github's builder to throw errors caused by env vars.
String environ(String key) {
final value = Platform.environment[key] ?? '';

if (value.isEmpty) {
log("Wasn't able to get '$key' from the environment values.");
io.exit(0);
}

return value;
}

void main() {
Bot bot = Bot(Platform.environment['BOT_TOKEN']!);
int chatId = int.parse(Platform.environment['CHAT_ID']!);
int gID = int.parse(Platform.environment['CHANNEL_ID']!);
ChatID id = ChatID(chatId);
ChatID groupID = ChatID(gID);
final bot = Bot(environ('BOT_TOKEN'));
final chatId = int.parse(environ('CHAT_ID'));
final gID = int.parse(environ('CHANNEL_ID'));

final id = ChatID(chatId), groupID = ChatID(gID);

String stickerFileID =
"CAACAgUAAxkBAAELxJhjw5m8ZywifRtXVhjG9HkygYQ-7gAC6AcAAqY4CVS1s3ikdwGZby0E";
Expand All @@ -24,10 +36,10 @@ void main() {
});

test("Send Message", () async {
Message message = await bot.api.sendMessage(id, "Hello World");
final message = await bot.api.sendMessage(id, "Hello World");
expect(message.text, "Hello World");

Message specialMessage = await bot.api.sendMessage(
final specialMessage = await bot.api.sendMessage(
id,
"<b>Hello World</b>\n\nYou can use <a href=\"https://core.telegram.org/bots/api\">Telegram Bot API</a> here.",
parseMode: ParseMode.html,
Expand All @@ -49,7 +61,7 @@ void main() {
});

test("Send Photo", () async {
Message message = await bot.api.sendPhoto(
final message = await bot.api.sendPhoto(
id,
InputFile.fromUrl("https://i.imgur.com/CUG0Aof.jpeg"),
caption: "<b>Not So Secret Recipe</b>",
Expand All @@ -61,7 +73,7 @@ void main() {
});

test("Send Contact", () async {
Message message = await bot.api.sendContact(
final message = await bot.api.sendContact(
id,
"+628123456789",
"John",
Expand All @@ -75,7 +87,7 @@ void main() {
});

test("Send Location", () async {
Message message = await bot.api.sendLocation(
final message = await bot.api.sendLocation(
id,
37.4220,
-122.0841,
Expand All @@ -93,7 +105,7 @@ void main() {
});

test("Send Venue", () async {
Message message = await bot.api.sendVenue(
final message = await bot.api.sendVenue(
id,
37.4220,
-122.0841,
Expand All @@ -120,7 +132,7 @@ void main() {
// Send Invoice currently won't work because we don't provide a valid provider token
/*
test("Send Invoice", () async {
Message message = await bot.api.sendInvoice(
final message = await bot.api.sendInvoice(
id,
title: "Test Invoice",
description: "Test Invoice Description",
Expand All @@ -141,7 +153,7 @@ void main() {
*/

test("Send Video", () async {
Message message = await bot.api.sendVideo(
final message = await bot.api.sendVideo(
id,
InputFile.fromUrl(
"https://telegram.org/file/464001154/11e69/9FLiJnH4fF4.2869553.mp4/18ca1dba8837d3db6f",
Expand All @@ -159,7 +171,7 @@ void main() {
});

test("Send Sticker", () async {
Message message = await bot.api.sendSticker(
final message = await bot.api.sendSticker(
id,
InputFile.fromFileId(stickerFileID),
);
Expand All @@ -168,16 +180,16 @@ void main() {
});

test("Delete Message", () async {
Message message = await bot.api.sendMessage(id, "Hello World");
final message = await bot.api.sendMessage(id, "Hello World");
expect(message.text, "Hello World");
bool deleted = await bot.api.deleteMessage(id, message.messageId);
final deleted = await bot.api.deleteMessage(id, message.messageId);
expect(deleted, true, reason: "Message is not deleted");
});

test("Edit Message Text", () async {
Message message = await bot.api.sendMessage(id, "Hello World");
final message = await bot.api.sendMessage(id, "Hello World");
expect(message.text, "Hello World");
Message editedMessage = await bot.api.editMessageText(
final editedMessage = await bot.api.editMessageText(
id,
message.messageId,
"Hello World Edited",
Expand All @@ -186,19 +198,19 @@ void main() {
});

test("Get Chat", () async {
Chat chat = await bot.api.getChat(id);
Chat groupChat = await bot.api.getChat(groupID);
final chat = await bot.api.getChat(id);
final groupChat = await bot.api.getChat(groupID);
print(groupChat.type);
expect(chat.id, id.id);
});

test("Get Chat Administrators", () async {
List<ChatMember> chatMembers = await bot.api.getChatAdministrators(groupID);
final chatMembers = await bot.api.getChatAdministrators(groupID);
expect(chatMembers.isNotEmpty, true, reason: "Chat members is empty");
});

test("Get Chat Menu Button", () async {
MenuButton button = await bot.api.getChatMenuButton(id);
final button = await bot.api.getChatMenuButton(id);
print(button.type);
expect(MenuButtonType.values.contains(button.type), true);
});
Expand Down