Chloe  Butler

Chloe Butler

1667339400

Perl Implementation Of The Telegram Bot API

Name

WWW::Telegram::BotAPI - Perl implementation of the Telegram Bot API

Synopsis

use WWW::Telegram::BotAPI;
my $api = WWW::Telegram::BotAPI->new (
    token => 'my_token'
);
# The API methods die when an error occurs.
say $api->getMe->{result}{username};
# ... but error handling is available as well.
my $result = eval { $api->getMe }
    or die 'Got error message: ', $api->parse_error->{msg};
# Uploading files is easier than ever.
$api->sendPhoto ({
    chat_id => 123456,
    photo   => {
        file => '/home/me/cool_pic.png'
    },
    caption => 'Look at my cool photo!'
});
# Complex objects are as easy as writing a Perl object.
$api->sendMessage ({
    chat_id      => 123456,
    # Object: ReplyKeyboardMarkup
    reply_markup => {
        resize_keyboard => \1, # \1 = true when JSONified, \0 = false
        keyboard => [
            # Keyboard: row 1
            [
                # Keyboard: button 1
                'Hello world!',
                # Keyboard: button 2
                {
                    text => 'Give me your phone number!',
                    request_contact => \1
                }
            ]
        ]
    }
});
# Asynchronous request are supported with Mojo::UserAgent.
$api = WWW::Telegram::BotAPI->new (
    token => 'my_token',
    async => 1 # WARNING: may fail if Mojo::UserAgent is not available!
);
$api->sendMessage ({
    chat_id => 123456,
    text    => 'Hello world!'
}, sub {
    my ($ua, $tx) = @_;
    die 'Something bad happened!' if $tx->error;
    say $tx->res->json->{ok} ? 'YAY!' : ':('; # Not production ready!
});
Mojo::IOLoop->start;

Description

This module provides an easy to use interface for the Telegram Bot API. It also supports async requests out of the box using Mojo::UserAgent, which makes this module easy to integrate with an existing Mojolicious application.

Methods

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.

%options may contain the following:

token => 'my_token'

The token that will be used to authenticate the bot.

This is required! The method will croak if this option is not specified.

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.

This requires Mojo::UserAgent, and the method will croak if it isn't found.

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 every current and future method of the Telegram Bot API can be used by calling its Perl equivalent, 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).

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. This key only exists when 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');

Using a proxy

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.

Debugging

To perform some cool troubleshooting, you can set the environment variable TELEGRAM_BOTAPI_DEBUG to a true value:

TELEGRAM_BOTAPI_DEBUG=1 perl script.pl

This dumps the content of each request and response in a friendly, human-readable way. It also prints the version and the configuration of the module. As a security measure, the bot's token is automatically removed from the output of the dump.

Since version 0.12, enabling this flag also gives more details when a proxy connection fails.

WARNING: using this option along with an old Mojolicious version (< 6.22) leads to a warning, and forces LWP::UserAgent instead of Mojo::UserAgent. This is because Mojo::JSON used incompatible boolean values up to version 6.21, which led to an horrible death of JSON::MaybeXS when serializing the data.

Caveats

When asynchronous mode is enabled, no error handling is performed. You have to do it by yourself as shown in the "SYNOPSIS".

See also

LWP::UserAgent, Mojo::UserAgent, https://core.telegram.org/bots/api, https://core.telegram.org/bots, example implementation of a Telegram bot, example implementation of an async Telegram bot

Author

Roberto Frenna (robertof AT cpan DOT org)

Bugs

Please report any bugs or feature requests to https://github.com/Robertof/perl-www-telegram-botapi.

Thanks

Thanks to the authors of Mojolicious for inspiration about the license and the documentation.

License

Copyright (C) 2015, Roberto Frenna.

This program is free software, you can redistribute it and/or modify it under the terms of the Artistic License version 2.0.


Download Details:

Author: Robertof
Source Code: https://github.com/Robertof/perl-www-telegram-botapi

License: Artistic-2.0 license

#perl #telegram 

Perl Implementation Of The Telegram Bot API
Kevin  Simon

Kevin Simon

1667274344

Install the Telegram Desktop App in Linux Ubuntu Termina

Telegram is a hugely popular messaging client, especially for those interested in privacy. It’s easy to use and widely available for all platforms – Windows, macOS, Linux, Android, and iOS all have access to this platform, making it ideal for diverse teams of people. There are a few ways to get Telegram installed on your Linux desktop.

In this tutorial, we will learn how to install and use telegram desktop app in linux ubuntu system using terminal. To install and use telegram desktop application in linux ubuntu system using terminal we follow these two steps

  • Step 1 : Update System Dependencies
  • Step 2 : Install Telegram on Ubuntu

Step 1 : Update System Dependencies

Execute the following command on command prompt to update or upgrade linux ubuntu system dependencies:

sudo apt update

sudo apt upgrade

Step 2 : Install Telegram on Ubuntu

Execute the following command on command prompt to install telegram desktop messenger app in linux ubuntu system:

sudo apt install telegram-desktop

After that, wait few minutes.

Then, Enter “y” to permit the process to complete the Telegram installation on system.

#linux  #ubuntu #telegram 

Roff Bot: A Bot for A Rust-offtopic Chat in The Telegram

Roff-bot

This is a bot for a rust-offtopic chat in the Telegram.

Bot usage

This section describes features available in the bot.

Structural warnings

Structural warnings is a flexible system of warnings allow you to describe conditions upon which user must be warned and punishments.

Warnings are divided into a groups, these groups do not intersect each other. You can set up any group any time.

Under a group there are score point panel. When score point panel is full, punishment follows.

TODO: add time limit for warnings. TODO: progressive time for recidivists.

Punishments

There are few types of punishments:

  1. Ban. User was removed from the chat for a time or forever.
  2. Mute. User cannot send messages for a time or forever.
  3. Restrict. User cannot send specific kinds of messages for a time or forever.

Set up warning group

TODO

.gitignore

/target
.idea

Cargo.toml

[package]
name = "autowarn_bot"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
teloxide = { git = "https://github.com/teloxide/teloxide", branch = "dispatching2", features = ["macros", "trace-adaptor"] }
serde = "1.0.133"
mongodb = "2.0.2"
tokio = "1.15.0"
log = "0.4.14"
pretty_env_logger = "0.4.0"
anyhow = "1.0.52"
chrono = "0.4.19"

Download Details:

Author: p0lunin
Source Code: https://github.com/p0lunin/autowarn_bot

#rust #telegram 

Roff Bot: A Bot for A Rust-offtopic Chat in The Telegram
Jack  Shaw

Jack Shaw

1666434501

PartitelleBot: An Italian Telegram Bot in Python

PartitelleBot

PartitelleBot is an Italian Telegram Bot in Python to retrieve participants for the organization of a football game.

Architecture

This is a Python project relying on python-telegram-bot library. Data storage is handled through PostgreSQL. The application and the mentioned database are both hosted on Heroku.

Project structure

  • database.ini: a configuration file with database credentials (obscured from this repo for security reasons)
  • config.py: a little function to parse and read database credentials in database.ini
  • Procfile: a file for Heroku's pipelines of deployment to know where to take Python code.
  • requirements.txt: a file to indicate Heroku which external libraries are necessary to the Python code.
  • main.py: the real heart of PartitelleBot code

Behaviour

Presentation message

 

By adding PartitelleBot to your Telegram group, you can easily manage those so-hard-to-organize weekly football matches with your friends. You have two ways of interacting with the bot:

  1. by writing a specific set of allowed messages through the conversation
  2. by using standard commands

