Giter VIP home page Giter VIP logo

bot-api-base's Introduction

Telegram Bot Api Base

Telegram bot api Latest Version on Packagist Software License Coverage Status build Quality Score PHP Version >= 7.2 Symfony Recipe

Quality Gate Status Bugs Duplicated Lines (%) Security Rating

Supported Telegram Bot API 5.0 (November 4, 2020)

Installation

Via Composer

composer require tg-bot-api/bot-api-base --prefer-dist

Usage

We support all psr17 and psr18 implementations, but we will use guzzle6 for example

composer require php-http/guzzle6-adapter http-interop/http-factory-guzzle --prefer-dist
$botKey = '<bot key>';

$requestFactory = new Http\Factory\Guzzle\RequestFactory();
$streamFactory = new Http\Factory\Guzzle\StreamFactory();
$client = new Http\Adapter\Guzzle6\Client();

$apiClient = new \TgBotApi\BotApiBase\ApiClient($requestFactory, $streamFactory, $client);
$bot = new \TgBotApi\BotApiBase\BotApi($botKey, $apiClient, new \TgBotApi\BotApiBase\BotApiNormalizer());

$userId = '<user id>';

$bot->send(\TgBotApi\BotApiBase\Method\SendMessageMethod::create($userId, 'Hi'));

You can configure it to work in symfony, for example, in this way.

If you want to use your own api server - you can set url as 4th param in bot api

$bot = new \TgBotApi\BotApiBase\BotApi('<bot key>', $apiClient, new \TgBotApi\BotApiBase\BotApiNormalizer(), '<your-domain>');

Allowed methods:

Method Allowed type response
add AddStickerToSetMethod bool
answer AnswerCallbackQueryMethod, AnswerInlineQueryMethod, AnswerPreCheckoutQueryMethod, AnswerShippingQueryMethod bool
create CreateNewStickerSetMethod bool
delete DeleteChatPhotoMethod, DeleteChatStickerSetMethod, DeleteMessageMethod, DeleteStickerFromSetMethod, DeleteWebhookMethod bool
edit EditMessageCaptionMethod, EditMessageLiveLocationMethod, EditMessageMediaMethod, EditMessageReplyMarkupMethod, EditMessageTextMethod bool
forward ForwardMessageMethod MessageType
kick KickChatMemberMethod bool
leave LeaveChatMethod bool
pin PinChatMessageMethod bool
promote PromoteChatMemberMethod bool
restrict RestrictChatMemberMethod bool
send SendPhotoMethod, SendAudioMethod, SendDocumentMethod, SendVideoMethod, SendAnimationMethod, SendVoiceMethod, SendVideoNoteMethod, SendGameMethod, SendInvoiceMethod, SendLocationMethod, SendVenueMethod, SendContactMethod, SendStickerMethod, SendMessageMethod, SendPollMethod, SendDiceMethod MessageType
set SetChatDescriptionMethod, SetChatPhotoMethod, SetChatStickerSetMethod, SetChatTitleMethod, SetGameScoreMethod, SetStickerPositionInSetMethod, SetWebhookMethod, SetPassportDataErrorsMethod, SetChatPermissionsMethod, SetChatAdministratorCustomTitleMethod, SetMyCommandMethod, SetStickerSetThumbMethod bool
stop StopMessageLiveLocationMethod bool
stopPoll StopPollMethod Poll
unban UnbanChatMemberMethod bool
unpin UnpinChatMessageMethod, UnpinAllChatMessagesMethod bool
upload UploadStickerFileMethod FileType
exportChatInviteLink ExportChatInviteLinkMethod string
sendChatAction SendChatActionMethod bool
getUpdates GetUpdatesMethod UpdateType[]
getMe GetMeMethod UserType
getMyCommands GetMyCommandsMethod BotCommandType
getUserProfilePhotos GetUserProfilePhotosMethod UserProfilePhotosType
getWebhookInfo GetWebhookInfoMethod WebhookInfoType
getChatMembersCount GetChatMembersCountMethod int
getChat GetChatMethod ChatType
getChatAdministrators GetChatAdministratorsMethod ChatMemberType[]
getChatMember GetChatMemberMethod ChatMemberType
getChatMenuButton GetChatMenuButtonMethod MenuButtonType
getGameHighScores GetGameHighScoresMethod GameHighScoreType[]
getStickerSet GetStickerSetMethod StickerSetType
getFile GetFileMethod FileType
sendMediaGroup SendMediaGroupMethod MessageType[]
getAbsoluteFilePath FileType string
logOut LogOutMethod bool
close CloseMethod bool
copyMessage CopyMessageMethod MessageIdType
call($method, [string $type]) any method class, [optional expected type] array or excepted type object

