Skip to content

Commit

Permalink
Merge: Televerse v1.10.1
Browse files Browse the repository at this point in the history
Refactors and performance 💎
  • Loading branch information
HeySreelal committed Jul 4, 2023
2 parents 6a10fc8 + b738fae commit 3421163
Show file tree
Hide file tree
Showing 8 changed files with 70 additions and 44 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
## 1.10.1

- Fixed an issue with the `command` method that crashed the bot when setting up the listener.
- Thanks to [@GiuseppeFn](https://github.com/GiuseppeFn) for reporting this issue.
- Refactored code for better performance.

## 1.10.0

- Introducing the `Televerse Conversation`! 🎉
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ We have an active Telegram group where you can discuss Televerse and get help fr

<a href="https://t.me/TeleverseDart">
<img src="https://img.shields.io/badge/Telegram-2CA5E0?style=for-the-badge&logo=telegram&logoColor=white"/>
</a> <a href="https://github.com/HeySreelal/televerse/discussions">
</a> <a href="https://github.com/HeySreelal/televerse/">
<img src="https://img.shields.io/badge/GitHub-100000?style=for-the-badge&logo=github&logoColor=white"/>
</a>

Expand Down
13 changes: 6 additions & 7 deletions lib/src/televerse/fetch/long_polling.dart
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,13 @@ class LongPolling extends Fetcher {
timeout: timeout,
allowedUpdates: allowedUpdates.map((e) => e.type).toList(),
);
for (var update in updates) {
int len = updates.length;
for (int i = 0; i < len; i++) {
if (_updateStreamController.isClosed) {
return;
}
addUpdate(update);
offset = update.updateId + 1;
addUpdate(updates[i]);
offset = updates[i].updateId + 1;
}

await Future.delayed(delayDuration);
Expand Down Expand Up @@ -129,10 +130,8 @@ class LongPolling extends Fetcher {
int limit = 100,
Duration delayDuration = const Duration(milliseconds: 200),
}) {
List<UpdateType> allowedUpdates = [
for (var type in UpdateType.values)
if (type != UpdateType.unknown) type
];
List<UpdateType> allowedUpdates = UpdateType.values;
allowedUpdates.remove(UpdateType.unknown);
return LongPolling(
allowedUpdates: allowedUpdates,
offset: offset,
Expand Down
9 changes: 9 additions & 0 deletions lib/src/televerse/models/televerse_exception.dart
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,13 @@ class TeleverseException implements Exception {
description:
"To save/load the session, you must provide a path or set the session ID.",
);

/// Exception thrown when the `getMe` request is failed when setting up a bot command.
static TeleverseException getMeRequestFailed(Object err, StackTrace stack) =>
TeleverseException(
"RawAPI/getMe Request Failed",
description:
"The request to getMe failed. Please check your internet connection and try again. \n\nError: $err",
stackTrace: stack,
);
}
34 changes: 17 additions & 17 deletions lib/src/televerse/raw_api.dart
Original file line number Diff line number Diff line change
Expand Up @@ -854,21 +854,24 @@ class RawAPI {
List<Map<String, dynamic>> mediaList = [];

if (media.any((m) => m.media.type == InputFileType.file)) {
for (InputMedia m in media) {
if (m.media.type == InputFileType.file) {
if (!m.media.file!.existsSync()) {
throw TeleverseException.fileDoesNotExist(m.media.file!.path);
int length = media.length;
for (int i = 0; i < length; i++) {
if (media[i].media.type == InputFileType.file) {
if (!media[i].media.file!.existsSync()) {
throw TeleverseException.fileDoesNotExist(
media[i].media.file!.path,
);
}
String filename = m.media.file!.path.split("/").last;
String filename = media[i].media.file!.filename;
files.add(
MultipartFile.fromBytes(
filename,
m.media.file!.readAsBytesSync(),
media[i].media.file!.readAsBytesSync(),
filename: filename,
),
);
}
mediaList.add(m.toJson());
mediaList.add(media[i].toJson());
}
params["media"] = jsonEncode(mediaList);
List<dynamic> response = await HttpClient.multipartPost(
Expand Down Expand Up @@ -1783,9 +1786,7 @@ class RawAPI {
List<dynamic> data = await HttpClient.getURI(
_buildUri("getChatAdministrators", params),
);
for (var i = 0; i < data.length; i++) {
response.add(ChatMember.fromJson(data[i]));
}
response = data.map((e) => ChatMember.fromJson(e)).toList();
return response;
}

Expand Down Expand Up @@ -1853,9 +1854,7 @@ class RawAPI {
List<dynamic> data = await HttpClient.getURI(
_buildUri("getForumTopicIconStickers"),
);
for (var i = 0; i < data.length; i++) {
response.add(Sticker.fromJson(data[i]));
}
response = data.map((e) => Sticker.fromJson(e)).toList();
return response;
}

Expand Down Expand Up @@ -3270,13 +3269,14 @@ class RawAPI {
};
bool response;
List<MultipartFile> files = [];
int len = stickers.length;

for (var sticker in stickers) {
if (sticker.sticker.type == InputFileType.file) {
String fileName = sticker.sticker.file!.path.split("/").last;
for (int i = 0; i < len; i++) {
if (stickers[i].sticker.type == InputFileType.file) {
String fileName = stickers[i].sticker.file!.path.split("/").last;
files.add(MultipartFile.fromBytes(
fileName,
sticker.sticker.file!.readAsBytesSync(),
stickers[i].sticker.file!.readAsBytesSync(),
filename: fileName,
));
}
Expand Down
5 changes: 3 additions & 2 deletions lib/src/televerse/sessions/sessions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,9 @@ class SessionsManager<T extends Session> {
/// bot.sessions.saveAllSessions(path: '/path/to/sessions');
/// ```
void saveAllSessions({String? path}) {
for (final session in _sessions.values) {
session?.saveToFile(path: path);
final int count = _sessions.length;
for (int i = 0; i < count; i++) {
_sessions[i]?.saveToFile(path: path);
}
}

Expand Down
43 changes: 27 additions & 16 deletions lib/src/televerse/televerse.dart
Original file line number Diff line number Diff line change
Expand Up @@ -173,29 +173,30 @@ class Televerse<TeleverseSession extends Session> {
void _onUpdate(Update update) async {
final sub = _handlerScopes.reversed.where((scope) {
return scope.types.contains(update.type);
});
for (HandlerScope scope in sub) {
}).toList();
int len = sub.length;
for (int i = 0; i < len; i++) {
Context context = Context.create(this, update);
if (scope.isConversation && scope.predicate(context)) {
if (sub[i].isConversation && sub[i].predicate(context)) {
break;
}
if (scope.handler == null) continue;
if (sub[i].handler == null) continue;
if (scope.special) {
if (scope.isRegExp) {
if (sub[i].special) {
if (sub[i].isRegExp) {
context as MessageContext;
String? text = context.message.text;
if (text != null && scope.pattern != null) {
context.matches = scope.pattern!.allMatches(text).toList();
if (text != null && sub[i].pattern != null) {
context.matches = sub[i].pattern!.allMatches(text).toList();
}
}
}
if (scope.predicate(context)) {
if (_checkSync(scope.handler!)) {
((scope.handler!(context)) as Future)
if (sub[i].predicate(context)) {
if (_checkSync(sub[i].handler!)) {
((sub[i].handler!(context)) as Future)
.then((_) {})
.catchError((err) async {
if (_onError != null) {
Expand All @@ -206,7 +207,7 @@ class Televerse<TeleverseSession extends Session> {
});
} else {
try {
scope.handler!(context);
sub[i].handler!(context);
} catch (err, stack) {
if (_onError != null) {
await _onError!(err, stack);
Expand Down Expand Up @@ -326,11 +327,21 @@ class Televerse<TeleverseSession extends Session> {
Pattern command,
MessageHandler callback,
) async {
User bot;
User? bot;
try {
bot = me;
} catch (err) {
bot = await api.getMe();
try {
bot = await api.getMe();
_me = bot;
} catch (err, st) {
if (_onError != null) {
final ex = TeleverseException.getMeRequestFailed(err, st);
await _onError!(ex, st);
} else {
rethrow;
}
}
}
HandlerScope scope = HandlerScope<MessageHandler>(
isCommand: true,
Expand All @@ -343,8 +354,8 @@ class Televerse<TeleverseSession extends Session> {
return command.hasMatch(ctx.message.text!);
} else if (command is String) {
final firstTerm = ctx.message.text!.split(' ').first;
return firstTerm == '/$command' ||
firstTerm == '/$command@${bot.username}';
final suffix = bot?.username != null ? '@${bot?.username}' : '';
return firstTerm == '/$command' || firstTerm == '/$command$suffix';
}
return false;
},
Expand Down
2 changes: 1 addition & 1 deletion pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name: televerse
description: Televerse lets you create your own efficient Telegram bots with ease in Dart. Supports latest Telegram Bot API - 6.7!
version: 1.10.0
version: 1.10.1
homepage: https://github.com/HeySreelal/televerse

environment:
Expand Down

0 comments on commit 3421163

Please sign in to comment.