Giter Site home page Giter Site logo

unreal4u / telegram-api Goto Github PK

View Code? Open in Web Editor NEW
783.0 57.0 172.0 2.16 MB

Complete async capable Telegram bot API implementation for PHP7

Home Page: https://github.com/unreal4u/telegram-api/wiki

License: MIT License

PHP 99.60% Shell 0.15% Dockerfile 0.25%
telegram-api bot-api php7 telegram telegram-bot php reactphp inline-bots wiki-page composer

telegram-api's Introduction

PHP 7 Telegram Bot API Library

Telegram API Library

Latest Stable Version Total Downloads Build Status Scrutinizer Code Quality Code Coverage License

This is a PHP7 bot API implementation for Telegram implementing the vast majority of Bot API up until v4.7. The only thing it does not implement is Telegram Passport which was introduced in Bot API v4.0. It is unlikely to be introduced as it may introduce security vulnerabilities. However, if you think you have a strong case for the need, feel free to let me know.

About this package

  • Enables you to anything supported by the Telegram Bot API: messages, stickers, location, inline bots and any other supported method via PHP to a Telegram user (either direct conversation, channel, group or supergroup).
  • Respects and implements the default types and methods made by Telegram itself. Have any doubts about any method? Just check the original documentation, this implementation will not differ too much.
  • Doesn't need any mandatory dependencies, except for ReactPHP, which you can inject if you already use it elsewhere.
  • Full inline bots support.
  • Full support for payment system.

Known bugs

Telegram

The only thing that is not included in this library (yet) is the Passport support. This was an ongoing development, but it ended up being a lot more work than initially thought, so if someone wants to pick that up... be my guest!

All other known bugs can be found in the form of issues or pull requests. Found a new bug? Feel free to submit a PR or create an issue! Not sure if you've found a new bug? You can always ask in the special group :)

Roadmap

  • v4 (no branch yet) will be the next major release. More information.
  • v3 (master branch) is the current active branch.
  • v2 (v2 branch) is deprecated and no new work will be done there.
  • v1 is deprecated and no new work will be done there.
  • v0 is deprecated and no new work will be done there.

Installation

Total Downloads

Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you. Read this for installation instructions.
The preferred (and only for now) installation method is Composer, so add the following to your composer.json:

{
  "require": {
    "unreal4u/telegram-api": "~3.4"
  }
}

If you are not familiar with it, I suggest reading the basic usage manual located here.

Tip for Russian users

In order to use a proxy, you can use the https://github.com/clue/php-socks-react package and pass on the following options to the Client:

<?php

use Clue\React\Socks\Client;

$loop = Factory::create();
// Replace PROXY_ADDRESS and PROXY_PORT with the correct configuration
$proxy = new Client('socks5://' . PROXY_ADDRESS . ':' . PROXY_PORT, new Connector($loop));
$handler = new HttpClientRequestHandler($loop, [
    'tcp' => $proxy,
    'timeout' => 3.0,
    'dns' => false
]);

$this->tgLog = new TgLog(BOT_TOKEN, $handler);
// The rest is exactly the same as it normally is, see the examples folder for more information

With these simple steps, a proxy is configured in no time!

Upgrading v2.x to v3

