Giter Site home page Giter Site logo

irazasyed / telegram-bot-sdk Goto Github PK

View Code? Open in Web Editor NEW
2.9K 102.0 644.0 2.09 MB

πŸ€– Telegram Bot API PHP SDK. Lets you build Telegram Bots easily! Supports Laravel out of the box.

Home Page: https://telegram-bot-sdk.com

License: BSD 3-Clause "New" or "Revised" License

PHP 100.00%
telegram telegram-bot telegram-bot-sdk php laravel botkit chatbot bot bot-framework telegram-bot-api

telegram-bot-sdk's Introduction

Telegram Bot API PHP SDK

Join PHP Chat Chat on Telegram Build Status Latest Version Total Downloads

Telegram Bot API - PHP SDK

Telegram Bot PHP SDK lets you develop Telegram Bots in PHP easily! Supports Laravel out of the box.

Telegram Bot API is an HTTP-based interface created for developers keen on building bots for Telegram.

To learn more about the Telegram Bot API, please consult the Introduction to Bots and Bot FAQ on official Telegram site.

To get started writing your bots using this SDK, Please refer the documentation.

Supported Versions

Only the latest released version of the SDK is supported. To facilitate upgrades, we rarely make backward-incompatible changes.

Version Supported Documentation
2.x ❌ βœ… docs
3.x βœ… (current) 🚧 docs
4.x βœ… (in development) ❌

Documentation

Documentation for the SDK can be found on the website.

Are You Using Telegram Bot SDK?

If you're using this SDK to build your Telegram Bots or have a project that's relevant to this SDK, We'd love to know and share it with the world.

Head over to Awesome Telegram Bots to share, discover, and learn more.

Additional information

Any issues, feedback, suggestions or questions please use issue tracker here.

Contributing

Thank you for considering contributing to the project. Please review the CONTRIBUTING guidelines before submitting any pull requests.

Credits

Thanks

Thanks to these companies for providing access to their products that have been very useful in developing this SDK. Please go check them out!

1Password JetBrains

Disclaimer

This project and its author are neither associated nor affiliated with Telegram in any way. Please see the License for more details.

License

This project is released under the BSD 3-Clause License.

telegram-bot-sdk's People

Contributors

agelxnash avatar alexmorbo avatar alies-dev avatar alr2413 avatar autowp avatar dependabot-preview[bot] avatar dependabot[bot] avatar doctorlines avatar filipekiss avatar foremtehan avatar halaei avatar holtkamp avatar ihoru avatar imanghafoori1 avatar irazasyed avatar irpcpro avatar jonnywilliamson avatar kolirt avatar lptn avatar maizergomes avatar makkmarci13 avatar matthewnessworthy avatar mattiabasone avatar mihard avatar pavel-mironchik avatar rkhitin avatar romm avatar scrutinizer-auto-fixer avatar semsphy avatar sloothword 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  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-bot-sdk's Issues

Magic _call method

In the BaseObject class file is this:

    public function __call($name, $arguments)
    {
        $action = substr($name, 0, 3);

        if ($action === 'get') {
            $property = snake_case(substr($name, 3));
            $response = $this->get($property, false);

            if ($response) {
                // Map relative property to an object
                $relations = $this->relations();
                if (isset($relations[$property])) {
                    return new $relations[$property]($response);
                }

                return $response;
            }

            throw new TelegramUndefinedPropertyException();
        }

        return false;
    }

Does the $arguments parameter have any use? I can't see it being used, but I just wanted to check.

Which method is use to send messages?