By default, the bot sets all new matches the next Wednesday at 9 pm but this information is, of course, editable. Once a new match is created through /start command, people can begin to organize the match through the set of allowed messages. The first time the bot detects an adding interaction, it will print a match summary of the current situation whereas from the second time it will edit its previous message (by the way remind that a new explicit summary can be obtained through /participants command). In this way, people can easily and autonomously add, propose, and remove themselves or each other. Once the target number is reached, users enter the final phase; here, the bot states that is the time to play and asks permission to generate /teams. Through this command, the bot randomly generates two groups of players, respectively the black team and the white team. At this point, users can always adjust the teams by swapping players.

Note: if you give PartitelleBot the administrator rights, it will be able to pin its messages in the group.

Match summary

Match summary

 

In my organizational experience, one of the most annoying tasks is to keep on copying and pasting the same list over and over again each time a new update over participants turns out. This summary aims to change this pattern and let the bot do the dirty work. This message has a specific structure:

GIORNO: <day> | <time>

<participants list from 1 to N

  • added player ✅
  • added player ✅
  • proposed player ❓
  • ...
  • free slot ❌

where N is the target number>

<description>

CAMPO: <pitch>

Final phase

Final phase

 

Swapping players

Swap

 

Allowed messages

This is the list of current available allowed messages to interact with the bot:

  • proponimi - you want to be added to the list but you are not 100% sure to be present
  • proponi <nome> - you propose someone else who may participate
  • aggiungimi - you want to be added or confirmed to the list of participants
  • aggiungi <nome> - you add someone to the list or someone who had been previously proposed
  • toglimi - you remove yourself from the list in any case
  • togli <nome> - you remove someone else from the list in any case
  • scambia <nome 1> con <nome 2> - you swap two players to balance the teams generated by the bot

Commands

This is the list of current available commands:

  • /start - Create new match
  • /setnumber - Set the number of participants
  • /setday - Set the day of the match
  • /settime - Set the time of the match
  • /setdescription - Set the custom message under the list of participants
  • /setpitch - Set the football pitch
  • /participants - Show the participants of the current match
  • /teams - Show the generated teams for the current match
  • /stop - Remove the match
  • /help - Show the list of available commands

Download Details:

Author: iamgiolaga
Source Code: https://github.com/iamgiolaga/partitelle-bot

License: GPL-3.0 license

#python #telegram 

PartitelleBot: An Italian Telegram Bot in Python
Daniel  Hughes

Daniel Hughes

1666396020

A Chatbot on Telegram using Technologies Of Cloud Computing

Chatbot

This project is about a chatbot on Telegram to study the cloud computing. You can refer to the project of chatbot-deploy which is conveinent for the environment of development and deployment. You can refer to an instruction for bots on Telegram to learn about how to create a bot and more.

An example of chatbot on Telegram

telegram-bot

Initialize Database

You can find sql files under the directory of db to initialize the database.

Create a file config.ini under the root directory

[postgresql]
host=
database=
user=
password=

[telegram]
access_token=

How to run

Run python directly, in Terminal

pip install -r requirements.txt

python chatbot.py

Run docker command to test chatbot image before pushing code

docker build -t chatbot:test .

docker run -it --rm -v "$(pwd)/config.ini:/app/config.ini"  --name test_chatbot chatbot:test

Run the script to test chatbot image before pushing code

./docker-test.sh

Run docker by using the remote chatbot image

You can view the remote chatbot image from dockerjeffery/chatbot.

docker run -it --rm -v "$(pwd)/config.ini:/app/config.ini"  --name test_chatbot dockerjeffery/chatbot

Download Details:

Author: JianFengH
Source Code: https://github.com/JianFengH/chatbot

License: Apache-2.0 license

#telegram #chatbot 

A Chatbot on Telegram using Technologies Of Cloud Computing

Core: PHP Telegram Bot Based on The Official Telegram Bot API

PHP Telegram Bot

A Telegram Bot based on the official Telegram Bot API

Introduction

This is a pure PHP Telegram Bot, fully extensible via plugins.

Telegram announced official support for a Bot API, allowing integrators of all sorts to bring automated interactions to the mobile platform. This Bot aims to provide a platform where one can simply write a bot and have interactions in a matter of minutes.

The Bot can:

  • Retrieve updates with webhook and getUpdates methods.
  • Supports all types and methods according to Telegram Bot API 6.2 (August 2022).
  • Supports supergroups.
  • Handle commands in chat with other bots.
  • Manage Channel from the bot admin interface.
  • Full support for inline bots.
  • Inline keyboard.
  • Messages, InlineQuery and ChosenInlineQuery are stored in the Database.
  • Conversation feature.

This code is available on GitHub. Pull requests are welcome.

Instructions

Create your first bot

Message @BotFather with the following text: /newbot

If you don't know how to message by username, click the search field on your Telegram app and type @BotFather, where you should be able to initiate a conversation. Be careful not to send it to the wrong contact, because some users have similar usernames to BotFather.

BotFather initial conversation

@BotFather replies with:

Alright, a new bot. How are we going to call it? Please choose a name for your bot.

Type whatever name you want for your bot.

@BotFather replies with:

Good. Now let's choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or tetris_bot.

Type whatever username you want for your bot, minimum 5 characters, and must end with bot. For example: telesample_bot

@BotFather replies with:

Done! Congratulations on your new bot. You will find it at
telegram.me/telesample_bot. You can now add a description, about
section and profile picture for your bot, see /help for a list of
commands.

Use this token to access the HTTP API:
123456789:AAG90e14-0f8-40183D-18491dDE

For a description of the Bot API, see this page:
https://core.telegram.org/bots/api

Note down the 'token' mentioned above.

Optionally set the bot privacy:

Send /setprivacy to @BotFather.

BotFather later conversation

@BotFather replies with:

Choose a bot to change group messages settings.

Type (or select) @telesample_bot (change to the username you set at step 5 above, but start it with @)

@BotFather replies with:

'Enable' - your bot will only receive messages that either start with the '/' symbol or mention the bot by username.
'Disable' - your bot will receive all messages that people send to groups.
Current status is: ENABLED

Type (or select) Disable to let your bot receive all messages sent to a group.

@BotFather replies with:

Success! The new status is: DISABLED. /help

Require this package with Composer

Install this package through Composer. Edit your project's composer.json file to require longman/telegram-bot.

Create composer.json file

{
    "name": "yourproject/yourproject",
    "type": "project",
    "require": {
        "php": ">=7.3",
        "longman/telegram-bot": "*"
    }
}

and run composer update

or

run this command in your command line:

composer require longman/telegram-bot

Choose how to retrieve Telegram updates

The bot can handle updates with Webhook or getUpdates method:

 WebhookgetUpdates
DescriptionTelegram sends the updates directly to your hostYou have to fetch Telegram updates manually
Host with httpsRequiredNot required
MySQLNot required(Not) Required

Using a custom Bot API server

For advanced users only!

As from Telegram Bot API 5.0, users can run their own Bot API server to handle updates. This means, that the PHP Telegram Bot needs to be configured to serve that custom URI. Additionally, you can define the URI where uploaded files to the bot can be downloaded (note the {API_KEY} placeholder).

Longman\TelegramBot\Request::setCustomBotApiUri(
    $api_base_uri          = 'https://your-bot-api-server', // Default: https://api.telegram.org
    $api_base_download_uri = '/path/to/files/{API_KEY}'     // Default: /file/bot{API_KEY}
);

