Giter VIP home page Giter VIP logo

driver-telegram's Introduction

BotMan

Latest Version on Packagist Build Status codecov Scrutinizer Code Quality Packagist StyleCI Slack Monthly Downloads

https://phppackagedevelopment.com

If you want to learn how to create reusable PHP packages yourself, take a look at my upcoming PHP Package Development video course.

About BotMan

BotMan is a framework agnostic PHP library that is designed to simplify the task of developing innovative bots for multiple messaging platforms, including Slack, Telegram, Microsoft Bot Framework, Nexmo, HipChat, Facebook Messenger and WeChat.

$botman->hears('I want cross-platform bots with PHP!', function (BotMan $bot) {
    $bot->reply('Look no further!');
});

If you want to learn how to create reusable PHP packages yourself, take a look at my upcoming PHP Package Development video course.

Documentation

You can find the BotMan documentation at https://botman.io.

Stand Alone Configuration

If you are installing Botman in a stand alone Laravel application, you can publish the configuration file with the following command:

php artisan vendor:publish --tag=config --provider="BotMan\BotMan\BotManServiceProvider"

Support the development

Do you like this project? Support it by donating

Contributing

Please see CONTRIBUTING for details.

0 1 2 3 4 5 6 7

Security Vulnerabilities

If you discover a security vulnerability within BotMan, please send an e-mail to Marcel Pociot at [email protected]. All security vulnerabilities will be promptly addressed.

License

BotMan is free software distributed under the terms of the MIT license.

driver-telegram's People

Contributors

antimech avatar chimit avatar crynobone avatar emulator000 avatar feralheart avatar filippotoso avatar germanow avatar gnurlan avatar hanc2006 avatar holtkamp avatar jaewun avatar jeroen-g avatar lloople avatar mpociot avatar sergix44 avatar sh41 avatar stefanprintezis avatar tasselchof avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

driver-telegram's Issues

Is there way to send files (not images) without extending the driver?

Can I send CSV, XLS, PDF, or other files without rewriting the driver to get this feature?

$filePath = $this->createRatesCsv($rates);
$fileAttachment = new File($filePath, [
                'custom_payload' => false,
]);
$message = OutgoingMessage::create('Rate Data')->withAttachment($fileAttachment);
$this->bot->reply($message);

The construction like that doesn't work with both (URL or path) cases.

Someone may have had the proper piece of code not to dance with that thing.

The tests GitHub workflow is not working

Tests runs fine on my machine. Seems like to fix it here this needs to be added to the end of the composer.json file:

"config": {
    "allow-plugins": {
        "thecodingmachine/discovery": true
    }
}

and add --ignore-platform-req=composer-plugin-api to tests.yml composer install section.

Originally posted by @antimech in #110 (comment)

How to get callback_query_id into Conversation

  • BotMan Version: 2.7.6
  • PHP Version: 8.1
  • Messaging Service(s):
  • Cache Driver:
  • Laravel 9.11

Description:

How to get callback_query_id from ?