Implemented all methods and types referenced by official Api

You can use BotApiComplete instance as helper to call all methods from official Api like this:

$botKey = '<bot key>';

$requestFactory = new Http\Factory\Guzzle\RequestFactory()
$streamFactory = new Http\Factory\Guzzle\StreamFactory();
$client = new Http\Adapter\Guzzle6\Client();

$apiClient = new \TgBotApi\BotApiBase\ApiClient($requestFactory, $streamFactory, $client);
$bot = new \TgBotApi\BotApiBase\BotApiComplete($botKey, $apiClient, new \TgBotApi\BotApiBase\BotApi\BotApiNormalizer());

$userId = '<user id>';

$bot->sendMessage(\TgBotApi\BotApiBase\Method\SendMessageMethod::create($userId, 'Hi'));

Learn api

Fetching webhooks

Method fetch() of WebhookFetcher handling Psr\Http\Message\RequestInterface or string and always returns instance of UpdateType or throwing BadRequestException.

$fetcher = new \TgBotApi\BotApiBase\WebhookFetcher(new \TgBotApi\BotApiBase\BotApiNormalizer());
$update = $fetcher->fetch($request);

Change log

Please see CHANGELOG for more information on what has changed recently.

Testing

$ composer test

Contributing

Please see CONTRIBUTING and CODE_OF_CONDUCT for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

bot-api-base's People

Contributors

big-shark avatar cybernet avatar greenplugin avatar gusaln avatar jan-di avatar uterok avatar xepozz 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

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

bot-api-base's Issues

Issue: ❓ Support Question

I tray to get some info bot Telegram don't reply support tickets!

Can you help me with Telegram. so that I am sent in the right direction.

I work for a government organization and we have a weekly exercise, now I would like to simplify this with, for example, a poll or something else where if someone responds to that I get a feedback via the telegram API.

I want to use PHP for this but see many options on the Telegram website https://core.telegram.org/bots/samples#php but now which one is and is not suitable for this and there is a little explanation somewhere how to find it tackles this?

https://telegram.org/blog/polls-2-0-vmq

Greetings Theo

Version 2.x (php7.4)

We want to change minimal version php to 7.4 in our package version 2. It's make all methods and types more strict and clean.

In this thread we will collect suggestions for version 2.
This update will not be compatible with version 1.x, so you can suggest any reasonable improvement.

Ofcourse we will support both versions (1.x and 2.x) and update it according telegram bot api changes.

Throws exception when the sending user has a username

Detailed description

When the user which seends a message to the bot has a username, there will be an exception thrown while processing webhook updates.

ReflectionException: Property TgBotApi\BotApiBase\Type\ChatType::$username does not exist

If i remove my username in telegram, the message get processed normally.

Possible implementation

After a quick test, it seems to be sufficient to simply add a property called $username in the ChatType class.

Your environment

PHP 7.3 with lando.dev

Entities property of SendMessageMethod misses important comment

Detailed description

When I'm building a new message via SendMessageMethod I'm passing an entities list that cannot be normalized by BotApiNormalizer. It just ignores them and still appears as an array instead of encoded json.

$buttonA = new InlineKeyboardButtonType();
$buttonA->callbackData = 'a';
$buttonA->text = 'A';

$buttonB = new InlineKeyboardButtonType();
$buttonB->callbackData = 'b';
$buttonB->text = 'B';

$inlineKeyboard = new InlineKeyboardMarkupType();
$inlineKeyboard->inlineKeyboard = [
    [$buttonA, $buttonB],
];

$messageEntity = new MessageEntityType();
$messageEntity->type = MessageEntityType::TYPE_TEXT_LINK;
$messageEntity->offset = 58;
$messageEntity->length = 23;
$messageEntity->url = 'https://google.com';

$sendMessage = new SendMessageMethod();
$sendMessage->chatId = '111222333';
$sendMessage->text = 'some text';
$sendMessage->replyMarkup = $inlineKeyboard;
$sendMessage->entities = [$messageEntity];

$this->botApi->send($sendMessage);

$normalizer = new BotApiNormalizer();
$normalizedRequest = $normalizer->normalize($sendMessage); // entities are not normalized at this step

And this method cannot be sent by the api client:

[2022-04-23 17:33:43] app.ERROR: Array to string conversion in /.../tg-bot-api/bot-api-base/src/ApiClient.php:106