Note: If you are running your bot in --local mode, you won't need the Request::downloadFile() method, since you can then access your files directly from the absolute path returned by Request::getFile().

Webhook installation

Note: For a more detailed explanation, head over to the example-bot repository and follow the instructions there.

In order to set a Webhook you need a server with HTTPS and composer support. (For a self signed certificate you need to add some extra code)

Create set.php with the following contents:

<?php
// Load composer
require __DIR__ . '/vendor/autoload.php';

$bot_api_key  = 'your:bot_api_key';
$bot_username = 'username_bot';
$hook_url     = 'https://your-domain/path/to/hook.php';

try {
    // Create Telegram API object
    $telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username);

    // Set webhook
    $result = $telegram->setWebhook($hook_url);
    if ($result->isOk()) {
        echo $result->getDescription();
    }
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
    // log telegram errors
    // echo $e->getMessage();
}

Open your set.php via the browser to register the webhook with Telegram. You should see Webhook was set.

Now, create hook.php with the following contents:

<?php
// Load composer
require __DIR__ . '/vendor/autoload.php';

$bot_api_key  = 'your:bot_api_key';
$bot_username = 'username_bot';

try {
    // Create Telegram API object
    $telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username);

    // Handle telegram webhook request
    $telegram->handle();
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
    // Silence is golden!
    // log telegram errors
    // echo $e->getMessage();
}

Self Signed Certificate

Upload the certificate and add the path as a parameter in set.php:

$result = $telegram->setWebhook($hook_url, ['certificate' => '/path/to/certificate']);

Unset Webhook

Edit unset.php with your bot credentials and execute it.

getUpdates installation

For best performance, the MySQL database should be enabled for the getUpdates method!

Create getUpdatesCLI.php with the following contents:

#!/usr/bin/env php
<?php
require __DIR__ . '/vendor/autoload.php';

$bot_api_key  = 'your:bot_api_key';
$bot_username = 'username_bot';

$mysql_credentials = [
   'host'     => 'localhost',
   'port'     => 3306, // optional
   'user'     => 'dbuser',
   'password' => 'dbpass',
   'database' => 'dbname',
];

try {
    // Create Telegram API object
    $telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username);

    // Enable MySQL
    $telegram->enableMySql($mysql_credentials);

    // Handle telegram getUpdates request
    $telegram->handleGetUpdates();
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
    // log telegram errors
    // echo $e->getMessage();
}

Next, give the file permission to execute:

$ chmod +x getUpdatesCLI.php

Lastly, run it!

$ ./getUpdatesCLI.php

getUpdates without database

If you choose to / or are obliged to use the getUpdates method without a database, you can replace the $telegram->useMySQL(...); line above with:

$telegram->useGetUpdatesWithoutDatabase();

Filter Update

:exclamation: Note that by default, Telegram will send any new update types that may be added in the future. This may cause commands that don't take this into account to break!

It is suggested that you specifically define which update types your bot can receive and handle correctly.

You can define which update types are sent to your bot by defining them when setting the webhook or passing an array of allowed types when using getUpdates.

use Longman\TelegramBot\Entities\Update;

// For all update types currently implemented in this library:
// $allowed_updates = Update::getUpdateTypes();

// Define the list of allowed Update types manually:
$allowed_updates = [
    Update::TYPE_MESSAGE,
    Update::TYPE_CHANNEL_POST,
    // etc.
];

// When setting the webhook.
$telegram->setWebhook($hook_url, ['allowed_updates' => $allowed_updates]);

// When handling the getUpdates method.
$telegram->handleGetUpdates(['allowed_updates' => $allowed_updates]);

Alternatively, Update processing can be allowed or denied by defining a custom update filter.

Let's say we only want to allow messages from a user with ID 428, we can do the following before handling the request:

$telegram->setUpdateFilter(function (Update $update, Telegram $telegram, &$reason = 'Update denied by update_filter') {
    $user_id = $update->getMessage()->getFrom()->getId();
    if ($user_id === 428) {
        return true;
    }

    $reason = "Invalid user with ID {$user_id}";
    return false;
});

The reason for denying an update can be defined with the $reason parameter. This text gets written to the debug log.

Support

Types

All types are implemented according to Telegram API 6.2 (August 2022).

Inline Query

Full support for inline query according to Telegram API 6.2 (August 2022).

Methods

All methods are implemented according to Telegram API 6.2 (August 2022).

Send Message

Messages longer than 4096 characters are split up into multiple messages.

$result = Request::sendMessage([
    'chat_id' => $chat_id,
    'text'    => 'Your utf8 text 😜 ...',
]);

Send Photo

To send a local photo, add it properly to the $data parameter using the file path:

$result = Request::sendPhoto([
    'chat_id' => $chat_id,
    'photo'   => Request::encodeFile('/path/to/pic.jpg'),
]);

If you know the file_id of a previously uploaded file, just use it directly in the data array:

$result = Request::sendPhoto([
    'chat_id' => $chat_id,
    'photo'   => 'AAQCCBNtIhAoAAss4tLEZ3x6HzqVAAqC',
]);

To send a remote photo, use the direct URL instead:

$result = Request::sendPhoto([
    'chat_id' => $chat_id,
    'photo'   => 'https://example.com/path/to/pic.jpg',
]);

sendAudio, sendDocument, sendAnimation, sendSticker, sendVideo, sendVoice and sendVideoNote all work in the same way, just check the API documentation for the exact usage. See the ImageCommand.php for a full example.

Send Chat Action

Request::sendChatAction([
    'chat_id' => $chat_id,
    'action'  => Longman\TelegramBot\ChatAction::TYPING,
]);

getUserProfilePhoto

Retrieve the user photo. (see WhoamiCommand.php for a full example)

getFile and downloadFile

Get the file path and download it. (see WhoamiCommand.php for a full example)

Send message to all active chats

To do this you have to enable the MySQL connection. Here's an example of use (check DB::selectChats() for parameter usage):

$results = Request::sendToActiveChats(
    'sendMessage', // Callback function to execute (see Request.php methods)
    ['text' => 'Hey! Check out the new features!!'], // Param to evaluate the request
    [
        'groups'      => true,
        'supergroups' => true,
        'channels'    => false,
        'users'       => true,
    ]
);

You can also broadcast a message to users, from the private chat with your bot. Take a look at the admin commands below.

Utils

MySQL storage (Recommended)

If you want to save messages/users/chats for further usage in commands, create a new database (utf8mb4_unicode_520_ci), import structure.sql and enable MySQL support BEFORE handle() method:

$mysql_credentials = [
   'host'     => 'localhost',
   'port'     => 3306, // optional
   'user'     => 'dbuser',
   'password' => 'dbpass',
   'database' => 'dbname',
];

$telegram->enableMySql($mysql_credentials);

You can set a custom prefix to all the tables while you are enabling MySQL:

$telegram->enableMySql($mysql_credentials, $bot_username . '_');

You can also store inline query and chosen inline query data in the database.

External Database connection

It is possible to provide the library with an external MySQL PDO connection. Here's how to configure it:

$telegram->enableExternalMySql($external_pdo_connection);
//$telegram->enableExternalMySql($external_pdo_connection, $table_prefix)

Channels Support

All methods implemented can be used to manage channels. With admin commands you can manage your channels directly with your bot private chat.

Commands

Predefined Commands

The bot is able to recognise commands in a chat with multiple bots (/command@mybot).