Steps To Reproduce:

 $this->ask($inline_keyboard, function (Answer $answer) use ($textMessage) {
            $selectedText = $answer->getText();
            $selectedValue = $answer->getValue();
            
            if ($selectedValue == "plus"){
                $this->bot->sendRequest('answerCallbackQuery', [
                    'callback_query_id' => 'HERE NEED callback_query_id',
                    'text' => "+ 1 товар"
                ]);
            }
        ........

image

New Feature: Get the complete chatMember object

In getUser() we use the getChatMember endpoints 'chatMember->user' entry, but next to it the return object has lot of other entries what some Telegram bots could use.
This is the documentation of the chatMember object.

TelegramInlineQueryDriver [feature discussion]

I successfully implemented Inline Queries Driver in my project and I would like to make PR to this repo but I need some advices about how to do it properly to meet the package requirements.

So the steps are:

  1. To create TelegramInlineQueryDriver class [DONE]
  2. Write matching logic [DONE]
public function matchesRequest()
    {
        return ! is_null($this->payload->get('inline_query'));
    }
  1. Check that other driver will not match inline_query (TelegramDriver itself)

  2. Here is the interesting part. Need to decide how TelegramInlineQueryDriver sends request to Telegram API.
    Because inline queries don't use Conversations/Messages - we just need to send response directly.

  3. In my project I've created buildServicePayloadInline instead of buildServicePayload method in TelegramInlineQueryDriver. buildServicePayloadInline will switch to answerInlineQuery endpoint:

$this->endpoint = 'answerInlineQuery';
  1. There I was sending request with data needed:
$data = ['inline_query_id' => $inline_query_id, 'cache_time' => 0];
//forming $arArticlesJson array
$data['results'] = '[' . implode(',', $arArticlesJson) . ']';

return $data;
  1. $arArticlesJson is array of InlineQueryResultArticle objects https://core.telegram.org/bots/api#inlinequeryresultarticle.

So now I'm wondering the most about "//forming $arArticlesJson array" part. We don't have Conversation classes here. But we need to inject our logic to prepare data that will be sent.

The most primitive way I see is for example to do that just by static method with closure:

DriverManager::loadDriver(TelegramInlineQueryDriver::class);

TelegramInlineQueryDriver::listen(function($inline_query) {
    //developer got access to all inline query parameters:
    //$inline_query['from']['id'];
    //$inline_query['id'];
    //$inline_query['query']; - the string user enters writing @bot_name <query>

    $data = ['inline_query_id' => $inline_query_id, 'cache_time' => 0];
    //forming $arArticlesJson array
    $data['results'] = '[' . implode(',', $arArticlesJson) . ']';

    return $data;
});

What are your ideas on this, dear colleagues?

Proxy

Can Botman connect to Telegram API via SOCKS5 or MTProto proxy? For example in Russia Telegram is blocked and API can't be used directly

The proper way to use Keyboard

Hello!
Could anyone share the conversation.php file with the proper way to use Keyboard and KeyboardButton classes? I'm walking around with no clear understanding of how to make bot react on keybord click.

Can't sendRequest with custom chat_id

Let's say I want sendRequest with custom chat_id like this without hears method:

$bot->sendRequest("pinChatMessage", [
        "chat_id" => $chatId,
        "message_id" => $messageId,
]);

This is not going to work because sendRequest always replaces my chat_id with Message.

$parameters = array_replace_recursive([
    'chat_id' => $matchingMessage->getRecipient(),
], $parameters);

In case we are not in hears method it will be null so nothing works.
Can you provide a way to pass custom chat_id?

Add new exceptions: bot was blocked by the user, chat not found

It would be cool not to handle such errors manually.

Here is an example of Telegram response after trying to send a message to a user that blocked your bot:
HTTP 403

{
  "ok": false,
  "error_code": 403,
  "description": "Forbidden: bot was blocked by the user"
}

Chat doesn't exist (i.e. user doesn't exist):
HTTP 400

{
  "ok": false,
  "error_code": 400,
  "description": "Bad Request: chat not found"
}

How to use Keyboard

  • BotMan Version: #.#.#
  • PHP Version: 7.4.1
  • Messaging Service(s): Telegram
  • Cache Driver: Telegram

Description:

Hello, please type a using Keyboard and callback example. Thanks

Why extra call to API for getUser()?

Method getUser() in TelegramDriver issue getChatMember telegram API call. Why fire 'expensive' by time API call while Telegram provides from entry in each call which is enought in most cases?

    "from": {
        "id": 000000,
        "is_bot": false,
        "first_name": "fname",
        "last_name": "lname",
        "username": "username",
        "language_code": "en"
    },

I think it must extract that information and may be implement in BotMan\Drivers\Telegram\Extensions\User getters for additional data, provided by getChatMember and call API only if one of additional fields is requested

Inline queries

Is this Telegram driver able to listen to inline queries à la https://core.telegram.org/bots/api#inline-mode?
I can't find any documentation about this.
In the end I want to build a bot that listens to inline queries, moves to Private Mode for a conversation and returns the answer in a group chat.

Error retrieving user info

When I try to start a conversation with a user who has already had a conversation with a Telegram bot, I receive the following error message:

BotMan\Drivers\Telegram\Exceptions\TelegramException: Error retrieving user info

It would seem not to be able to recover the infamous chat_id, you have any suggestions about it???

Versions:
"botman/botman": "2.4.1",
"botman/driver-telegram": "1.5.2"

Global commands are not working during the asking of a question

I'm sending a text message with links (like /ovd_info_12) and with two buttons "Next Page" and "Subscribe".

Now the system is waiting for the click or for some text entered.

Is there a way that if text was entered then the system will process if through the global hearing rules?
Because if user clicked on the "/ovd_info_12" then it's not processed by the globally defined hear rule.

        $buttons = [];
        $buttons[] = Button::create('Next Page')->value('ovd_page_2');
        $buttons[] = Button::create('Subscribe')->value('ovd_subscribe');

        $question = Question::create($text)
            ->callbackId('ovd_place')
            ->addButtons($buttons);

        $this->ask($question, function (Answer $answer) {

            if ($answer->isInteractiveMessageReply()) {
                if ($answer->getValue() == 'ovd_subscribe') {
                    $this->say('You are subscribed. Thanks.', ['parse_mode' => 'HTML']);
                }
            }
        }, ['parse_mode' => 'HTML']);`

Can't send/receive messages after a user posts a file greater than 20mb

If your bot receives a video/attachment that is greater than 20mb, it gets stuck in an error loop and can no longer send messages.

An exception is thrown because of this, but the Telegram API never receives a 200 response code so it just continues to send the attachment over and over.

[2018-10-14 06:42:07] production.ERROR: Error retrieving file url: Bad Request: file is too big {"exception":"[object] (BotMan\\Drivers\\Telegram\\Exceptions\\TelegramAttachmentException...

The only solution right now seems to be to unregister the webook and register it again.

TODO: Improve documentation

In this issue I will collect everything what should be included into the documentation.

If you have suggestions send a comment to this issue.

Bot replies to a message: #62

how we could add custom generic events?

Could someone explain that how I can add custom events on this driver?
like the array that was in TelegramDriver class

const GENERIC_EVENTS = [ 'new_chat_members', 'left_chat_member', 'new_chat_title', 'new_chat_photo', 'group_chat_created' ];

and on the other hand I have another question about hasMatchingEvent() function, how can I refer to this function in my CustomDriver class?

KeyboardButton with text 0 is filtered

When the following keyboard is added to a message

$keyboard = Keyboard::create(Keyboard::TYPE_KEYBOARD)->oneTimeKeyboard(true)->resizeKeyboard();  
$keyboard->addRow(KeyboardButton::create(0));

it will be translated into

'reply_markup' => '{"keyboard":[[[]]],"one_time_keyboard":true,"resize_keyboard":true}',

which causes Telegram to not relay the message to the intended recipient because of empty keyboard parameter.

As I dig through the code, the cause might be the following filter() inside KeyboardButton@jsonSerialize

public function jsonSerialize()
    {
        return Collection::make([
            'url' => $this->url,
            'callback_data' => $this->callbackData,
            'request_contact' => $this->requestContact,
            'request_location' => $this->requestLocation,
            'text' => $this->text,
        ])->filter()->toArray();
    }

Add an option to disable auto hiding keyboard

Now Telegram driver automatically hides keyboard for interactive messages:

public function messagesHandled()
{
$callback = $this->payload->get('callback_query');
if ($callback !== null) {
$callback['message']['chat']['id'];
$this->removeInlineKeyboard($callback['message']['chat']['id'],
$callback['message']['message_id']);
}
}

This method is called here:
https://github.com/botman/botman/blob/0afbda1ad742dd369b0b1368104b6d3462118262/src/BotMan.php#L408-L409

For my case it is required to prevent hiding keyboard, but I did not find a way to do this without extending TelegramDriver and overriding messagesHandled. My suggestion is to add an option to TelegramDriver config, for example 'hideKeyboard' => true (default) and hide a keyboard only if this parameter is set to true. Can make a PR.

Error with contacts that don't have telegram account!

  • BotMan Version: 2.8.2
  • driver-telegram version: 2.0.4
  • PHP Version: 7.3

Description:

I was testing botman using a very simple controller that only hears('{message}') and replies. it replies any kind of messages except the contacts that didn't have telegram account!

ErrorException: Undefined index: user_id in file vendor\botman\driver-telegram\src\TelegramContactDriver.php on line 54

Steps To Reproduce:

I think line 54 in TelegramContactDriver.php should be like the above lines for fixing this issue:

$this->event->get('contact')['user_id'], => $this->event->get('contact')['user_id'] ?? '',

do you agree with me?

How to send video via telegram bot

  • BotMan Version: 2.0
  • PHP Version: 7.4
  • Messaging Service(s): Telegram
  • Cache Driver: Laravel

Description:

How to send video via telegram bot to user. Please help
I installed Telegram driver on to BotManStudio. It works good! But I can't send video to user via telegram bot

I tried this. But it does not work

$attachment = new Video($url);
    $message = OutgoingMessage::create()->withAttachment($attachment);

   $bot->reply($message);

Steps To Reproduce:

Receiving image caption

  • BotMan Version: 1.6.2

In Telegram you can send an image and add a caption. Is it possible to retrieve a caption using Telegram Driver?

        $botman->receivesImages(function($bot, $images) {
            foreach ($images as $image) {
                 $title = $image->getTitle();
                 // $title is always empty
            }
        });

Extended driver not loaded on `receivesLocation` method

I have extended this driver by adding DriverManager::loadDriver(MyTelegramDriver::class); in AppServiceProvider because I want to send external button links on normal reply without creating a question.

All works great except if the Controller's method is called from $botman->receivesLocation method. I tried to dig into the code but can't find the problem.

Thank you.

Botman with Telegram driver removes Keyboard from chat

When I try to send message like this:

bot->reply('blabla', [
            'reply_markup' => json_encode(Collection::make([
            'inline_keyboard' => [ ... ]
        ]))
]);

After click on a button , all keyboard will be removed instantly.

I found these lines in listen() method:

               if (method_exists($this->getDriver(), 'messagesHandled')) {
                    $this->getDriver()->messagesHandled();
                }

Which calls removeInlineKeyboard().
Is it possible to add some kind of manual switcher for this feature? Or better just automatically control if it was a Question, than removeInlineKeyboard, otherwise - don't?

Versions:
"botman/botman": "2.1.10",
"botman/driver-telegram": "1.4",

"date": field

I'm trying to understand when can I extend your driver to get the telegram "date" of a message.

In my bot I'd love to get the user datetime sent by Telegram POST request on every message to handle some logic.

Is it possible?

POST'ing Telegram url through botman studio

I think it would be great if it were possible from within Botman studio to register the webhook for the bot with telegram.
If I were to turn this into an artisan command, would this be merged?

Is it possible to send local files (not by URL)?

  • BotMan Version: 2.6
  • PHP Version: 7.4
  • Messaging Service(s): Telegram
  • Cache Driver:

Description:

I try to add local image to OutgoingMessage and recieve error 400 from telegram.
Is it possible to send local files to TG?

Steps To Reproduce:

    $attachment = new BotmanImageAttachment($image->getPathname(), ['custom_payload' => true]);
    $message = OutgoingMessage::create($messageText)->withAttachment($attachment);

Response:
"{"ok":false,"error_code":400,"description":"Bad Request: wrong remote file identifier specified: Wrong character in the string"}"

Messages not being received from Telegram

The only thing I see comming to my server is:

149.154.167.217 - - [25/Mar/2019:15:07:51 +0100] "POST /botman HTTP/1.1" 500 132738 "-" "-"
149.154.167.217 - - [25/Mar/2019:15:07:57 +0100] "POST /botman HTTP/1.1" 500 132729 "-" "-"
149.154.167.217 - - [25/Mar/2019:15:07:59 +0100] "POST /botman HTTP/1.1" 500 132723 "-" "-"
149.154.167.217 - - [25/Mar/2019:15:08:03 +0100] "POST /botman HTTP/1.1" 500 132733 "-" "-"
149.154.167.217 - - [25/Mar/2019:15:08:06 +0100] "POST /botman HTTP/1.1" 500 132745 "-" "-"
149.154.167.217 - - [25/Mar/2019:15:08:08 +0100] "POST /botman HTTP/1.1" 500 132743 "-" "-"
149.154.167.217 - - [25/Mar/2019:15:08:12 +0100] "POST /botman HTTP/1.1" 500 132757 "-" "-"

But anything I type on Telegram isn't getting thru?

Webhook is properly registered

Your bot is now set up with Telegram's webhook!
{#665
+"ok": true
+"result": true
+"description": "Webhook is already set"
}

Telegram public channel 'hearing messages'

The returned payload of a public channel message and DM message are structured differently.

So the following works in a DM, however not in public channels.

$botman->hears('keyword', function($bot) {
    $bot->reply('I heard you! :)');
});

What is suggested for making this work in a Telegram channel?

Not working callback_data in menu

  • BotMan Version: 2.0.0
  • PHP Version: 8.0.17
  • Messaging Service(s): Telegram
  • Cache Driver: Laravel

Description:

Not working callback_data
bot sends text

Steps To Reproduce:

$bot->reply(
    "👉🏼 Menu👇🏽",
    [
            'reply_markup' => json_encode([
                'keyboard' => [
                    [
                        [
                            'text' => 'Фотогалерея 🖼',
                            'callback_data' => '/photos',
                        ],
                        [
                            'text' => 'Планировки 📐',
                            'callback_data' => 'plans',
                        ],
                    ],
                    [
                        [
                            'text' => 'Характеристики ЖК 🏣',
                            'callback_data' => 'characteristics',
                        ],
                        [
                            'text' => 'Расположение ⛳️',
                            'callback_data' => 'place',
                        ],
                    ],
                    [
                        [
                            'text' => "Скачать прайс  ₽",
                            'callback_data' => 'price',
                        ],
                        [
                            'text' => 'Записаться на показ 📞',
                            'callback_data' => 'write-on-show',
                        ],
                    ],
                    [
                        [
                            'text' => 'Получить консультацию 📞',
                            'callback_data' => 'consultation',
                        ],
                        [
                            'text' => 'Акции  %',
                            'callback_data' => 'sales',
                        ],
                    ],
                ],
            ]),
        ]
 )```

Class 'BotMan\BotMan\Messages\Attachments\Contact' not found

  • BotMan Version: 2.4.1
  • PHP Version: 7.2

Description:

When I send contact to bot I got error in vendor\\botman\\driver-telegram\\src\\TelegramContactDriver.php.
There is no class BotMan\BotMan\Messages\Attachments\Contact

Steps To Reproduce:

Send contact to bot.

Why PHP 7.0?

I using PHP 5.6.25.0, and i cant install this package. Why it need PHP >= 7.0?

Telegram doesn't hear images.

  • BotMan Version: 2.5.0
  • PHP Version: 7.2.24
  • Messaging Service(s): Telegram
  • Cache Driver: Laravel Cache
    $botman = $this->botman;
    
    $botman->hears('stop', function(BotMan $bot) {})->skipsConversation();
    
    $botman->receivesImages(function(BotMan $bot, $images) {
        foreach ($images as $image) {
            $url = $image->getUrl();
            $this->interpret($bot, $url, 'IMAGE');
        }
    });
    
   $botman->hears('{something}', function (BotMan $bot, $something) {
            $this->interpret($bot, $something, 'TEXT');
    });

    $botman->listen();

In the interpret() method I have a $bot->reply("I have a " . $messageType); where the $messageType is the third param of interpret()
My problem is, that when I send a text from Telegram it replies me back the "I have a TEXT", but when I send an image I got a HTTP Status 200 in ngrok and next to it nothing happens.
What am I missing?

Undefined index: vcard in TelegramContactDriver

Required Information

  • BotMan version: 2.6
  • BotMan Telegram Driver version: 1.6

Expected behaviour

Receiving contact array after user sends his contact details.

Actual behaviour

TelegramContactDriver is not checking iv vcard field is present. That causes error:

Undefined index: vcard {"exception":"[object] (ErrorException(code: 0): Undefined index: vcard at /var/www/html/vendor/botman/driver-telegram/src/TelegramContactDriver.php:55)

Steps to reproduce

Using this code example: https://gist.github.com/yarkm13/4d9359f2c96149a012f563ea41849c02

Extra details

Solved it by extending TelegramContactDriver and overriding loadMessages method:

public function loadMessages()
    {
        $message = new IncomingMessage(Contact::PATTERN, $this->event->get('from')['id'], $this->event->get('chat')['id'], $this->event);
        $message->setContact(new Contact(
            $this->event->get('contact')['phone_number'],
            $this->event->get('contact')['first_name'],
            $this->event->get('contact')['last_name'],
            $this->event->get('contact')['user_id'],
            $this->event->get('contact')['vcard'] ?? null
        ));

        $this->messages = [$message];
    }

then in routes/botman.php:

DriverManager::unloadDriver(TelegramContactDriverBase::class);
DriverManager::loadDriver(TelegramContactDriver::class);
// required to do before the 'resolve'
$botman = resolve('botman');

Array to string conversion error on Laravel 5.6

Array to string conversion {"exception":"[object] (ErrorException(code: 0): Array to string conversion at /PROJECT-ROOT/vendor/botman/driver-telegram/src/TelegramDriver.php:138)

Don't know much what's wrong with this error, do you have any ideas to solve this error out?
Thank you so much!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.