Your environment

Include as many relevant details about the environment you experienced the bug in and how to reproduce it.

  • Version used: PHP 8.1

New version bot api released

We need to support it

March 30, 2020

Bot API 4.7
  • Added the method sendDice for sending a dice message, which will have a random value from 1 to 6. (Yes, we're aware of the “proper” singular of die. But it's awkward, and we decided to help it change. One dice at a time!)
  • Added the field dice to the Message object.
  • Added the method getMyCommands for getting the current list of the bot's commands.
  • Added the method setMyCommands for changing the list of the bot's commands through the Bot API instead of @BotFather.
  • Added the ability to create animated sticker sets by specifying the parameter tgs_sticker instead of png_sticker in the method createNewStickerSet.
  • Added the ability to add animated stickers to sets created by the bot by specifying the parameter tgs_sticker instead of png_sticker in the method addStickerToSet.
  • Added the field thumb to the StickerSet object.
  • Added the ability to change thumbnails of sticker sets created by the bot using the method setStickerSetThumb.

source: https://core.telegram.org/bots/api#march-30-2020

  • add all tests

Poll data is absent in MessageType class

When sending SendPollMethod, there is no poll info in response. I suppose it can be achieved by adding the following property to the MessageType class:

    /**
     * @var PollType
     */
    public $poll;

I rely on a quick fix for this. Thank you in advance.

Serialization error

Serialization error

When I'm sends poll I receive this error. It's because wrong normalization in request.

In ApiClient.php line 128:
                                      
Notice: Array to string conversion

How to fix

We need to add new normalizer like this

I'll fix it tonight

[InvalidArgumentException] Could not find a matching version of package greenplugin/telegram-bot-api. Check the package spelling, your version constraint and that the package is available in a stability which matches your minimum-stability (stable).

Detailed description

When I tried to install using composer, I got this error message :

[InvalidArgumentException]
Could not find a matching version of package greenplugin/telegram-bot-api.
Check the package spelling, your version constraint and that the package is
available in a stability which matches your minimum-stability (stable).

Installation does not work because there are no stable version. Please make a release so it can be used.

BotApi::edit(EditMessageMediaMethod) cast error

after executing following line:

BotApi::edit(EditMessageMediaMethod::create($chatId, $messageId, InputMediaVideoType::create($url), array('replyMarkup'=>$someInlineKeyboardMarkup)));

exception throws : Bad Request: can't parse InputMedia: Can't parse media JSON object

and PHP Notice : Array to string conversion in /foo/vendor/tg-bot-api/bot-api-base/src/ApiClient.php on line 106 which is ApiClient::createStreamBody() method

Bot api update June 4, 2020

Need to implement all new features:

  • Added the new field via_bot to the Message object. You can now know which bot was used to send a message.
  • Supported video thumbnails for inline GIF and MPEG4 animations.
  • Supported the new basketball animation for the random dice. Choose between different animations (dice, darts, basketball) by specifying the emoji parameter in the method sendDice.

Баг нормализации InlineKeyboardMarkupType

Описание

Telegram ожидает в поле reply_markup json с ключом inline_keyboard и значением в виде массива массивов, но после нормализации в reply_markup остается json c ключом inline_keyboard значения которого массив объектов

PHP 7.4.2
Slim 4.7

Packages conflict on Laravel 7

Can't install this package on Laravel 7 instalation

composer require tg-bot-api/bot-api-base

gives error

  Problem 1
    - Conclusion: remove phpdocumentor/reflection-common 2.2.0
    - Conclusion: don't install phpdocumentor/reflection-common 2.2.0
    - phpdocumentor/reflection-docblock 4.3.0 requires phpdocumentor/reflection-common ^1.0.0 -> satisfiable by phpdocumentor/reflection-common[1.0, 1.0.1].
    - phpdocumentor/reflection-docblock 4.3.1 requires phpdocumentor/reflection-common ^1.0.0 -> satisfiable by phpdocumentor/reflection-common[1.0, 1.0.1].
    - Can only install one of: phpdocumentor/reflection-common[1.0, 2.2.0].
    - Can only install one of: phpdocumentor/reflection-common[1.0.1, 2.2.0].
    - Installation request for phpdocumentor/reflection-common (locked at 2.2.0) -> satisfiable by phpdocumentor/reflection-common[2.2.0].
    - Installation request for tg-bot-api/bot-api-base ^1.6 -> satisfiable by tg-bot-api/bot-api-base[1.6.0].
    - Conclusion: don't install phpdocumentor/reflection-docblock 5.1.0|install phpdocumentor/reflection-docblock 4.3.0|install phpdocumentor/reflection-docblock 4.3.1
    - Conclusion: remove phpdocumentor/reflection-docblock 5.1.0|install phpdocumentor/reflection-docblock 4.3.0|install phpdocumentor/reflection-docblock 4.3.1
    - tg-bot-api/bot-api-base 1.6.0 requires phpdocumentor/reflection-docblock ^4.3 -> satisfiable by phpdocumentor/reflection-docblock[4.3.0, 4.3.1, 4.3.2, 4.3.3, 4.3.4].
    - Can only install one of: phpdocumentor/reflection-docblock[4.3.2, 5.1.0].
    - Can only install one of: phpdocumentor/reflection-docblock[4.3.3, 5.1.0].
    - Can only install one of: phpdocumentor/reflection-docblock[4.3.4, 5.1.0].
    - Installation request for phpdocumentor/reflection-docblock (locked at 5.1.0) -> satisfiable by phpdocumentor/reflection-docblock[5.1.0].