It can also execute commands that get triggered by events, so-called Service Messages.

Custom Commands

Maybe you would like to develop your own commands. There is a guide to help you create your own commands.

Also, be sure to have a look at the example commands to learn more about custom commands and how they work.

You can add your custom commands in different ways:

// Add a folder that contains command files
$telegram->addCommandsPath('/path/to/command/files');
//$telegram->addCommandsPaths(['/path/to/command/files', '/another/path']);

// Add a command directly using the class name
$telegram->addCommandClass(MyCommand::class);
//$telegram->addCommandClasses([MyCommand::class, MyOtherCommand::class]);

Commands Configuration

With this method you can set some command specific parameters, for example:

// Google geocode/timezone API key for /date command
$telegram->setCommandConfig('date', [
    'google_api_key' => 'your_google_api_key_here',
]);

// OpenWeatherMap API key for /weather command
$telegram->setCommandConfig('weather', [
    'owm_api_key' => 'your_owm_api_key_here',
]);

Admin Commands

Enabling this feature, the bot admin can perform some super user commands like:

  • List all the chats started with the bot /chats
  • Clean up old database entries /cleanup
  • Show debug information about the bot /debug
  • Send message to all chats /sendtoall
  • Post any content to your channels /sendtochannel
  • Inspect a user or a chat with /whois

Take a look at all default admin commands stored in the src/Commands/AdminCommands/ folder.

Set Admins

You can specify one or more admins with this option:

// Single admin
$telegram->enableAdmin(your_telegram_user_id);

// Multiple admins
$telegram->enableAdmins([
    your_telegram_user_id,
    other_telegram_user_id,
]);

Telegram user id can be retrieved with the /whoami command.

Channel Administration

To enable this feature follow these steps:

  • Add your bot as channel administrator, this can be done with any Telegram client.
  • Enable admin interface for your user as explained in the admin section above.
  • Enter your channel name as a parameter for the /sendtochannel command:
$telegram->setCommandConfig('sendtochannel', [
    'your_channel' => [
        '@type_here_your_channel',
    ]
]);
  • If you want to manage more channels:
$telegram->setCommandConfig('sendtochannel', [
    'your_channel' => [
        '@type_here_your_channel',
        '@type_here_another_channel',
        '@and_so_on',
    ]
]);
  • Enjoy!

Upload and Download directory path

To use the Upload and Download functionality, you need to set the paths with:

$telegram->setDownloadPath('/your/path/Download');
$telegram->setUploadPath('/your/path/Upload');

Documentation

Take a look at the repo Wiki for further information and tutorials! Feel free to improve!

Assets

All project assets can be found in the assets repository.

Example bot

We're busy working on a full A-Z example bot, to help get you started with this library and to show you how to use all its features. You can check the progress of the example-bot repository).

Projects with this library

Here's a list of projects that feats this library, feel free to add yours!

Troubleshooting

If you like living on the edge, please report any bugs you find on the PHP Telegram Bot issues page.

Contributing

See CONTRIBUTING for more information.

Security

See SECURITY for more information.

For enterprise

Available as part of the Tidelift Subscription.

The maintainers of PHP Telegram Bot and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

Credits

Credit list in CREDITS


Download Details:

Author: php-telegram-bot
Source Code: https://github.com/php-telegram-bot/core 
License: MIT license

#php #telegram #bot #sdk 

Core: PHP Telegram Bot Based on The Official Telegram Bot API
Rupert  Beatty

Rupert Beatty

1666089074

Advanced Usage Of UIAlertController & Pickers Based on It: Telegram

Alerts & Pickers

Advanced usage of native UIAlertController with TextField, TextView, DatePicker, PickerView, TableView, CollectionView and MapView.

Features

  •  Custom pickers based on UITextField, UITextView, UIDatePicker, UIPickerView, UITableView, UICollectionView and MKMapView.
  •  Example using a Storyboard.
  •  Easy contentViewController placement.
  •  Attributed title label and message label.
  •  Button customization: image and title color.
  •  Understandable action button placement.
  •  Easy presentation.
  • Pure Swift 4.

actionSheet-.gif 

Usage

actionSheet-simple.gif alert-simple.gif

  • New Alert
let alert = UIAlertController(style: .alert, title: "Title", message: "Message")
// or
let alert = UIAlertController(style: .alert)
  • Set and styling title
alert.set(title: "Title", font: .systemFont(ofSize: 20), color: .black)
// or
alert.setTitle(font: .systemFont(ofSize: 20), color: .black)
  • Set and styling message
alert.set(message: "Message", font: .systemFont(ofSize: 16), color: .black)
// or
alert.setMessage(font: .systemFont(ofSize: 16), color: .black)
  • Add button with image
alert.addAction(image: image, title: "Title", color: .black, style: .default) { action in
    // completion handler
}
  • Show Alert
// show alert
alert.show()

// or show alert with options
alert.show(animated: true, vibrate: true) {
    // completion handler
}

actionSheet-simple-image.gif alert-simple-image.gif

Set Content ViewController

When setting your own custom UIViewController into UIAlertController keep in mind to set prefferedContentSize.height of the controller otherwise it will no effect. You can not set prefferedContentSize.width.

let alert = UIAlertController(style: .alert, title: "Title")
let vc = CustomViewController()
vc.preferredContentSize.height = height
alert.setValue(vc, forKey: "contentViewController")
alert.show()

// or
let alert = UIAlertController(style: .alert, title: "Title")
let vc = CustomViewController()
alert.set(vc: vc, height: height)
alert.show()

Pickers

For UX better to use .actionSheet style in UIAlertController when set picker into contentViewController. If you like you can use .alert style as well, buy .actionSheet style is wider and User can see more as well as action button is placing at bottom that also more convenience for User to touch it.

UITextField In native UIAlertController you can only add UITextField to .alert style with default style and you can not change such properties as .borderColor, .borderWidth, .frame.size and so on. But if you make your own UIViewController with UITextField, it will solve all these problems.

One TextField Picker

You can use both styles .alert and .actionSheet of UIAlertController.

 alert-textField-1.gif

let alert = UIAlertController(style: self.alertStyle, title: "TextField")                  
let config: TextField.Config = { textField in
    textField.becomeFirstResponder()
    textField.textColor = .black
    textField.placeholder = "Type something"
    textField.left(image: image, color: .black)
    textField.leftViewPadding = 12
    textField.borderWidth = 1
    textField.cornerRadius = 8
    textField.borderColor = UIColor.lightGray.withAlphaComponent(0.5)
    textField.backgroundColor = nil
    textField.keyboardAppearance = .default
    textField.keyboardType = .default
    textField.isSecureTextEntry = true
    textField.returnKeyType = .done
    textField.action { textField in
        // validation and so on
    }
}              
alert.addOneTextField(configuration: config)
alert.addAction(title: "OK", style: .cancel)
alert.show()

Two TextFields Picker

You can use both styles .alert and .actionSheet of UIAlertController.

actionSheet-textField-2.gif

let alert = UIAlertController(style: .alert, title: "Login")

let configOne: TextField.Config = { textField in
    textField.left(image: user), color: .black)
    textField.leftViewPadding = 16
    textField.leftTextPadding = 12
    textField.becomeFirstResponder()
    textField.backgroundColor = nil
    textField.textColor = .black
    textField.placeholder = "Name"
    textField.clearButtonMode = .whileEditing
    textField.keyboardAppearance = .default
    textField.keyboardType = .default
    textField.returnKeyType = .done
    textField.action { textField in
        // action with input
    }
}

