Skip to content

Commit

Permalink
Merge pull request #24 from KaikyuLotus/APIv7.0
Browse files Browse the repository at this point in the history
Api v7.0
  • Loading branch information
ale183 authored Apr 13, 2024
2 parents 5a9704d + 83ff92e commit fb16fad
Show file tree
Hide file tree
Showing 141 changed files with 2,468 additions and 526 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
## 1.2.0

- Updated to bot API 7.0
- Minor improvements and fixes

## 1.1.0

- Stable release
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Dart Telegram Bot is a [Dart](https://dart.dev) wrapper for [Telegram](https://t
bot [API](https://core.telegram.org/bots/api). \
It is compatible with Native, Flutter and JS.

[![Bot API Version](https://img.shields.io/badge/Bot%20API-6.9-blue.svg?style=flat-square)](https://core.telegram.org/bots/api)
[![Bot API Version](https://img.shields.io/badge/Bot%20API-7.0-blue.svg?style=flat-square)](https://core.telegram.org/bots/api)
[![Dart Version](https://img.shields.io/badge/Dart-2.15.0-blue.svg?style=flat-square)](https://dart.dev)

Using Dart Telegram Bot is straightforward, here's an example echo bot:
Expand Down
137 changes: 66 additions & 71 deletions example/bot_example.dart
Original file line number Diff line number Diff line change
Expand Up @@ -21,76 +21,70 @@ void main(List<String> arguments) async {

var token = Platform.environment['BOT_TOKEN']!;

var bot = Bot(
Bot(
token: token,
onReady: onReady,
onStartFailed: onStartFailed,
allowedUpdates: UpdateType.allBut([UpdateType.editedMessage]),
);

bot.onUpdate(_onUpdate);

bot.onCommand('buttons', (bot, update) async {
var buttons = [
[InlineKeyboardButton.callbackData('Button 1', 'btn1')],
[InlineKeyboardButton.callbackData('Button 2', 'btn2')]
];
await bot.sendMessage(
ChatID(update.message!.chat.id),
'Tap a button...',
replyMarkup: InlineKeyboardMarkup(buttons),
);
});

bot.onCommand('chatid', (bot, update) async {
await bot.sendMessage(
ChatID(update.message!.chat.id),
'*Chat ID*: `${update.message!.chat.id}`',
parseMode: ParseMode.markdown,
);
});

bot.onCommand('msgid', (bot, update) async {
await bot.sendMessage(
ChatID(update.message!.chat.id),
'*Message ID*: `${update.message!.messageId}`',
parseMode: ParseMode.markdown,
);
});

bot.onCommand('uid', (bot, update) async {
await bot.sendMessage(
ChatID(update.message!.chat.id),
'*ID*: `${update.message!.from!.id}`',
parseMode: ParseMode.markdown,
);
});

bot.onCommand('quid', (bot, update) async {
if (update.message!.replyToMessage == null) return;
await bot.sendMessage(
ChatID(update.message!.chat.id),
'*ID*: `${update.message!.replyToMessage!.from!.id}`',
parseMode: ParseMode.markdown,
);
});

bot.onCommand('poll', (bot, update) async {
await bot.sendPoll(
ChatID(update.message!.chat.id),
'Nani desu ka?',
['Hai!', 'Ara ara?', '!'],
replyToMessageId: update.message!.messageId,
allowsMultipleAnswers: true,
isAnonymous: true,
type: 'quiz',
correctOptionId: 1,
);
});
)
..errorHandler = defaultErrorHandler
..onUpdate(_onUpdate)
..onCommand('buttons', (bot, update) async {
var buttons = [
[InlineKeyboardButton.callbackData('Button 1', 'btn1')],
[InlineKeyboardButton.callbackData('Button 2', 'btn2')],
];
await bot.sendMessage(
ChatID(update.message!.chat.id),
'Tap a button...',
replyMarkup: InlineKeyboardMarkup(buttons),
);
})
..onCommand('chatid', (bot, update) async {
await bot.sendMessage(
ChatID(update.message!.chat.id),
'*Chat ID*: `${update.message!.chat.id}`',
parseMode: ParseMode.markdown,
);
})
..onCommand('msgid', (bot, update) async {
await bot.sendMessage(
ChatID(update.message!.chat.id),
'*Message ID*: `${update.message!.messageId}`',
parseMode: ParseMode.markdown,
);
})
..onCommand('uid', (bot, update) async {
await bot.sendMessage(
ChatID(update.message!.chat.id),
'*ID*: `${update.message!.from!.id}`',
parseMode: ParseMode.markdown,
);
})
..onCommand('quid', (bot, update) async {
if (update.message!.replyToMessage == null) return;
await bot.sendMessage(
ChatID(update.message!.chat.id),
'*ID*: `${update.message!.replyToMessage!.from!.id}`',
parseMode: ParseMode.markdown,
);
})
..onCommand('poll', (bot, update) async {
await bot.sendPoll(
ChatID(update.message!.chat.id),
'Nani desu ka?',
['Hai!', 'Ara ara?', '!'],
replyParameters: ReplyParameters(update.message!.messageId),
allowsMultipleAnswers: true,
isAnonymous: true,
type: 'quiz',
correctOptionId: 1,
);
});
}

void defaultErrorHandler(Object e, StackTrace s) {
print('something failed: $e\n$s');
Future defaultErrorHandler(_, __, Object e, StackTrace s) async {
print('Something failed: $e\n$s');
}

void onStartFailed(Bot bot, Object err, StackTrace st) {
Expand Down Expand Up @@ -132,7 +126,7 @@ Future _onUpdate(Bot bot, Update update) async {
'/results?search_query=Zekk+-+TOMOYO)',
parseMode: ParseMode.markdown,
),
)
),
],
cacheTime: 0,
);
Expand All @@ -142,7 +136,6 @@ Future _onUpdate(Bot bot, Update update) async {

// Those will be converted into tests
if (update.message == null) return;
if (update.editedMessage != null) return; // Ignore edited messages

var chatId = ChatID(update.message!.chat.id);
print('$chatId - ${update.message!.messageId}');
Expand Down Expand Up @@ -227,11 +220,13 @@ Future _onUpdate(Bot bot, Update update) async {
);
}

if (update.message!.forwardFrom != null) {
var user = update.message!.forwardFrom!;
var resp = 'Forwarded from ${user.firstName} '
'(${user.id} / @${user.username})';
return bot.sendMessage(chatId, resp);
if (update.message!.forwardOrigin != null) {
var forwardOrigin = update.message!.forwardOrigin!;
if (forwardOrigin is MessageOriginUser) {
var resp = 'Forwarded from ${forwardOrigin.senderUser.firstName} '
'(${forwardOrigin.senderUser.id} / @${forwardOrigin.senderUser.username})';
return bot.sendMessage(chatId, resp);
}
}

if (update.message!.videoNote != null) {
Expand Down
28 changes: 17 additions & 11 deletions lib/src/entities/internal/bot.dart
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ class Bot with TGAPIMethods {

var _log = Logger('Bot');

/// List of allowed updates to be received<br>
/// List of allowed updates to be received
///
/// Can be changed while the bot is running
List<UpdateType>? allowedUpdates;

Expand Down Expand Up @@ -72,7 +73,7 @@ class Bot with TGAPIMethods {
_timeout = timeout,
_onStartFailedEvent = onStartFailed {
this.token = token;
_setup();
unawaited(_setup());
}

/// Override this method when extending this class
Expand Down Expand Up @@ -104,7 +105,7 @@ class Bot with TGAPIMethods {
var user = await getMe();
_id = user.id;
_name = user.firstName;
_username = user.username!;
_username = user.username;
_log = Logger(_name!);
}

Expand All @@ -114,13 +115,15 @@ class Bot with TGAPIMethods {
if (clean) {
await _cleanUpdates();
}

await _eventLoop();
// Clean last read update
await getUpdates(timeout: 0, offset: _offset);
}

/// Adds a new update handler
/// which is executed on each update<br>
/// which is executed on each update
///
/// If an handler throws an error, [errorHandler] is called
/// and the next handler/update is elaborated
void onUpdate(Future Function(Bot, Update) callback) {
Expand All @@ -142,8 +145,9 @@ class Bot with TGAPIMethods {
}

Future _criticalErrorHandler(Object e, StackTrace st) async {
_log.severe('An exception occurred during an exception handling');
_log.severe(e, st);
_log
..severe('An exception occurred during an exception handling')
..severe(e, st);
}

Future _onConnectionError(Bot bot, Object error, StackTrace st) async {
Expand All @@ -170,14 +174,13 @@ class Bot with TGAPIMethods {
closeClient();
return;
}

await _onReady();
}

void _runProtectedSimple(Function foo) {
runZonedGuarded(
() {
foo();
},
() => foo(),
_criticalErrorHandler,
);
}
Expand All @@ -189,7 +192,7 @@ class Bot with TGAPIMethods {
}) {
runZonedGuarded(
foo,
(e, s) => (customErrHandler ?? _onError)(this, update, e, s),
(e, s) async => (customErrHandler ?? _onError)(this, update, e, s),
);
}

Expand All @@ -198,6 +201,7 @@ class Bot with TGAPIMethods {
Future<bool> _checkCommands(Update update) async {
var message = update.message;
if (message == null || message.text == null) return false;

var cmdParser = BotCommandParser.fromMessage(message);
if (cmdParser == null) return false;

Expand All @@ -208,6 +212,7 @@ class Bot with TGAPIMethods {
username: username,
);
if (!isMatching) continue;

anyExecuted = true;
_runProtected(() => commandEntry.value.call(this, update), update);
}
Expand All @@ -216,6 +221,7 @@ class Bot with TGAPIMethods {

Future _handleUpdate(Update update) async {
if (await _checkCommands(update)) return;

for (var callback in _updateCallbacks) {
_runProtected(() => callback(this, update), update);
}
Expand All @@ -237,7 +243,7 @@ class Bot with TGAPIMethods {
}
} on ClientException catch (e, s) {
await _onConnectionError(this, e, s);
await Future.delayed(Duration(seconds: 1));
await Future.delayed(const Duration(seconds: 1));
} on Exception catch (e, s) {
_log.severe('Loop body exception', e, s);
} on Error catch (e, s) {
Expand Down
16 changes: 11 additions & 5 deletions lib/src/entities/internal/entities/chat_id.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,24 @@ class ChatID {
/// Telegram ChatUsername
String? chatUsername;

ChatID._internal({this.chatUsername});

/// ChatId constructor
ChatID(this.chatId);

ChatID._internal({this.chatUsername});

/// Username constructor
factory ChatID.fromUsername(String username) {
return ChatID._internal(chatUsername: username);
}

@override
String toString() {
return (chatId ?? chatUsername)!.toString();
factory ChatID.fromJson(Map<String, dynamic> json) {
if (int.tryParse(json['chat_id']) == null) {
return ChatID.fromUsername(json['chat_id']);
} else {
return ChatID(int.parse(json['chat_id']));
}
}

@override
String toString() => (chatId ?? chatUsername)!.toString();
}
2 changes: 1 addition & 1 deletion lib/src/entities/internal/helpers/bot_command_parser.dart
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ class BotCommandParser {
return false;
}
}

return command.toLowerCase() == this.command.toLowerCase();
}

Expand All @@ -44,7 +45,6 @@ class BotCommandParser {
var command = match.group(1)!;
var username = match.group(2);
var foundArgs = match.group(3);

if (foundArgs != null) {
return BotCommandParser(command, username, args: foundArgs.split(' '));
}
Expand Down
Loading

0 comments on commit fb16fad

Please sign in to comment.