Hello
i recently had a bug , i suppose this sdk use Get method to send text messaged to telegram api, right ?
when i try to send a big message a message pops up about :
{"\r\n<title>414_Request-URI_Too_Large</title></head>\r\n<body_bgcolor":""white">\r\n

414 Request-URI Too Large</h1></center>\r\n
nginx/1.6.2</center>\r\n</body>\r\n</html>\r\n"}
is there a way to use Post instead of Get ?

Problem in setting up web hook at Telegram

I've designed a robot for Telegram.
After setting up web hook and sending messages to this robot, the robot response me as repetitious, as if the response of robot is on loop.
My code is simple, but I don’t know why telegram sends duplicate massages for my web hook.

command detection

Imagine my username's bot is "something_bot".

when a command receives like that:
/start
StartCommand triggered.

and when this command receives
/start@something_bot
again StartCommand triggered.

and bug is here:
when
/start@ANOTHER_bot
receives StartCommand triggered, the command is not for my bot.

utf-8 !!!

I get this error for many times:

Telegram\Bot\Exceptions\TelegramResponseException
[Error]: Bad Request: text must be in utf-8

request:

{"update_id":1111,"message":{"message_id":1111,"from":{"id":1111,"first_name":"xxx"},"chat":{"id":1111,"first_name":"xxx","type":"private"},"date":1449401679,"text":"1. \u06a9\u0627\u0646\u0627\u0644"}}

I provide this by keyboard, if you choose one of buttons, it return this error and if you push the same button again it works!

This error just did not occur on version 1.0

Store telegram user's chat_id in my database

For first i need to say: Great job man!

It look like works... only one difficult to understand what exactly is a "webhook" and so...

HOW I could easy store the chat_id of a telegram user in the database of my app... it will be fantastic that it appen only by pressing a button.

Thank a lot!

Manually executing commands

Currently doing this:
$api = new Api(TELEGRAM_API_KEY);
// let's assume CustomCommand has been implemented and works through Telegram App
$api->addCommand(MINE\Bot\Commands\CustomCommand::class);
$updates = $api->getWebhookUpdates();

// command is passed without prefixed '/'
$api->getCommandBus()->execute('customcommand', 'string of arguments', $updates);

CustomCommand works on its own via telegram app with the exact 'string of arguments'
but when called manually in the above manner, it does not respond in the same manner given the same arguments

Also tried the following:
$api->getCommandBus()->handler('/customcommand string of arguments', $updates);
Without any success

There is some confusion between API->getWebhookUpdates() which returns Update object
and API->getUpdates() which returns array of Update objects
but this is minor.

What could I be doing wrong?

[WIP] Add Conversational System

I have plans to create a system with which, we can build a Q/A kinda interactive bots easily.

Since the commands system is not designed to handle this nor it was intended to do that, A separate functionality makes sense.

The only part that's quite complex is to track the answers/responses and to map it to the right question and then move to next in a queue.

Any inputs would be good.

"[Error]: Photo has unsupported extension", for remote files.

Was testing the support for remote files added in 67e17a5 and got an error [Error]: Photo has unsupported extension.

$tg = new Api($telegram_token);
$img_url = 'https://www.instagram.com/p/-kfo63BQes/media/?size=l';
$response = $tg->sendPhoto(
    array('chat_id' => $chat_id
        , 'photo' => $img_url
        , 'caption' => $my_caption)
);

This can be worked around by artificially adding a fake param x=.jpg making it
$img_url = 'https://www.instagram.com/p/-kfo63BQes/media/?size=l&x=.jpg';

In my opinion, there shouldn't be file extension checks for remote files because an image/video url can be in any format.

Command matching bot username

In /Commands/CommandBus.php#L148
I'd like to change the regex for parsing commands
from:
preg_match('/^\/([^\s@]+)@?(\S+)?\s?(.*)$/', $text, $matches);
to:
preg_match('/^(?:\/|@)([^\s@]+)@?(\S+)?\s?(.*)$/i', $text, $matches);
so that @botusername_bot is also matched as a command This way any arguments can be parsed that are passed as @botusername_bot arg1 arg2.

Unless this is handled some other way?

Edit:
This works in a group. Ideally, when typing anything in a one-on-one session with the bot should also parse these arguments. Why else would you type anything directly to a bot? A request is coming in from telegram in both cases (@botName args in a group and any message with one-on-one). It just needs to be handled somehow.

error when using webhook

Hi,
i've a problem with the telegram-bot-sdk.
When i activate webhook i've the following error in my php:
Fatal error: Call to a member function has() on a non-object in Api.php on line 681
The code is:
$message = $update->getMessage();
if ($message->has('text'))

I've PHP Version 5.5.9.
Thank you.
Massimiliano

PHP Fatal error: Uncaught exception

aue@aaak:~/telegram-bot-sdk# php stest.php 
PHP Fatal error:  Uncaught exception 'Irazasyed\Telegram\Exceptions\TelegramUndefinedPropertyException' in /aue/telegram-bot-sdk/src/Objects/BaseObject.php:144
Stack trace:
#0 /aue/telegram-bot-sdk/stest.php(13): Irazasyed\Telegram\Objects\BaseObject->__call('getLastName', Array)
#1 /aue/telegram-bot-sdk/stest.php(13): Irazasyed\Telegram\Objects\User->getLastName()
#2 {main}
  thrown in /aue/telegram-bot-sdk/src/Objects/BaseObject.php on line 144
aue@aaak:~/telegram-bot-sdk# cat stest.php 
<?php

$loader = require __DIR__.'/vendor/autoload.php';

use Irazasyed\Telegram\Telegram;

$telegram = new Telegram('XX:XX');

$response = $telegram->getMe();

$botId = $response->getId();
$firstName = $response->getFirstName();
$lastName = $response->getLastName();
$username = $response->getUsername();

echo $botId . ' ' . $firstName . ' ' . $lastName . ' ' . $username;

One time keyboard may not be working correctly.

Hi there,

This package is just fantastic. I have it working really well at the moment. Just noticed one thing that I'm not sure is actually broken but I'll run it past you.

The official docs state:

github

So in my mind, you should receive a message, when you go to reply, the custom keyboard appears and you can select your option but then the keyboard is GONE and doesn't come back.

When I try this code:

    $keyboard = [
        ['Yes', 'No', 'Maybe'],
        ["I'm Not Sure", 'Can You'],
        ['Repeat the question?']
    ];

$response = Telegram::sendMessage('<myid>', 'Hello!', false, null, Telegram::replyKeyboardMarkup($keyboard, true, true, false));

I get my message perfectly and the custom keyboard pops up:

2015-07-18 16 00 18

However when I press my reply, the custom keyboard icon doesn't disappear:

2015-07-18 16 00 26

Pressing on this icon brings up the custom keyboard all the time.

The only way to remove the custom keyboard is to send a new message with

    $response = Telegram::sendMessage('<myid>', 'Just removing the keyboard', false, null, Telegram::replyKeyboardHide());

Now instantly it disappears:

2015-07-18 16 00 58

Is this intentional or is there a bug with how the one-time-keyboard should work?

Add the ability to send markdown messages

Telegram has added an option to send markdown formatted messages passing Markdown as parse_mode when sending a message, as seen here. I couldn't seem to find how to use this option.

send automatic message for all user and group with telegram bot

i want put a part in my bot that when user want from my bot send new data automatic (with link or command for active this)
when i put a new record in my table of database my bot send this new record in message for all user that want give this data automatic
it is my work that i will do it
and now my question is:
telegram bot has function or part for manage this work
or
i should get user_id when active this part and save id in the table and when i create new record i send new message for all user that i save the id in the table and do this work with programming?

Token contstructor required

public function __construct($token, $async = false, $http_client_handler = null)
$this->accessToken = isset($token) ? $token : getenv(static::BOT_TOKEN_ENV_NAME);

maybe use
public function __construct($token = null, $async = false, $http_client_handler = null)?

Async Requests not working

Hi, I was trying to use asynchronous requests using the following setup:

-Windows 7 64 Bit
-PHP 5.6.3 (32 Bit)
-Telegram Bot SDK 0.2.4
-Guzzle 6.0.2

Plain sending messages using this

$telegram->setAsyncRequest(true)
    ->sendMessage($message->get('chat')->get('id'), 'Test');

does not work although requests without async do work. I don't know if this is Windows related.
There is no error message nor exception, there is just nothing being sent to the Telegram server.

With best regards,

Stefan Hueg

I am totally new to Laravel

I am totally new to Laravel frame work ! I know this issue is because of that ! but PLZ help Me !
I do not know how to add this Packege in Providers ! Actually I have done steps and I have telegram.php in config folder now ! but I am getting this Err :

Undefined variable: telegram

while I want test my bot like this :
echo $response = $telegram->getMe();

Suddenly webhook stopped working

Hello
I applyed webhook in my telegram bot and it was working fine. SSL provided by claudeflare.
But suddenly some hours later, it stopped.
Everything was OK. But now just Long Polling is working and not Webhook.
Do you have any idea?
Thanks in advance

[request] SendPhoto from URL

Actually your API support only the official method (upload a local file OR reference a file_id).

But automatically handling URL (so submitting as multipart data) can be really useful.

Thank you for your work!!

Get user and group sender of command

Hi,

As far as I have read, it's not possible to get the group or the user from which a command has been sent, it would be useful for "private" bots, or user systems.

what do you think?

webhook issue

hi
i'm using the standalone without laravel.
I have a page called notifer.php this is where my webhook is set to.
I have this code in it :
require 'vendor/autoload.php';

use Telegram\Bot\Api;
$telegram = new Api('token');

$updates = $telegram->getWebhookUpdates();

var_dump($updates) ;

when i visit notifer.php in browser it returns this : object(Telegram\Bot\Objects\Update)#18 (1) { ["items":protected]=> array(0) { } }

[Todo] Add Commands Handler System

A system to handle and process commands automatically. Maybe like Laravel's command bus.

So when a new message arrives through a webhook or when manually getting updates, Make it easy to process such messages if they're commands.

determining setWebhook result

Sorry if this is wrong place but I cannot find any other place to ask questions.

I am trying to use setWebhook to register my web hook url and upload a self-signed certificate but running into issues:

I use setWebhook($url, $cert) where $url is https://mydomain/webhook/sometoken and $cert is inputFile resource ( i also tried with only filename which also seems acceptable and handled appropriately).

A dump of the return I get is this:
object(Telegram\Bot\Objects\Message)#187 (1) { ["items":protected]=> array(1) { [0]=> bool(true) } }

What does this mean? Did it fail? It does not work as there are no incoming requests to my server when I trigger it with /start from a client.

The webhook did register because when I do a manual getUpdates() it complains that web hook is already present. If I remove the webhook I get a nice return from removeWebhook() and using getUpdates() manually thereafter works fine.

So my question is how do I figure out what the problem is? The url is correct, I've double checked it. I don't think the certificate is a problem as there is no entry in Apache access log of a request from Telegram.

Thanks.

Class not found

Hi,
Can you please explain in details how to install it?
What paths should I work in? is it public_html or root?
No matter what I did, I'm always facing this error:
Fatal error: Class 'Irazasyed\Telegram\Telegram' not found in /home/XXXX/public_html/tele.php on line 5

Usage of commands

Hi;
Thanks for this cool program. πŸ‘
I used your startCommand sample code in a file named startCommand and saved this into commands folder.
Either I did write $telegram->commandsHandler(true);

But

When I use /start command in my telegram app, nothing gonna happen.

This is my webhook file structure.

_Note :_ The commented lines was tested.

require 'vendor/autoload.php';

use Telegram\Bot\Api;

$telegram = new Api('123456:AASxty3ydXux3yeCYEobGNFDefzT-fLUZXE');

$telegram->commandsHandler(true);


//$startCommand = new \Telegram\Bot\Commands\startCommand;

//$startCommand->handle('');

//\Telegram\Bot\Commands\startCommand::handle('');

Would you please tell me where's my fault and misunderstanding?

Thanks in advance

Your code has been copied and license violated.

Hi,

I came across this repository recently: https://github.com/mgp25/Telegram-Bot-API

And i noticed, the guy copied maximum of your methods/functions including complete documentation and other things and as per your license, It seems like a clear case of violation since he doesn't even bother to give proper credit or follow the license.

I informed him too but he doesn't seem to bother and defends himself.

Just thought I'd give heads up as being a developer myself, I know the value of ones work and time! Also, It's never a good idea to steal someones work and take credits.

getFile

$telegram = new Api(config('telegram.bot_token'));
$files = $telegram->getFile($fileId);

make error below:
Argument 3 passed to Telegram\Bot\Api::sendRequest() must be of the type array, string given, called in .../vendor/irazasyed/telegram-bot-sdk/src/Api.php on line 715 and defined

sendVideo Actually accepts caption field

Hi,

The official docs show that you can send a caption with sendMessage.

There is no mention of being able to send a caption with sendVideo, however when you actually send a video in a normal client (ie iOS app, desktop etc) you CAN set a caption.

I have added the caption variable to the sendVideo method in your library and surprise surprise it works perfectly.....but it seems like it was missed when they wrote the documents on the official Telegram site.

Would you accept a PR with this added or do you prefer to keep you library in strict adherence to the official docs?

keyboard doesn't work!

$keyboard = $telegram->replyKeyboardMarkup([['test']]);
$params = [
'chat_id' => $chatId,
'text' => $text,
'reply_markup' => $keyboard,

 ];

return $telegram->sendMessage($params);

keyboard dose not work!

"Message not supported" when replying with document

I'm trying to build an bot that will use the giphy API for getting a random gif for the supplied keyword, but I can't get the gifs to work in Telegram. I know it's possible because other bots are doing it.
When I use the replyWithPhoto it end up showing a static photo of the gif, after some searching I read that you should send gifs as document, but when I use replyWithDocument I get a message in telegram that says

The message is not supported on your version of Telegram Web. Update the app to view: web.telegram.org.

Ofcourse I am using the latest version of Telegram.

I have a feeling that it's caused by a wrong MIME type but I have no idea how to change that.
This is the code I am using for the command:

<?php

namespace App\Commands;

use Telegram\Bot\Actions;
use Telegram\Bot\Commands\Command;

class GiphyCommand extends Command
{
    /**
     * @var string Command Name
     */
    protected $name = "giphy";

    /**
     * @var string Command Description
     */
    protected $description = "Post a random GIF";

    /**
     * @inheritdoc
     */
    public function handle($arguments)
    {
        $this->replyWithDocument(['document' => 'http://media2.giphy.com/media/FiGiRei2ICzzG/giphy.gif']);
    }
}

Any idea what is causing this?

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.