let configTwo: TextField.Config = { textField in
    textField.textColor = .black
    textField.placeholder = "Password"
    textField.left(image: lock, color: .black)
    textField.leftViewPadding = 16
    textField.leftTextPadding = 12
    textField.borderWidth = 1
    textField.borderColor = UIColor.lightGray.withAlphaComponent(0.5)
    textField.backgroundColor = nil
    textField.clearsOnBeginEditing = true
    textField.keyboardAppearance = .default
    textField.keyboardType = .default
    textField.isSecureTextEntry = true
    textField.returnKeyType = .done
    textField.action { textField in
        // action with input
    }
}
// vInset - is top and bottom margin of two textFields   
alert.addTwoTextFields(vInset: 12, textFieldOne: configOne, textFieldTwo: configTwo)
alert.addAction(title: "OK", style: .cancel)
alert.show()

DatePicker

UIDatePicker does not look very much in .alert style.

 

let alert = UIAlertController(style: .actionSheet, title: "Select date") alert.addDatePicker(mode: .dateAndTime, date: date, minimumDate: minDate, maximumDate: maxDate) { date in    // action with selected date } alert.addAction(title: "OK", style: .cancel) alert.show()

PickerView

Example how to use UIPickerView as contentViewController and change height of the UIAlertController.

 

let alert = UIAlertController(style: .actionSheet, title: "Picker View", message: "Preferred Content Height") let frameSizes: [CGFloat] = (150...400).map { CGFloat($0) } let pickerViewValues: [[String]] = [frameSizes.map { Int($0).description }] let pickerViewSelectedValue: PickerViewViewController.Index = (column: 0, row: frameSizes.index(of: 216) ?? 0) alert.addPickerView(values: pickerViewValues, initialSelection: pickerViewSelectedValue) { vc, picker, index, values in    DispatchQueue.main.async {        UIView.animate(withDuration: 1) {            vc.preferredContentSize.height = frameSizes[index.row]        }    } } alert.addAction(title: "Done", style: .cancel) alert.show()

Locale Pickers

Country Picker

 

let alert = UIAlertController(style: .actionSheet, message: "Select Country") alert.addLocalePicker(type: .country) { info in    // action with selected object } alert.addAction(title: "OK", style: .cancel) alert.show()

Phone Code Picker

 

let alert = UIAlertController(style: .actionSheet, title: "Phone Codes") alert.addLocalePicker(type: .phoneCode) { info in    // action with selected object } alert.addAction(title: "OK", style: .cancel) alert.show()

Currency Picker

 

let alert = UIAlertController(style: .actionSheet, title: "Currencies") alert.addLocalePicker(type: .currency) { info in    alert.title = info?.currencyCode    alert.message = "is selected"    // action with selected object } alert.addAction(title: "OK", style: .cancel) alert.show()

Image Picker

 

  • Horizontal Image Picker with paging and single selection:

let alert = UIAlertController(style: .actionSheet) let photos: [UIImage] = images alert.addImagePicker(    flow: .horizontal,    paging: true,    images: photos,    selection: .single(action: { [unowned self] image in        // action with selected image    })) alert.addAction(title: "OK", style: .cancel) alert.show()

  • Vertical Image Picker w/o paging and with multiple selection:

let alert = UIAlertController(style: .actionSheet) let photos: [UIImage] = images alert.addImagePicker(    flow: .vertical,    paging: false,    height: UIScreen.main.bounds.height,    images: photos,    selection: .multiple(action: { [unowned self] images in        // action with selected images    })) alert.addAction(title: "OK", style: .cancel) alert.show()

PhotoLibrary Picker

 

let alert = UIAlertController(style: .actionSheet) alert.addPhotoLibraryPicker(    flow: .horizontal,    paging: true,    selection: .single(action: { image in        // action with selected image    })) alert.addAction(title: "Cancel", style: .cancel) alert.show()

ColorPicker

Example how to use UIViewController instantiated from Storyboard with Autolayout as contentViewController in the UIAlertController.

 

let alert = UIAlertController(style: .actionSheet) alert.addColorPicker(color: color) { color in    // action with selected color } alert.addAction(title: "Done", style: .cancel) alert.show()

Contacts Picker

 

let alert = UIAlertController(style: .actionSheet) alert.addContactsPicker { contact in    // action with contact } alert.addAction(title: "Cancel", style: .cancel) alert.show()

Location Picker

 

let alert = UIAlertController(style: .actionSheet) alert.addLocationPicker { location in    // action with location } alert.addAction(title: "Cancel", style: .cancel) alert.show()

Telegram Picker

 

let alert = UIAlertController(style: .actionSheet) alert.addTelegramPicker { result in    switch result {      case .photo(let assets):        // action with assets      case .contact(let contact):        // action with contact      case .location(let location):        // action with location    } } alert.addAction(title: "Cancel", style: .cancel) alert.show()

TextViewer

 

let alert = UIAlertController(style: .actionSheet) alert.addTextViewer(text: .attributedText(text)) alert.addAction(title: "OK", style: .cancel) alert.show()

Alerts vs. Action Sheets

There are some things to keep in mind when using .actionSheet and .alert styles:

  • Pickers better to use in .actionSheet style.
  • UITextField can be used in both styles.

Installing

Manually

Download and drop /Source folder in your project.

Requirements

  • Swift 4
  • iOS 11 or higher

Communication

  • If you found a bug, open an issue.
  • If you have a feature request, open an issue.
  • If you want to contribute, submit a pull request.

Download Details:

Author: Dillidon
Source Code: https://github.com/dillidon/alerts-and-pickers 
License: MIT license

#swift #map #telegram #login #contact 

Advanced Usage Of UIAlertController & Pickers Based on It: Telegram
Lenna  Kihn

Lenna Kihn

1666063380

Autogenerated Wrapper for The Telegram Bot API Written in Rust

An Elegant Rust Client for Telegram Bot API

Introduction

FerrisGram is an asynchronous autogenerated wrapper for the Telegram Bot API written in Rust. This library provides all the methods and types that are available on the official Telegram Bot API.

Key Features

  • Easy to use: Heavily inspired by the python-telegram-bot, Ferrisgram is designed in such a way that even a beginner can make a bot with it easily.
  • Asynchronous: Ferrisgram is powered by rust's built-in await async syntax.
  • Typo Free Docs: Autogenerated documentations of the native Bot API types and methods make it typo free.
  • Filters: Ferrisgram provides filters to make it easy for you to sort different type of updates in a managed way.

Installation

You can install ferrisgram by adding the following to dependencies section of Cargo.toml:

[dependencies]
ferrisgram = "0.1.5"

Getting Started

You can checkout our sample bots in the examples directory.

Documentation

Documentations can be found at docs.rs.

Index

.gitignore

# basic build and cargo files
target/
*.exe
Cargo.lock

# generator
generator/src
generator/Cargo.lock

# test example
examples/test.rs

Cargo.toml

[package]
name = "ferrisgram"
version = "0.1.5"
edition = "2021"
description = "An elegent rust client for the Telegram Bot API."
homepage = "https://github.com/ferrisgram"
repository = "https://github.com/ferrisgram/ferrisgram"
documentation = "https://docs.rs/ferrisgram"
readme = "README.md"
license = "MIT"
keywords = ["telegram", "bot-api", "bot"]
categories = ["api-bindings", "asynchronous"]
include = ["/src", "/examples"]

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
reqwest = { version = "0.11", features = ["blocking", "json"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1.0.114", features = ["derive"] }
serde_json = "1.0"
async-trait = "0.1.50"
dyn-clone = "1.0.4"

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update examples as appropriate.


Download Details:

Author: ferrisgram
Source Code: https://github.com/ferrisgram/ferrisgram

License: MIT license

#rust #telegram 

Autogenerated Wrapper for The Telegram Bot API Written in Rust
Python  Library

Python Library

1662671460

Telegeo: A Python Package for Scraping Telegram Based on Geolocation

telegeo

This is a python package for scraping Telegram:iphone: based on geolocation.

Installing

pip install telegeo

Dependencies:

(If nothing odd happens, users will install all the following dependencies of telegeo automatically after running "pip install telegeo"):
pandas
geopy
plotly
tqdm
telethon

How to use

step1: import telegeo

from telegeo import telegeo

step2: generating all coordinates within the specified latitude and longitude range.
use the map_range() fucntion in telegeo to generate the coordinates you need.

users should provide the following parameters⬇
lat_max: max latitude of the map range.
lon_max: max longitude of the map range.
lat_min: min latitude of the map range.
lon_min: min longitude of the map range.
distance: the distance between two coordinates on the map.
save_path: the path and filename for saving a csv file, which records all the coordinates.
(see Figure 1 for the first 5 parameters)

Example:
Move every 500 meters to generate all coordinates covering Hong Kong. And, save as csv.

telegeo.map_range(22.560100,114.404948,22.155232,113.835564,0.5,'geo_range_hk_r500.csv')

step3: generate a interactive map for displaying and checking the coordinates on a world map.
use the map_show() function in telegeo to create the map based on the above csv file.

telegeo.map_show('geo_range_hk_r500.csv')

Figure 2

More tutorial: To Be Continued...

Download details:

Author: Jacobzwj
Source code: https://github.com/Jacobzwj/telegeo 
License: MIT license

#python #telegram

Telegeo: A Python Package for Scraping Telegram Based on Geolocation
Michael Bryan

Michael Bryan

1660295282

How to Install the Telegram Desktop App in Linux Ubuntu

How to Install the Telegram Desktop App in Linux Ubuntu 

In this guide, we will learn how to install and use telegram desktop app in linux ubuntu system using terminal. Follow the following steps to install and use the telegram desktop app in Linux ubuntu using terminal:

  • Update System Dependencies
  • Install Telegram on Ubuntu

1 :Update System Dependencies

Execute the following command on command prompt to update or upgrade linux ubuntu system dependencies:

sudo apt update

sudo apt upgrade

2 – Install Telegram on Ubuntu

Execute the following command on command prompt to install telegram desktop messenger app in linux ubuntu system:

sudo apt install telegram-desktop

Then, Enter “y” to permit the process to complete the Telegram installation on system.

How to Install Telegram in Linux Ubuntu with Video Tutorial

Learn to install telegram desktop application in Linux ubuntu.

Telegram Desktop Application: https://desktop.telegram.org/ 

#ubuntu #telegram 

How to Install the Telegram Desktop App in Linux Ubuntu
Royce  Reinger

Royce Reinger

1658496240

Telegram-bot-ruby: Ruby Wrapper for Telegram's Bot API

Telegram-bot-ruby

Ruby wrapper for Telegram's Bot API

Installation

Add following line to your Gemfile:

gem 'telegram-bot-ruby'

And then execute:

$ bundle

Or install it system-wide:

$ gem install telegram-bot-ruby

Usage

First things first, you need to obtain a token for your bot. Then create your Telegram bot like this:

require 'telegram/bot'

token = 'YOUR_TELEGRAM_BOT_API_TOKEN'

Telegram::Bot::Client.run(token) do |bot|
  bot.listen do |message|
    case message.text
    when '/start'
      bot.api.send_message(chat_id: message.chat.id, text: "Hello, #{message.from.first_name}")
    when '/stop'
      bot.api.send_message(chat_id: message.chat.id, text: "Bye, #{message.from.first_name}")
    end
  end
end

Note that bot.api object implements Telegram Bot API methods as is. So you can invoke any method inside the block without any problems. All methods are available in both snake_case and camelCase notations.

Same thing about message object - it implements Message spec, so you always know what to expect from it.

Webhooks

If you are going to use webhooks instead of long polling, you need to implement your own webhook callbacks server. Take a look at this repo as an example.

Proxy

As some countries block access to Telegram, you can set up your own proxy and use it to access Telegram API. In this case you need to configure API url:

Telegram::Bot::Client.run(token, url: 'https://proxy.example.com') do |bot|
  # ...
end

Custom keyboards

You can use your own custom keyboards. Here is an example:

bot.listen do |message|
  case message.text
  when '/start'
    question = 'London is a capital of which country?'
    # See more: https://core.telegram.org/bots/api#replykeyboardmarkup
    answers =
      Telegram::Bot::Types::ReplyKeyboardMarkup
      .new(keyboard: [%w(A B), %w(C D)], one_time_keyboard: true)
    bot.api.send_message(chat_id: message.chat.id, text: question, reply_markup: answers)
  when '/stop'
    # See more: https://core.telegram.org/bots/api#replykeyboardremove
    kb = Telegram::Bot::Types::ReplyKeyboardRemove.new(remove_keyboard: true)
    bot.api.send_message(chat_id: message.chat.id, text: 'Sorry to see you go :(', reply_markup: kb)
  end
end

Furthermore, you can ask user to share location or phone number using KeyboardButton:

bot.listen do |message|
  kb = [
    Telegram::Bot::Types::KeyboardButton.new(text: 'Give me your phone number', request_contact: true),
    Telegram::Bot::Types::KeyboardButton.new(text: 'Show me your location', request_location: true)
  ]
  markup = Telegram::Bot::Types::ReplyKeyboardMarkup.new(keyboard: kb)
  bot.api.send_message(chat_id: message.chat.id, text: 'Hey!', reply_markup: markup)
end

Inline keyboards

Bot API 2.0 brought us new inline keyboards. Example:

bot.listen do |message|
  case message
  when Telegram::Bot::Types::CallbackQuery
    # Here you can handle your callbacks from inline buttons
    if message.data == 'touch'
      bot.api.send_message(chat_id: message.from.id, text: "Don't touch me!")
    end
  when Telegram::Bot::Types::Message
    kb = [
      Telegram::Bot::Types::InlineKeyboardButton.new(text: 'Go to Google', url: 'https://google.com'),
      Telegram::Bot::Types::InlineKeyboardButton.new(text: 'Touch me', callback_data: 'touch'),
      Telegram::Bot::Types::InlineKeyboardButton.new(text: 'Switch to inline', switch_inline_query: 'some text')
    ]
    markup = Telegram::Bot::Types::InlineKeyboardMarkup.new(inline_keyboard: kb)
    bot.api.send_message(chat_id: message.chat.id, text: 'Make a choice', reply_markup: markup)
  end
end

Inline bots

If you are going to create inline bot, check the example below:

bot.listen do |message|
  case message
  when Telegram::Bot::Types::InlineQuery
    results = [
      [1, 'First article', 'Very interesting text goes here.'],
      [2, 'Second article', 'Another interesting text here.']
    ].map do |arr|
      Telegram::Bot::Types::InlineQueryResultArticle.new(
        id: arr[0],
        title: arr[1],
        input_message_content: Telegram::Bot::Types::InputTextMessageContent.new(message_text: arr[2])
      )
    end

    bot.api.answer_inline_query(inline_query_id: message.id, results: results)
  when Telegram::Bot::Types::Message
    bot.api.send_message(chat_id: message.chat.id, text: "Hello, #{message.from.first_name}!")
  end
end

Now, with inline mode enabled, your message object can be an instance of Message, InlineQuery or ChosenInlineResult. That's why you need to check type of each message and decide how to handle it.

Using answer_inline_query you can send query results to user. results field must be an array of query result objects.

File upload

Your bot can even upload files (photos, audio, documents, stickers, video) to Telegram servers. Just like this:

bot.listen do |message|
  case message.text
  when '/photo'
    bot.api.send_photo(chat_id: message.chat.id, photo: Faraday::UploadIO.new('~/Desktop/jennifer.jpg', 'image/jpeg'))
  end
end

Logging

By default, bot doesn't log anything (uses NullLoger). You can change this behavior and provide your own logger class. See example below:

Telegram::Bot::Client.run(token, logger: Logger.new($stderr)) do |bot|
  bot.logger.info('Bot has been started')
  bot.listen do |message|
    # ...
  end
end

Connection adapters

Since version 0.5.0 we rely on faraday under the hood. You can use any of supported adapters (for example, net/http/persistent):

require 'net/http/persistent'

Telegram::Bot.configure do |config|
  config.adapter = :net_http_persistent
end

Boilerplates

If you don't know how to setup database for your bot or how to use it with different languages here are some boilerplates which can help you to start faster:

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Author: Atipugin
Source Code: https://github.com/atipugin/telegram-bot-ruby 
License: WTFPL license

#ruby #bot #telegram 

Telegram-bot-ruby: Ruby Wrapper for Telegram's Bot API
Royce  Reinger

Royce Reinger

1658488860

TelegramBotRuby: Yet another client for Telegram's Bot API

TelegramBotRuby

Installation

Add this line to your application's Gemfile:

gem 'telegram_bot_ruby'

And then execute:

$ bundle

Or install it yourself as:

$ gem install telegram_bot_ruby

Quick start

Set up client

require 'telegram_bot'

bot = TelegramBot.new(token: <token>)

bot.listen(method: :webhook, url: '/meow/meow')  # not implemented yet
# or
bot.listen(method: :poll, interval: 1)

Set up update listeners

bot.on :command, 'ping' do  # /ping
  reply 'pong'
end

bot.on :command, 'plus' do |num1, num2|  # /plus 1 2
  reply (num1.to_i + num2.to_i).to_s
end

bot.on :text 'ping' do     # plain 'ping'
  say 'pong'
end

# with block: false, message will keep passing through other listeners
bot.on :text, /(\d+)\+(\d+)\=\?/, block: false do |n1, n2|
  send_chat_action :typing
  say (n1.to_i + n2.to_i).to_s
end

# a simple history logger
bot.on :anything do |msg|
  Database.save [msg.from.username, msg.text] if !msg.text.empty?
end

Start && Stop

# register service at telegram or start long polling
trap(:INT) {
    bot.stop!
}
bot.start!

Documentation

Matchers

anything/fallback matcher

on :anything do
end
on :fallback do
end

text matcher

# match when message.type == :text
on :text do |txt|
    say txt  # a simplest echo bot
end

# arguments are given by `MatchData#to_a`
on :text, /reply me with (.*)/ do |matched_text, reply_txt|
    say reply_txt
end

command matcher

on :command, :ping do
    reply 'pong'
end

# handling requests like `/plus 1 2`
on :command :plus do |*args|
    reply args.map(&:to_i).sum.to_s
end

# or handle all commands
on :command do |cmd, *args|
    case cmd
    when 'echo'
        reply args.join(' ')
    when 'rand'
        reply rand.to_s
    else
        reply "unknown command #{cmd}"
    end
end

Telegram Types

Check the classes that include this module:

http://www.rubydoc.info/gems/telegram_bot_ruby/TelegramBot/AutoFromMethods

Bot methods

# msg: message object, or message id
# to: chat/user object or chat/user id
TelegramBot#forward_message(msg, to, from = nil)

TelegramBot#get_me => User

CHAT_ACTIONS = [
  :typing,
  :upload_photo,
  :record_video,
  :update_video,
  :record_audio,
  :upload_audio,
  :upload_document,
  :find_location
]
# chat: {chat,user} {object,id}
# action: CHAT_ACTIONS.sample
TelegramBot#send_chat_action(chat, action)


# chat: {chat,user} {object,id}
# text: text content of the message
# disable_web_page_preview: see Telegram doc
# reply_to: message object or id
# reply_markup: a keyboard markup, see example below
TelegramBot#send_message(chat,
                         text,
                         disable_web_page_preview: nil,
                         reply_to: nil,
                         reply_markup: nil)


# example keyboard markup
markup = {
    keyboard: [
        ["1", "2"],
        ["3", "4", "5"],
        ["6"]
    ],
    selective: false
}

Shorthand methods

Shorthand methods can be used within a handler block, with the received message as its context. rubydoc.info

reply(text, *args)
say(text, *args)
forward_to(to, *args)
send_chat_action(action, *args)

Handler context variables/methods

Other than the shorthand above, within the handler block, these contextual variable are accessible:

bot            # the current TelegramBot instance
bot.history    # request histories :: [Message]
bot.start!     # start polling
bot.stop!      # quit the bot

message        # the message just received
message.<attr> # message attributes
matcher        # current matcher object

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/shouya/telegram-bot.

Telegram api doc

Author: Shouya
Source Code: https://github.com/shouya/telegram-bot 
License: MIT license

#ruby #bot #telegram #api 

TelegramBotRuby: Yet another client for Telegram's Bot API
Royce  Reinger

Royce Reinger

1658481420

TelegramBot: A Charismatic Ruby Client for Telegram's Bot API

TelegramBot

A charismatic ruby client for Telegram's Bot API.

Write your own Telegram Bot using Ruby! Yay!

Installation

Add this line to your application's Gemfile (currently under development):

gem 'telegram_bot'

And then execute:

$ bundle

Usage

Here's an example:

require 'telegram_bot'

bot = TelegramBot.new(token: '[YOUR TELEGRAM BOT TOKEN GOES HERE]')
bot.get_updates(fail_silently: true) do |message|
  puts "@#{message.from.username}: #{message.text}"
  command = message.get_command_for(bot)

  message.reply do |reply|
    case command
    when /greet/i
      reply.text = "Hello, #{message.from.first_name}!"
    else
      reply.text = "#{message.from.first_name}, have no idea what #{command.inspect} means."
    end
    puts "sending #{reply.text.inspect} to @#{message.from.username}"
    reply.send_with(bot)
  end
end

Here's a sample output:

$ bundle exec ruby bot.rb
@eljojo: greet
sending "Hello, José!" to @eljojo
@eljojo: heeeeeeeeya!
sending "José, have no idea what \"heeeeeeeeya!\" means." to @eljojo

Example

How do I get a Bot Token

Talk to the @BotFather. You can find more info here.

How to get Token

What else can it do?

you can pass options to the bot initializer:

bot = TelegramBot.new(token: 'abc', logger: Logger.new(STDOUT), offset: 123, timeout: 20)

if you don't want to start the loop, don't pass a block to #get_updates and you'll get an array with the latest messages:

messages = bot.get_updates(timeout: 30, offset: 123)

Because things can go wrong sometimes with the API, there's a fail_silently option that you can pass to #get_updates like this:

bot.get_updates(fail_silently: true) do |message|
  puts message.text
end

A message has several attributes:

message = bot.get_updates.last

# message data
message.text # "hello moto"
message.date # Wed, 01 Jul 2015 09:52:54 +0200 (DateTime)

# reading user
message.from # TelegramBot::User
message.from.first_name # "Homer"
message.from.last_name  # "Simpson"
message.from.username   # "mr_x"

# channel
message.channel.id # 123123123 (telegram's id)

# reply
message.reply do |reply|
  reply.text = "homer please clean the garage"
  reply.send_with(bot)
end
# or
reply = message.reply
reply.text = "i'll do it after going to moe's"
bot.send_message(reply)

To send message to specific channel you could do following:

bot = TelegramBot.new(token: '[YOUR TELEGRAM BOT TOKEN GOES HERE]')
channel = TelegramBot::Channel.new(id: channel_id)
message = TelegramBot::OutMessage.new
message.chat = channel
message.text = 'Some message'

message.send_with(bot)

Also you may pass additional options described in API Docs

message.parse_mode = 'Markdown'

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/eljojo/telegram_bot. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

Currently under heavy development. Please collaborate with your questions, ideas or problems!

Author: eljojo
Source Code: https://github.com/eljojo/telegram_bot 
License: MIT license

#ruby #telegram #bot 

TelegramBot: A Charismatic Ruby Client for Telegram's Bot API
Royce  Reinger

Royce Reinger

1658473920

BOTServer: Bot API Webhooks Framework, for Rubyists

BOTServer

Telegram Bot API Webhooks Framework, for Rubyists.
BOTServer configures, tests and deploys bots, running a fast rack server for webhooks routing.

Webhooks vs long polling

BOTServer first goal is to set-up a Ruby way to manage Telegram Bot API webhooks Updates, a performance improvement in comparison with HTTPS long polling mode.

This project is related to telegram-bot-ruby gem, Alexander Tipugin's excellent Telegram Bot client APIs wrapper; to thank him for his work, I tried to solve issue #19: setting up webhooks with telegram-bot-ruby ?. BOTServer closed the issue :)

Multiple bots webhooks updates routing

Receiving HTTPS webhooks callbacks is probably more efficient than getting updates on a long polling connection, but the real need of webhooks is when you have dozen, hundreds of bots to manage at once with your server. In this scenario, it could pretty impossible to manage in a single host, using long polling connections, because the need to maintain open too many Ruby processes/ HTTPS (persistent) connections.

** BOTServer is a toolkit to test and deploy Bot tokens to receive webhooks with a very simple dynamic routing server: a rack server that dispatch dinamically incoming token webhooks, calling update method of an instance of a class generated with a template sckeleton, that define the bot. Details: Telegram Bot Architecture(s)**

  TELEGRAM Bot API Server                         
 --------------------------------------------------------------------
   v v v                                                       ^ ^ ^
   | | |                                                       | | |
   | | |    SSL/HTTPS                                          | | | 
   | | |    front-end       BOTServer                          | | |
   | | |    +-------+       Rack router                        | | |
   | | |    |       |       +------+                           | | |
   | | |    |       |       |      |     +-------+ HTTPS send  | | |
   | | |    |       |       |      |---->| App 1 |-------------+ | |
   | | |    |       | HTTP  |      |     +-------+               | |
   | | |    |       | POST  |      |                             | |
   | | +--->|       |------>|      |     +-------+ HTTPS send    | |
   | +----->|       |------>|      |---->| App 2 |---------------+ |
   +------->|       |------>|      |     +-------+                 |
   webhooks |       |       |      |                               |
 HTTPS POST |       |       |      |     +-------+  HTTPS send     |
            |       |       |      |---->| App   |-----------------+
            |       |       | Thin |     +-------+
            | NGINX |       +------+
            +-------+       

Assembly instructions in 7 steps

BOTServer is a devops utility to:

  • set-up and test tokens/webhooks
  • generate a template app for each bot
  • run a webhooks router/server.

Here assembly instruction steps:

  1. Installation (web/proxy server, Ruby project code)
  2. Get Telegram Bot token(s)
  3. Update configuration files
  4. Create (self-signed) Certificate
  5. Configure "Webhooks mode" for each token
  6. Generate template for each bot
  7. Deploy and run _BOTServer

Keep calm and follow step by step instrctions: Assembly instructions in 7 steps

After installation of the project, just run rake from your project home:

$ rake
rake app:new[token]        # Create bot app template for given token
rake certificate:new       # Create SSL certificate
rake certificate:show      # Show public certificate
rake proxy:config:new      # Generate nginx proxy SSL configuration from server.yml data
rake proxy:restart         # Restart proxy server
rake proxy:start           # Start proxy server
rake proxy:stop            # Stop proxy server
rake server:config:show    # Show server configuration: /home/solyaris/BOTServer/config/server.yml
rake server:config:test    # Check server configuration: /home/solyaris/BOTServer/config/server.yml
rake server:log            # Tail -f rack sever logfile: /home/solyaris/BOTServer/log/thin.log
rake server:pid            # Show rack server pid
rake server:restart        # Restart rack server
rake server:start          # Start rack server
rake server:stop           # Stop rack server
rake tokens:show           # Show tokens configuration file: /home/solyaris/BOTServer/config/tokens.yml
rake tokens:test           # Verify if tokens are valid, online querying Telegram Server
rake webhook:reset[token]  # Reset webhook for a given token
rake webhook:set[token]    # Set webhook for a given token

Telegram Bots Platform Architectures ?

Details about Telegram Bot API long polling vs webhooks: Telegram Bot Platform

Webhooks ?

There are at least three Telegram Bot Ruby clients (as far as I know), here listed Telegram BOT Ruby clients:

NOTE: All of them implement Telegram Bot API long polling way, with getUpdates endpoint. No one of these gems implement the webhooks mode.

Documentation / wiki

To do/Releases

Author: Solyarisoftware
Source Code: https://github.com/solyarisoftware/BOTServer 
License: 

#ruby #bot #server #telegram 

BOTServer: Bot API Webhooks Framework, for Rubyists
Nat  Grady

Nat Grady

1658066040

Franz: A Free Messaging App for Services Like WhatsApp, Messenger

Franz 5

Messaging app for WhatsApp, Slack, Telegram, HipChat, Hangouts and many many more.

Development

Preparations

Install Linux OS dependencies

Guide: Linux distribution specific dependencies

Fix native modules to match current electron node version

$ npm run rebuild

Install dependencies

Run the following command to install all dependencies, and link sibling modules with Franz.

$ npx lerna bootstrap

If you previously ran npm install it sometimes is necessary to delete your node_modules folder before running npx lerna bootstrap.

Run Franz Development App

Run these two commands simultaneously in different console tabs.

$ npm run dev
$ npm run start

Be aware that the development database will be reset regularly.

Packaging

$ npm run build

How can I support the project?

If you have found a bug that hasn't been reported yet or want to request a new feature, please open a new issue.

I need help?

Join the Franz community on Slack and get in touch with us.

Create your own plugins/recipes

You can find all the Information at the Plugins repository. For questions feel free to ask in the community Slack

Download Franz

👉 www.meetfranz.com

Or use homebrew (macOS only)

$ brew cask install franz

(Don't know homebrew? brew.sh)

Author: Meetfranz
Source Code: https://github.com/meetfranz/franz 
License: Apache-2.0 license

#electron #slack #messenger #telegram 

Franz: A Free Messaging App for Services Like WhatsApp, Messenger