The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

Telegram::Bot::Brain - A base class to make your very own Telegram bot

VERSION

version 0.025

SYNOPSIS

  package MyApp::Coolbot;

  use Mojo::Base 'Telegram::Bot::Brain';

  has token       => 'token-you-got-from-@botfather';

  sub init {
      my $self = shift;
      $self->add_repeating_task(600, \&timed_task);
      $self->add_listener(\&respond_to_messages);
  }

Elsewhere....

  my $bot = MyApp::Coolbot->new();
  $bot->think;  # this will block unless there is already an event
                # loop running

DESCRIPTION

This base class makes it easy to create your own Bot classes that interface with the Telegram Bot API.

Internally it uses the Mojo::IOLoop event loop to provide non-blocking access to the Bot API, allowing your bot to listen for events via the longpoll getUpdates API method and also trigger timed events that can run without blocking.

As with any bot framework, the principle is that the framework allows you to interact with other users on Telegram. The Telegram API provides a rich set of typed objects. This framework will allow you to create those objects to send into the API (for instance, sending text messages, sending photos, and more) as well as call your code (via add_listener when your bot receives messages (which might be text, or images, and so on).

How bots work with Telegram is out of scope for this document, a good starting place is https://core.telegram.org/bots.

METHODS

add_repeating_task

This method will add a sub to run every $seconds seconds. Pass this method two parameters, the number of seconds between executions, and the coderef to execute.

Your coderef will be passed the Telegram::Bot::Brain object when it is executed.

add_listener

Respond to messages we receive. It takes a single argument, a coderef to execute for each update that is sent to us. These are *typically* Telegram::Bot:Object::Message objects, though that is not the only type of update that may be sent (see https://core.telegram.org/bots/api#update).

Multiple listeners can be added, they will receive the incoming update in the order that they are registered.

Any or all listeners can choose to ignore or take action on any particular update.

think

Start this bot thinking.

Calls your init method and then enters a blocking loop (unless a Mojo::IOLoop is already running).

getMe

This is the wrapper around the getMe API method. See https://core.telegram.org/bots/api#getme.

Takes no arguments, and returns the Telegram::Bot::Object::User that represents this bot.

sendMessage

See https://core.telegram.org/bots/api#sendmessage.

Returns a Telegram::Bot::Object::Message object.

forwardMessage

See https://core.telegram.org/bots/api#forwardmessage.

Returns a Telegram::Bot::Object::Message object.

deleteMessage

See https://core.telegram.org/bots/api#deletemessage.

Takes a hash $ags that contains exactly two keys:

chat_id

the id of the chat we want to delete the message from

message_id

the id of the message we want to delete

Returns true on success.

sendPhoto

See https://core.telegram.org/bots/api#sendphoto.

Returns a Telegram::Bot::Object::Message object.

SEE ALSO

Telegram Bot API methods

The following methods are relatively thin wrappers around the various methods available in the Telgram Bot API to send messages and perform other updates.

https://core.telegram.org/bots/api#available-methods

They all return immediately with the corresponding Telegram::Bot::Object subclass - consult the documenation for each below to see what to expect.

Note that not all methods have yet been implemented.

sendDocument

Send a file. See https://core.telegram.org/bots/api#sendDocument.

Takes two argument hashes $ags and $send_args. $args needs to contain two keys:

chat_id

the id of the chat we are writing to

document

a reference to a Mojo::Asset::Memory, internal Telegram file ID or a URL

$send_args can contain other arguments documented in Telegram's API docs.

Returns a Telegram::Bot::Object::Message object.

    sub file_sending_listener {
      my $self = shift;
      my $msg  = shift;

      my $string = "...";

      my $file = Mojo::Asset::Memory->new->add_chunk($string);
      $self->sendDocument(
        {    # args
          chat_id  => $msg->chat->id,
          document => { file => $file, filename => 'bot_export.csv' }
        },
        {}    # send_args
      );
    }

answerInlineQuery

Use this method to send answers to an inline query. On success, True is returned. No more than 50 results per query are allowed.

See https://core.telegram.org/bots/api#answerinlinequery.

Takes an argument hash $args with the following values.

inline_query_id

Required. Unique identifier for the answered query. You get that from the incoming Telegram::Bot::Object::InlineQuery.

results

Required. A JSON-serialized array of results for the inline query. You need to pass in a string of JSON.

See https://core.telegram.org/bots/api#inlinequeryresult for the format of the response.

cache_time

Optional. The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to 300.

is_personal

Optional. Pass True if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query.

next_offset

Optional. Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don't support pagination. Offset length can't exceed 64 bytes.

button

Optional. A JSON-serialized object describing a button to be shown above inline query results.

See "reply" in Telegram::Bot::Object::InlineQuery for a more convenient way to use this.

AUTHORS

  • Justin Hawkins <justin@eatmorecode.com>

  • James Green <jkg@earth.li>

  • Julien Fiegehenn <simbabque@cpan.org>

COPYRIGHT AND LICENSE

This software is copyright (c) 2023 by James Green.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.