Also tried to install version 1.5.0, but faced the same package conflict error.

  • PHP 7.4:
  • Laravel v7.18.0:

Add Bot api updates

Update package to actual bot api version

Telegram published two updates for bot api.
Need to update package to use the latest features.

Current bot api version: Telegram bot api
Available bot api version: Telegram bot api

All_languages_music_bot

Detailed description

Provide a detailed description of the change or addition you are proposing.

Make it clear if the issue is a bug, an enhancement or just a question.

Context

Why is this change important to you? How would you use it?

How can it benefit other users?

Possible implementation

Not obligatory, but suggest an idea for implementing addition or change.

Your environment

Include as many relevant details about the environment you experienced the bug in and how to reproduce it.

  • Version used (e.g. PHP 7.2):
  • Framework used (e.g. Symfony 5.0):
  • Link to your project:

Create symfony flex recipe

We need to create Symfony Flex recipe for this library.
It will easy installation and easy configuration.

EditMessage Problem

    $response = $bot->send(
        \TgBotApi\BotApiBase\Method\SendMessageMethod::create($userId, 'Hi2')
    );

    $prevMessageId = $response->messageId;
    $response = $bot->edit(
        \TgBotApi\BotApiBase\Method\EditMessageTextMethod::create($userId, $prevMessageId, 'Hello')
    );

Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_RECOVERABLE_ERROR)
Argument 3 passed to TgBotApi\BotApiBase\ApiClient::createDataStream() must be of the type string, int given

Normalize problem with prices attribute of SendInvoiceMethod

I tried to send an invoice, but got the notice:
PHP Notice: Array to string conversion in .../src/ApiClient.php on line 106

And receive unsuccessful response from telegram.

Example

$invoice = SendInvoiceMethod::create(
    $telegramAccount->getTelegramId(),
    'title',
    'description',
    'payload',
    'token',
    'startParameter',
    'USD',
    [LabeledPriceType::create('label', 234)]
);

$bot->sendInvoice($invoice);

When ApiClient try to createStreamBody it cast value (array) as string:

        foreach ($request->getData() as $name => $value) {
            // todo [GreenPlugin] fix type cast and replace it to normalizer
            $stream .= $this->createDataStream($boundary, $name, (string) $value);
        }

All_languages_music_bot

Detailed description

Provide a detailed description of the change or addition you are proposing.

Make it clear if the issue is a bug, an enhancement or just a question.

Context

Why is this change important to you? How would you use it?

How can it benefit other users?

Possible implementation

Not obligatory, but suggest an idea for implementing addition or change.

Your environment

Include as many relevant details about the environment you experienced the bug in and how to reproduce it.

  • Version used (e.g. PHP 7.2):
  • Framework used (e.g. Symfony 5.0):
  • Link to your project:

PHP 7 Support?

Could not find package tg-bot-api/bot-api-base at any version matching your PHP version 7.0.10.0

Do you support PHP7?

Uncaught Error: Cannot use object of type stdClass as array in UserProfilePhotosNormalizer.php

Detailed description

BotApiInterface::getUserProfilePhotos(GetUserProfilePhotosMethod::create($id));

was throw this error:

Uncaught Error: Cannot use object of type stdClass as array

In UserProfilePhotosNormalizer.php line 54:

Cannot use object of type stdClass as array

Please replace line 54 of UserProfilePhotosNormalizer to $data->photos = $serializer->denormalize($data->photos, PhotoSizeType::class . '[][]');

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.