A lot of backwards incompatibility changes, but in a nutshell:

  • ReactPHP is the new Guzzle (Async requests!)
  • Changed parameter order when invoking the constructor of TgLog
  • Custom -Array types now implement IteratorAggregate (Solves #21 !)

Please check the following Wiki page if you have to upgrade from v2 to v3.

General usage

Basic usage example:

<?php

use \unreal4u\TelegramAPI\HttpClientRequestHandler;
use \unreal4u\TelegramAPI\TgLog;
use \unreal4u\TelegramAPI\Telegram\Methods\SendMessage;

$loop = \React\EventLoop\Factory::create();
$handler = new HttpClientRequestHandler($loop);
$tgLog = new TgLog(BOT_TOKEN, $handler);

$sendMessage = new SendMessage();
$sendMessage->chat_id = A_USER_CHAT_ID;
$sendMessage->text = 'Hello world!';

$tgLog->performApiRequest($sendMessage);
$loop->run();

(Side note: In case React\EventLoop\Factory cannot be resolved in the above code, add include('vendor/autoload.php') to your PHP file).

With the SendMessage() object, you can create a message to be sent through the TgLog object.
All other functionality is based upon this behaviour, so every other method is very similar: you instantiate an object, pass that object to TelegramLog->performApiRequest(), which will return a Promise. If the method returns a reply, pass a callback to its onFulfilled parameter and you'll get the native Telegram response back as an object. Different methods return different object types.

Please refer to the examples directory to view examples of some of the implemented methods, including inline bots.

For examples of actual code that works in a production environment, please refer to my other repo: https://github.com/unreal4u/telegram-bots

Getting updates via Webhook

Please check the following wiki section for more information on this.

Inline bots

Please checkout the special wiki page about inline bots.

Extra requirements

If you want to use this package, you'll need a bot API key. Check the following documentation for more instructions on that.

Getting everything started up

The most difficult thing to do when performing an action with the Telegram API is to get the chat_id, which is the actual conversation window the bot talks to. You can execute the GetUpdates() method in order to get this chatId. Note that there are some caveats on this, so you may be better out with the SetWebhook() method instead.

Development

Semver

I will try my best to respect Semantic Versioning.
That being said, the first stable release is v1.0.0, from there on no mayor BC changes will occur unless we update the major.

Want to colaborate?

Collaborations are very welcome! Check this Wiki page out for more information that will make the development easier!

Contact the author

Telegram

I actually don't use Telegram. Nah, kidding, I created a group where you can contact me at https://t.me/PHPBotAPI. Another great way to get in touch is to simply create an issue or a pull request!

Bugs related with security

I would appreciate it if you could handle these responsibly. If you happen to find a security issue relating to this Telegram Bot API client, please ask me to contact you privately over here.

Special thanks to

telegram-api's People

Contributors

azacchino avatar djnotes avatar djtommek avatar kelunik avatar lucadevelop avatar megazoll avatar mrdarkest avatar nanosector avatar nightprince avatar samnela avatar unreal4u avatar vivianlink avatar wyrihaximus 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  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

telegram-api's Issues

Got Error

Hi.
I'm trying use this library. bot i get this error

capture

This is my code. simple getme.

$tgLog = new TgLog($botToken);

        $getMe = new GetMe();

        try {
            $response = $tgLog->performApiRequest($getMe);
            echo '<pre>';
            var_dump($response);
            echo '</pre>';
        } catch (ClientException $e) {
            // Do whatever you want, function below contains exact JSON output from Telegram
            echo 'Exception catched, error is: <pre>';
            print_r(json_decode((string)$e->getResponse()->getBody()));
            echo '</pre>';
        }

ps: I'm using ngrok for testing.

Miscellaneous changes in the API

More power to admin bots

  • unbanChatMemeber now also works in channels!
  • New method deleteMessage that allows the bot to delete its own messages, as well as messages posted by other in groups and channels where the bot is an administrator.

Minor Changes

  • Replaced the field new_chat_member in Message with new_chat_members (the old field will still be available for a while for compatibility purposes).
  • Inline keyboards with switch_inline_query and switch_inline_query_current_chat can no longer be sent to channels because they are useless there.
  • New fields gif_duration in InlineQueryResultGif and mpeg4_duration in InlineQueryResultMpeg4Gif.

New namespace

Right now, the namespace does not have the name of the project in it, which is pretty uncomfortable when working with more packages of the same author. Change this.

LabeledPrice array must be json-encoded in SendInvoice method

Subj.
It's not obvious that array of LabeledPrice objects must be json_encode`d when passing to SendInvoice.

$invoice = new SendInvoice();
$price = new LabeledPrice( ['amount' => 100, 'label'=>'usd'] );
$invoice->prices = [ $price ];
...
$tg->performApiRequest( $invoice );

This code will result an error from Telegram API:
{"ok":false,"error_code":400,"description":"Bad Request: prices are not specified"}

To call this method successfully, we must json_encode "prices" parameter:

$invoice->prices = \GuzzleHttp\json_encode([ $price ]);

This way all working good.

I think the best solution would be some detection in SendInvoice: if data passed as array, encode data to json, else do nothing

PreCheckoutQuery doesnt morph `from` json string to object

It's me again with another issue, sorry ^^

print_r of PreCheckoutQuery received from Telegram API:

[19.06.2017 23:46:43] TgPay: PreCheckout query: unreal4u\TelegramAPI\Telegram\Types\PreCheckoutQuery Object
(
    [id] => 175373356413545972
    [from] => {"id":111111,"first_name":"222222","username":"123","language_code":"ru"}
    [currency] => USD
    [total_amount] => 100
    [invoice_payload] => 2222
    [shipping_option_id] =>
    [order_info] =>
    [logger:protected] => unreal4u\TelegramAPI\InternalFunctionality\DummyLogger Object
        (
        )

)

So, when trying to use from object, we are getting Trying to get property of non-object error

bot stops after 60 seconds.

Hi,
thank you for this sdk,
I have a messenger bot, and I must send a message at a time to more than 1000 records. It takes about 2 minutes.
But exactly after 60 seconds I receive the following message in the DirectAdmin log And posting will be unfinished.

Abort request processing by PID:440707, kill: 1, begin time: 61, sent time: 61, req processed: 1

And again, when the request from telegram is sent, it begins to send duplicate messages.
I will respond to the request by using the following code, and then I doing the pending_update_count to zero and the message does not repeat.

set_time_limit(600);
ignore_user_abort(true);
$out =  json_encode([
	'method'=>'sendMessage',
	'chat_id'=>$update->message->chat->id,
	'text'=> "Starting process..."
]);   
header('Connection: close');
header("Content-type:application/json");
ob_start();          
echo $out;   
header("Content-Length: ".ob_get_length(),TRUE);  
ob_end_flush();
ob_flush();
flush(); 
	
if (function_exists('fastcgi_finish_request')) {
	fastcgi_finish_request();
}  

But after 60 seconds, I still get the previous error message and Sends will be stop.
I do not know why it's still stopping. Do you know the solution?
Thank you
Peyman

Fatal error on Update

When the Update contains a new Object type, the following fatal is given:

PHP message: PHP Fatal error:  Uncaught TypeError: Return value of unreal4u\TelegramAPI\Abstracts\TelegramTypes::mapSubObjects() must be an instance of unreal4u\TelegramAPI\Abstracts\TelegramTypes, null returned in /.../vendor/unreal4u/telegram-api/src/Abstracts/TelegramTypes.php:71
Stack trace:
#0 /.../vendor/unreal4u/telegram-api/src/Telegram/Types/Message.php(267): unreal4u\TelegramAPI\Abstracts\TelegramTypes->mapSubObjects('new_chat_member', Array)

In the case of this particular one, it was because new_chat_participant and left_chat_participant changed to new_chat_member and left_chat_member respectively (In Bot API 2.0)

Update README

Update README with the latest changes.

Items to look out for:

  • Link to latest blog post
  • About this class section (add new content)
  • Installation: version constraint
  • Basic usage: this must always work

Inline bots support

It would be nice to have inline bots support, introduced in January 2016 in the Telegram API

Async Requests

Followup of #7

Enable async requests via Guzzle (or even better, per PSR definition)

Unable to send photos!

Hello
I use this bot sdk and I found it very useful, but the problem that I faced is that I couldn't send most of photos with the help of "SendPhoto()"!
It seems that everything is OK except for the mentioned method.
I cannot send Images even as document!

This is the Exception message:

Exception unreal4u\TelegramAPI\Exceptions\ClientException caught, message: An error occurred in the underlying stream

Greetings

new fields until_date, can_* to the ChatMember object

Added the new fields until_date, can_be_edited, can_change_info, can_post_messages, can_edit_messages, can_delete_messages, can_invite_users, can_restrict_members, can_pin_messages, can_promote_members, can_send_messages, can_send_media_messages, can_send_other_messages and can_add_web_page_previews to the ChatMember object.

Roadmap for 2.* and 3.*

Hi!

Could you please point me to your lifecycle roadmap of of 2.* and 3.* versions? I'm happy with v2 and do not plan to upgrade in the nearest future. About 5 projects use second version... So it would be nice to know what to expect in next 365 days :)

Inject a PSR compatible client

At this moment, Guzzle is a dependency of the project. This has to change so that we inject a PSR-7 compatible client to the app.

Android telegram client scroll down after callback

Hi! I have some problems with android telegram client. If I send a message with a link and callback button for this message, after press callback button client app force scroll down to the end of bot conversation.

This reproduce only in android client and only if a message has a link and callback button.

Maybe anyone one knows what I can do with this?

Strange issue: Class 'unreal4u\TelegramAPI\Telegram\Types\SuccessFulPayment' not found

Hello!

I have strange issue with payments API: after successfull payment, when Telegram sends to bot message of the type successful_payment , i have following error:

Unhandled error occured on face1!

Class 'unreal4u\TelegramAPI\Telegram\Types\SuccessFulPayment' not found
/var/www/tg-dev/vendor/unreal4u/telegram-api/src/Telegram/Types/Message.php:313

But i cannot fastly find any problems, all files, classes & namespaces seems to be ok...

Better unit tests & improve code coverage

Now that we can inject an HTTP client, improve the tests so that it doesn't need a mockup anymore.

Also, try to at least test 80% of all the codebase and functionality.

Error on the "Getting updates via Webhook" wiki page

use \unreal4u\TelegramAPI\Telegram\Types\Update;

$update = new Update($_POST);

It does not work because Telegram webhook servers are sending data using JSON-serialized POST body (not plain parameters).

There are two mutually exclusive ways of receiving updates for your bot — the getUpdates method on one hand and Webhooks on the other. Incoming updates are stored on the server until the bot receives them either way, but they will not be kept longer than 24 hours.
Regardless of which option you choose, you will receive JSON-serialized Update objects as a result.

So one of the simpliest examples must look like that:

use \unreal4u\TelegramAPI\Telegram\Types\Update;

$data = json_decode(file_get_contents('php://input'), true);

$update = new Update($data);

Correct me if I'm wrong, please.

Async Guzzle

What do you think about async Guzzle for send multi message?

`EditMessageCaption` may return multiple values

Since the May update (Bot API 2.1), it is possible to edit messages for bots. However, this one method can return a boolean true in some circumstances or a Message object in others. Check how we can solve this particular situation.

Logger integration

Logger integration will mean that this package will be capable to log relevant actions and write them in a standard psr/log fashioned way. If you require debug information because something is not going like it should, you can pass on a different Handler to display this information.

reading promise

hey,

thanks for great code, but i could not read value by

        $output = $getChatMembersCountPromise->then(
            function (ResultInt $getChatMembersCountResponse) {
               return $getChatMembersCountResponse;
                
            },
            function (ClientException $e) {
                return $e->getError();
            }
        );

return $output

but when i add echo its work fine but wont assaign it to any variable

any help ?

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.