dinoleung / teledart Goto Github PK
View Code? Open in Web Editor NEWA Dart library interfacing with the latest Telegram Bot API.
Home Page: https://pub.dev/packages/teledart
License: GNU General Public License v3.0
A Dart library interfacing with the latest Telegram Bot API.
Home Page: https://pub.dev/packages/teledart
License: GNU General Public License v3.0
Hello Dino!
I just forked your repository and was trying to make a compatilble version of the library with the javascript generated by https://pub.dev/packages/build_node_compilers
It is actually easy to make a node compatible project. I just added some conditional imports to teledart to import either the standard dart:io
and http
or the node_io
or node_http
depending on the build environment.
This is the current import for your http_client
class:
But there is a huge issue. Not all methods and classes from http
are implemented on node_http
, and one of the is the MultipartRequest
. Also, the SecurityContext
the you use on the class WebHook
also is not implemented yet.
This are some erros we get when trying to compile it to node:
Error: 'MultipartFile' isn't a type.
Future<dynamic> httpMultipartPost(String url, List<http.MultipartFile> files,
^^^^^^^^^^^^^
Error: Method not found: 'MultipartRequest'.
var request = http.MultipartRequest('POST', Uri.parse(url))
^^^^^^^^^^^^^^^^
Error: Method not found: 'HttpServer.bindSecure'.
Future<dynamic> serverFuture = io.HttpServer.bindSecure(
^^^^^^^^^^
-------------------------------------------------------------------------------
Error: Method not found: 'SecurityContext'.
_context = io.SecurityContext();
^^^^^^^^^^^^^^^
Error: Getter not found: 'anyIPv4'.
io.InternetAddress.anyIPv4.address, port, _context);
^^^^^^^
My question is: are those classes really needed for the working of the library? There is a way to replace them by other types?
What do you think?
How to use the getChatAdministrators Method?
I can't find this method...
I have wrote this code:
import 'package:teledart/teledart.dart';
import 'package:teledart/telegram.dart';
import 'package:teledart/model.dart';
void main(List<String> args) {
TeleDart t = TeleDart(Telegram('token'), Event());
t.startFetching();
final btns = <List<KeyboardButton>>[<KeyboardButton>[KeyboardButton(text: 'Yes'), KeyboardButton(text: 'No')]];
final keyboard = ReplyKeyboardMarkup(keyboard: btns);
t.onCommand('start').listen((msg) => t.replyMessage(msg, 'Some question?', reply_markup: keyboard));
}
And then a have got an error:
Unhandled exception:
HttpClientException:
HttpClientException:
400 Bad Request: can't parse keyboard button: Field "request_contact" must be of type Boolean
#0 Telegram.sendMessage (package:teledart/src/telegram/telegram.dart:109:29)
#1 TeleDart.replyMessage (package:teledart/src/teledart/teledart.dart:235:16)
#2 main. (file:///Users/ky/Projects/medical_bot/bin//bot.dart:13:42)
When I trying fix this (set true or false to parameter) - a new similar error is coming with other parameter. But they are optional and if I don't give them boolean value, they shouldn't influence my request.
Telegram have method to forward message but when you forward it will show you "forward from x user or x channel"
Add parameter with forward function
as_copy (bool, optional)
– Pass True to forward messages without the forward header (i.e.: send a copy of the message content).
That will send same message like a normal message not forwarded
Unhandled exception after a few hours LongPollingException: HttpClientException: SocketException: Failed host lookup: 'api.telegram.org' (OS Error: nodename nor servname provided, or not known, errno = 8)
Unhandled exception:
LongPollingException: HttpClientException: SocketException: Failed host lookup: 'api.telegram.org' (OS Error: nodename nor servname provided, or not known, errno = 8)
#0 LongPolling._recursivePolling.<anonymous closure> (package:teledart/src/teledart/fetch/long_polling.dart:97:21)
#1 _rootRunUnary (dart:async/zone.dart:1132:38)
#2 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#3 _FutureListener.handleError (dart:async/future_impl.dart:144:20)
#4 Future._propagateToListeners.handleError (dart:async/future_impl.dart:651:47)
#5 Future._propagateToListeners (dart:async/future_impl.dart:672:24)
#6 Future._completeError (dart:async/future_impl.dart:491:5)
#7 _SyncCompleter._completeError (dart:async/future_impl.dart:55:12)
#8 _Completer.completeError (dart:async/future_impl.dart:27:5)
#9 _AsyncAwaitCompleter.completeError (dart:async-patch/async_patch.dart:40:18)
#10 Telegram.getUpdates (package:teledart/src/telegram/telegram.dart)
Smart Plugins powerful plugin system that is meant to further simplify the organization of large projects and to provide a way for creating pluggable (modular) components that can be easily shared across different applications with minimal boilerplate code
like the main file is main.dart
And there is folder in same path plugins
in side it the project files like welcome_message.dart and help_message.dart
More Information Here
seperate methods telegram.dart
and teledart.dart
into multiple files.
Currently it sends a DM to the sender, while it is expected to send messages to the group
The exception is thrown after the bot tries to reply to the user (replyMessage (...)), after the user first wrote a message to the chatbot (which was not launched yet), and then "Delete and stop" the chatbot:
Unhandled Exception:
HttpClientException: null null.
or in other words:
Unhandled exception:
HttpClientException: null null
Is it possible to use teledart to process a message with a keyword if the message contains a hashtag?
teledart
..start(webhook: false).then((User user) => me = user)
// Will not work if the message has a hashtag:
..onMessage(keyword: 'Hi').listen((message) {teledart.replyMessage(message, 'Hello');})
..onHashtag().listen((message) {teledart.replyMessage(message, 'I\'ts hashtag');});
Example: https://ibb.co/JC7HTrs,
Unhandled exception:
HttpClientException: HttpClientException: 400 Bad Request: field "keyboard" of the ReplyKeyboardMarkup should be an Array of Arrays
#0 Telegram.sendMessage (package:teledart/src/telegram/telegram.dart:109:29)
...
Make .onCommand accept list of commands
like .onCommand(["start", "help"])
and when user send /start or /help will get same message
Also prefix with on commands to select what command use
Like .onCommand("start", prefix: ["!", "/", "#"])
That is mean if message /start or /start or #start will deal with it as command and reply
The removeWebhook()
method will work correctly only if the setupWebhook(...)
method was called before it in the current script.
But if I am not using webhook, but want to make sure it is disabled, I can execute teledart.telegram.deleteWebhook();
To use this method:
teledart.removeWebhook()
I suggest adding a couple of lines of code to the removeWebhook()
method:
void removeWebhook() {
if (_webhook != null) {
_webhook.deleteWebhook().then((_) {
_webhook.stopWebhook();
_webhook = null;
});
} else { // +
telegram.deleteWebhook(); // +
} // +
}
I am trying to mute users, but instead i get this error:
Converting object to an encodable object failed: Instance of 'ChatPermissions'
Snippet to reproduce the behavior:
var chat_id = message.chat.id;
var user_id = message.user.id;
var permissions = new ChatPermissions(can_send_messages: false);
var until_date = DateTime.now().millisecondsSinceEpoch + (7 * 24 * 60 * 60);
telegram.restrictChatMember(chat_id, user_id,
permissions: permissions, until_date: until_date);
I expected that the user is muted, but it was not muted.
The user has no admin rights, it's a supergroup and i'm a dart newbie.
I want to have a simple method like this
teledart.sendMessage( 'Hello')
right now! we have to wait before we can reply
teledart
.onCommand('hello')
.listen(((message) => teledart.replyMessage(message, 'world')));
Is there anything preventing this being used as a communications system from inside a Flutter app.
Sorry i am so lazy about checking the transport but ...
I assume that https://github.com/DinoLeung/DartWiseBot could just also be wrapped with a Dart GRPC, and then the Flutter GRPC uses it.
But i was hoping to be able to go direct from Flutter to Telegram without a Server in the middle.
The other way is to embed golang inside the FLutter app using https://github.com/go-telegram-bot-api/telegram-bot-api
thats just a gomobile compile away and some tinkering.
Hello! Such an amazing library! Thank you so much for your work.
I am using it on a side project but I realized that some properties are impossible to know it's meaning by just looking into the code. For example:
Message
class has a propery named date
(and forward_date
and edit_date
), as an int
value. But what doest it mean? Is it milliseconds since epoch or microseconds? And it is UTC date?Audio
has a int
property named duration
. Is it seconds, milliseconds or microseconds?For those two problems above there are 2 simple solutions:
DateTime
objects.Duration
objects.Both are dart native objects :)
Hope you consider that request.
Best regards!
Function to send all types of media from File Id
send_media
function short a lot if things
send photos, videos, audios, sticker .. etc from telegram file id
I tried running TeleDart_example.dart
and when I send any message that was not a registered command (ie. /start), example crashed with this error:
Unhandled exception:
NoSuchMethodError: The method 'substring' was called on null.
Receiver: null
Tried calling: substring(1)
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
#1 Event.onMessage.<anonymous closure> (package:teledart/src/teledart/event/event.dart:95:22)
#2 _WhereStream._handleData (dart:async/stream_pipe.dart:203:19)
#3 _ForwardingStreamSubscription._handleData (dart:async/stream_pipe.dart:166:13)
#4 _RootZone.runUnaryGuarded (dart:async/zone.dart:1316:10)
#5 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:338:11)
#6 _DelayedData.perform (dart:async/stream_impl.dart:593:14)
#7 _StreamImplEvents.handleNext (dart:async/stream_impl.dart:709:11)
#8 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:669:7)
#9 _microtaskLoop (dart:async/schedule_microtask.dart:43:21)
#10 _startMicrotaskLoop (dart:async/schedule_microtask.dart:52:5)
#11 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:393:30)
#12 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:418:5)
#13 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:174:12)
I've attached screenshot from Telegram app for clarity:
I don't see any error in TeleDart_example.dart
so I assume that the error is not on my side.
pubspec.yaml:
...
environment:
sdk: '>=2.4.0 <3.0.0'
dependencies:
teledart: ^0.0.37
...
dart --version:
Dart VM version: 2.7.2 (Mon Mar 23 22:11:27 2020 +0100) on "windows_x64"
Method onMessage(...)
- handles all messages (commands, regular messages and so on).
When I try write /start
in chat:
await _t.startFetching();
_t.onCommand('start').listen((msg) => _t.replyMessage(msg, 'text'));
_t.onMessage().listen((msg) => _t.replyMessage(msg, 'next text'));
All this methods are catch the same msg
object and both of them print their message. I think it is unacceptable behavior. onMessage(...)
don't need be able catch everything, why then more precise methods are created? Maybe I wrote a bad code?
Currently it only accept id(int), however according to the official docs, it needs to accept username(string) also
Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
When trying to send a poll a get :
Unhandled exception:
HttpClientException: HttpClientException: 400 Bad Request: can't parse options JSON object
#0 Telegram.sendPoll (package:teledart/src/telegram/telegram.dart:830:29)
Snippet to reproduce the behavior:
sendPoll(22, "My Question", List<String>()..addAll(['Choice1', 'Choice2']));
Replace in method Telegram.sendPoll (line 824)
https://github.com/DinoLeung/TeleDart/blob/master/lib/src/telegram/telegram.dart#L825
'options': options,
by
'options': jsonEncode(options),
Currently the library cannot listen to message type which is not support at the moment. So when telegram roll out new attributes developers need to wait until the library get updated.
Make the default case in event.onMessage()
returns message with entityType keyword input.
expect to looks like:
event.onMessage(entityType: 'unsupported_type', keyword: 'keyword').listen((msg) => {})
Is it possible to use teledart to process a message with a keyword if the message contains a hashtag?
teledart
..start(webhook: false).then((User user) => me = user)
// Will not work if the message has a hashtag:
..onMessage(keyword: 'Hi').listen((message) {teledart.replyMessage(message, 'Hello');})
..onHashtag().listen((message) {teledart.replyMessage(message, 'I\'ts hashtag');});
Example: https://ibb.co/JC7HTrs,
I like the distinction of telegram
and teledart
– one is a simple typed wrapper around web requests, the other one a full-fledged powerful API that uses the capabilities of object-oriented programming. Some aspects like the inline mode are really great, but I think other parts could be a bit better.
For example, most requests still need to be made through the teledart
instance with the exception of replies. I'd love it if you could simply send a message to a chat if you got hold of the Chat
. Something like chat.send('Some text.')
.
Also, most fields currently have the name from the API in snake_case
instead of using an adapted camelCase
version. The typing could also be a bit stronger. For example, we could create a ChatId
class to represent a reference to a Chat
. Then we could do stuff like this:
final id = someMessage.chat.id;
final chat = await id.resolve();
We could also introduce classes for several other concepts to make them type-safe. Take photos for example. Currently, the telegram.sendPhoto
function accepts dynamic
as a photo and developers are forced to go to the Telegram API documentation to find out what they can send, but we could also create a Photo
class which gets subclassed by PhotoUrl
, and PhotoFile
. Users could then create photos using Photo.fromUrl(…)
and Photo.fromFile(…)
constructors, which makes the API easier to use and explore.
Let me know what you think about this. I'd be happy to help implementing these changes.
So far we’ve seen how to register a callback function that executes every time a specific update comes from the server, but there’s much more than that to come.
Here we’ll discuss about Filters.
Filters enable a fine-grain control over what kind of updates are allowed or not to be passed in your callback functions, based on their inner details.
Like What Pyrogram Do Here
More details Here
Yes. I want to have a Telegram bot written in Dart and deployed with Firebase Cloud Functions and webhooks so my cloud function gets called by Telegram app when users send messages to the bot. That's why I have to handle updates independently (I don't need to listen, i.e. to call start()
). But the problem is that _updatesHandler()
method is private.
So what I'm trying to achieve is this:
Set webhook manually with help of Telegram's setWebhook()
method via http request to my cloud function, then
Telegram bot message -> Cloud function -> handle update
For example, in Node.JS framework called Telegraf, they have handleUpdate()
method, and if I was using it, I would have to do something like this (to call handleUpdate()
when my cloud function is called).
I'd like to have the _updatesHandler()
method public:
/// Private method to add updates into events queue
void updatesHandler(Update update) => _event.emitUpdate(update);
Or something similar:
/// Handle raw Telegram update. In case you use centralized webhook server, queue, etc.
void handleUpdate(Update update) => _updatesHandler(update);
Or any other solution...
Thanks!
Can you give me a example how to delete a message?
There are no method when I try use teledart.deleteMessage(chat_id, message_id);
Thank you
Kinda - I don't understand how to use the fromJson methods, eg the one for ReplyKeyboardMarkup, I assumed it would take a json string, instead it takes a Map<String, dynamic>, what keys are expected in that?
Add some doc examples of how the fromJson methods can be called
400 Bad Request Error when sending a message with reply_markup of InlineKeyboardMarkup, as its inline_keyboard argument should be a List<List<InlineKeyboardButton>>
.
I put my Token Telegram to test this example...(I´m sure my Token is Ok, because it´s running under my Qt application and my site ).
The "start" method is not working.
I updated all my dependecies like this example.
This is the message error:
Unhandled exception:
TeleDartException: TeleDartException: HttpClientException: HttpClientException: 404 Not Found
#0 TeleDart.start.<anonymous closure> (package:teledart/src/teledart/teledart.dart:70:27)
#1 _RootZone.runUnary (dart:async/zone.dart:1379:54)
#2 _FutureListener.handleError (dart:async/future_impl.dart:144:20)
#3 Future._propagateToListeners.handleError (dart:async/future_impl.dart:651:47)
#4 Future._propagateToListeners (dart:async/future_impl.dart:672:24)
#5 Future._completeError (dart:async/future_impl.dart:491:5)
#6 _SyncCompleter._completeError (dart:async/future_impl.dart:55:12)
#7 _Completer.completeError (dart:async/future_impl.dart:27:5)
#8 _RootZone.runBinary (dart:async/zone.dart:1384:54)
#9 _FutureListener.handleError (dart:async/future_impl.dart:140:20)
#10 Future._propagateToListeners.handleError (dart:async/future_impl.dart:651:47)
#11 Future._propagateToListeners (dart:async/future_impl.dart:672:24)
#12 Future._completeError (dart:async/future_impl.dart:491:5)
#13 _SyncCompleter._completeError (dart:async/future_impl.dart:55:12)
#14 _Completer.completeError (dart:async/future_impl.dart:27:5)
#15 _AsyncAwaitCompleter.completeError (dart:async-patch/async_patch.dart:40:18)
#16 Telegram.getMe (package:teledart/src/telegram/telegram.dart)
<asynchronous suspension>
#17 TeleDart._initBotInfo (package:teledart/src/teledart/teledart.dart:39:49)
<asynchronous suspension>
#18 TeleDart.start (package:teledart/src/teledart/teledart.dart:53:13)
<asynchronous suspension>
#19 main (file:///mnt/midia4/prj/Android/Telegram/bin/main.dart:14:12)
#20 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:300:19)
#21 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:171:12)
Am I doing anything wrong?
Greetings
Unhandled exception:
type 'Future' is not a subtype of type 'FutureOr'
Snippet to reproduce the behaviour:
teledart.answerInlineQuery(inlineQuery, results);
It looks like a file name cannot be specified for the document being sent right now. The file size value will be automatically substituted for the name. It would be convenient to set the file name in the parameters of the sendDocument (...) method.
It would be great to support proxies for countries like Russia where telegram is blocked :)
Bot api updated to 4.3
I need to know in bot about deleted by others users messages. Can I do it using teledart api?
Hello!
Thank you for your work! We need to do something similar to the NLP algorithm. But, we cannot change the case sensitivity with the help of additional parameters. And we cannot change the case sensitivity in the RegExp object with the necessary parameters.
So you have to write something like this:
teledart.onMessage (keyword: r '(Hi|hi|hI|HI)')
inputmedia can only take file_id
and HTTP URL
right now
need to implement POST
multipart/form-data
uploading files
might need to implement a inputFile
object
https://core.telegram.org/bots/api#sending-files
In NodeJS (actually in Telegraf) you write
bot.on('new_chat_members', (ctx) => console.log(ctx))
and it will handle new chat member, but here I can't find anything like this.
What about this feature?
dartson is not under maintenance
https://stackoverflow.com/a/45189401
https://pub.dartlang.org/packages/json_serializable
https://stackoverflow.com/a/49542401
Webhook support is required
Hi dino,
I am trying to contact you my e-mail, but the e-mail in flutter [email protected] does not exists.
I am trying to port my telegram bot (today in ruby) to dart using your lib.
What version of flutter must be use?
I am using stable and when I open your example in the vscode, the packages:
import 'package:teledart/teledart.dart';
import 'package:teledart/telegram.dart';
import 'package:teledart/model.dart';
show as Target URI not found.
Thank you,
Paulo
I managed to generate a "Bad Request" error (by sending parse_mode: 'MarkdownV2' on sendMessage), which just gives me an exception as "HttpClientException: null null" - I ended up having to put a breakpoint in your http client code to figure out what it was trying to tell me.
Snippet to reproduce the behavior:
teledart.telegram.sendMessage($someuserid, 'Some long text', parse_mode: 'MarkdownV2');
The client should output HttpClientException: (400) (Bad Request)
As to why I'm getting a Bad Request, I'm not sure - I've messaged telegram support to ask why (as teledart is just passing through my parse_mode string)
The call to removeLongPolling does not stop the longpolling recursive loop to make GET requests to Telegram API URL.
call
teledart.removeLongPolling();
The bot stops responding to Telegram messages. The recursive loop is stopped.
The polling continues and GET requests are sent to Telegram API. Bot continues to answer user messages.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.