WWW::Telegram::BotAPI implements the following methods.
new
my $api = WWW::Telegram::BotAPI->new (%options);
Creates a new WWW::Telegram::BotAPI instance.
WARNING: you should only create one instance of this module and reuse it when needed. Calling "new" each
time you run an async request causes unexpected behavior with Mojo::UserAgent and won't work correctly.
See also issue #13 on GitHub <https://github.com/Robertof/perl-www-telegram-botapi/issues/13>.
%options may contain the following:
• "token => 'my_token'"
The token that will be used to authenticate the bot.
Thisisrequired!Themethodwillcroakifthisoptionisnotspecified.
• "api_url => 'https://api.example.com/token/%s/method/%s'"
A format string that will be used to create the final API URL. The first parameter specifies the
token, the second one specifies the method.
Defaults to "https://api.telegram.org/bot%s/%s".
• "async => 1"
Enables asynchronous requests.
ThisrequiresMojo::UserAgent,andthemethodwillcroakifitisn'tfound.
Defaults to 0.
• "force_lwp => 1"
Forces the usage of LWP::UserAgent instead of Mojo::UserAgent, even if the latter is available.
By default, the module tries to load Mojo::UserAgent, and on failure it uses LWP::UserAgent.
AUTOLOAD
$api->getMe;
$api->sendMessage ({
chat_id => 123456,
text => 'Hello world!'
});
# with async => 1 and the IOLoop already started
$api->setWebhook ({ url => 'https://example.com/webhook' }, sub {
my ($ua, $tx) = @_;
die if $tx->error;
say 'Webhook set!'
});
This module makes use of "Autoloading" in perlsub. This means that everycurrentandfuturemethodoftheTelegramBotAPIcanbeusedbycallingitsPerlequivalent, without requiring an update of the module.
If you'd like to avoid using "AUTOLOAD", then you may simply call the "api_request" method specifying the
method name as the first argument.
$api->api_request ('getMe');
This is, by the way, the exact thing the "AUTOLOAD" method of this module does.
api_request
# Remember: each of these samples can be aliased with
# $api->methodName ($params).
$api->api_request ('getMe');
$api->api_request ('sendMessage', {
chat_id => 123456,
text => 'Oh, hai'
});
# file upload
$api->api_request ('sendDocument', {
chat_id => 123456,
document => {
filename => 'dump.txt',
content => 'secret stuff'
}
});
# complex objects are supported natively since v0.04
$api->api_request ('sendMessage', {
chat_id => 123456,
reply_markup => {
keyboard => [ [ 'Button 1', 'Button 2' ] ]
}
});
# with async => 1 and the IOLoop already started
$api->api_request ('getMe', sub {
my ($ua, $tx) = @_;
die if $tx->error;
# ...
});
This method performs an API request. The first argument must be the method name (here's a list
<https://core.telegram.org/bots/api#available-methods>).
Once the request is completed, the response is decoded using JSON::MaybeXS and then returned. If
Mojo::UserAgent is used as the user-agent, then the response is decoded automatically using Mojo::JSON.
If the request is not successful or the server tells us something isn't "ok", then this method dies with
the first available error message (either the error description or the status line). You can make this
method non-fatal using "eval":
my $response = eval { $api->api_request ($method, $args) }
or warn "Request failed with error '$@', but I'm still alive!";
Further processing of error messages can be obtained using "parse_error".
Request parameters can be specified using an hash reference. Additionally, complex objects can be
specified like you do in JSON. See the previous examples or the example bot provided in "SEE ALSO".
File uploads can be specified using an hash reference containing the following mappings:
• "file => '/path/to/file.ext'"
Path to the file you want to upload.
Required only if "content" is not specified.
• "filename => 'file_name.ext'"
An optional filename that will be used instead of the real name of the file.
Particularly recommended when "content" is specified.
• "content => 'Being a file is cool :-)'"
The content of the file to send. When using this, "file" must not be specified.
• "AnyCustom => 'Header'"
Custom headers can be specified as hash mappings.
Upload of multiple files is not supported. See "tx" in Mojo::UserAgent::Transactor for more information
about file uploads.
To resend files, you don't need to perform a file upload at all. Just pass the ID as a normal parameter.
$api->sendPhoto ({
chat_id => 123456,
photo => $photo_id
});
When asynchronous requests are enabled, a callback can be specified as an argument. The arguments passed
to the callback are, in order, the user-agent (a Mojo::UserAgent object) and the response (a
Mojo::Transaction::HTTP object). More information can be found in the documentation of Mojo::UserAgent
and Mojo::Transaction::HTTP.
NOTE: ensure that the event loop Mojo::IOLoop is started when using asynchronous requests. This is not
needed when using this module inside a Mojolicious app.
The order of the arguments, except of the first one, does not matter:
$api->api_request ('sendMessage', $parameters, $callback);
$api->api_request ('sendMessage', $callback, $parameters); # same thing!
parse_error
unless (eval { $api->doSomething(...) }) {
my $error = $api->parse_error;
die "Unknown error: $error->{msg}" if $error->{type} eq 'unknown';
# Handle error gracefully using "type", "msg" and "code" (optional)
}
# Or, use it with a custom error message.
my $error = $api->parse_error ($message);
When sandboxing calls to WWW::Telegram::BotAPI methods using "eval", it is useful to parse error messages
using this method.
WARNING: up until version 0.09, this method incorrectly stopped at the first occurence of "at" in error
messages, producing results such as "missing ch" instead of "missing chat".
This method accepts an error message as its first argument, otherwise $@ is used.
An hash reference containing the following elements is returned:
• "type => unknown|agent|api"
The source of the error.
"api" specifies an error originating from Telegram's BotAPI. When "type" is "api", the key "code" is
guaranteed to exist.
"agent" specifies an error originating from this module's user-agent. This may indicate a network
issue, a non-200 HTTP response code or any error not related to the API.
"unknown" specifies an error with no known source.
• "msg => ..."
The error message.
• "code => ..."
The error code. Thiskeyonlyexistswhen"type"is"api".
agent
my $user_agent = $api->agent;
Returns the instance of the user-agent used by the module. You can determine if the module is using
LWP::UserAgent or Mojo::UserAgent by using "isa":
my $is_lwp = $user_agent->isa ('LWP::UserAgent');
USINGAPROXY
Since all the painful networking stuff is delegated to one of the two supported user agents (either
LWP::UserAgent or Mojo::UserAgent), you can use their built-in support for proxies by accessing the user
agent object. An example of how this may look like is the following:
my $user_agent = $api->agent;
if ($user_agent->isa ('LWP::UserAgent')) {
# Use LWP::Protocol::connect (for https)
$user_agent->proxy ('https', '...');
# Or if you prefer, load proxy settings from the environment.
# $user_agent->env_proxy;
} else {
# Mojo::UserAgent (builtin)
$user_agent->proxy->https ('...');
# Or if you prefer, load proxy settings from the environment.
# $user_agent->detect;
}
NOTE: Unfortunately, Mojo::UserAgent returns an opaque "Proxy connection failed" when something goes
wrong with the "CONNECT" request made to the proxy. To alleviate this, since version 0.12, this module
prints the real reason of failure in debug mode. See "DEBUGGING". If you need to access the real error
reason in your code, please see issue #29 on GitHub <https://github.com/Robertof/perl-www-telegram-
botapi/issues/29>.