README.md 14.4 KB
Newer Older
LONGMAN's avatar
LONGMAN committed
1 2
# PHP Telegram Bot

3
[![Join the chat at https://gitter.im/akalongman/php-telegram-bot](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/akalongman/php-telegram-bot?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
LONGMAN's avatar
LONGMAN committed
4

LONGMAN's avatar
LONGMAN committed
5
[![Build Status](https://travis-ci.org/akalongman/php-telegram-bot.svg?branch=master)](https://travis-ci.org/akalongman/php-telegram-bot)
6
[![Latest Stable Version](https://img.shields.io/packagist/v/Longman/telegram-bot.svg)](https://packagist.org/packages/longman/telegram-bot)
LONGMAN's avatar
LONGMAN committed
7 8
[![Total Downloads](https://img.shields.io/packagist/dt/Longman/telegram-bot.svg)](https://packagist.org/packages/longman/telegram-bot)
[![Downloads Month](https://img.shields.io/packagist/dm/Longman/telegram-bot.svg)](https://packagist.org/packages/longman/telegram-bot)
9
[![License](https://img.shields.io/packagist/l/Longman/telegram-bot.svg)](https://github.com/akalongman/php-telegram-bot/LICENSE.md)
LONGMAN's avatar
LONGMAN committed
10 11


12
A Telegram Bot based on the official [Telegram Bot API](https://core.telegram.org/bots/api)
LONGMAN's avatar
LONGMAN committed
13 14


15 16 17
## Introduction

This is a pure PHP Telegram Bot, fully extensible via plugins.
MBoretto's avatar
MBoretto committed
18 19 20
Telegram recently announced official support for a [Bot
API](https://telegram.org/blog/bot-revolution) allowing integrators of
all sorts to bring automated interactions to the mobile platform. This
21
Bot aims to provide a platform where one can simply write a plugin
MBoretto's avatar
MBoretto committed
22
and have interactions in a matter of minutes.
23

24
The Bot can:
25
- retrieve updates with webhook and getUpdate methods.
MBoretto's avatar
MBoretto committed
26
- supports all types and methods according to Telegram API (20 January 2016).
MBoretto's avatar
MBoretto committed
27
- supports supergroups.
MBoretto's avatar
MBoretto committed
28
- handle commands in chat with other bots.
29 30 31 32 33 34 35
- manage Channel from the bot admin interface.
- full support for **inline bots**. (**new!**)
- Messages, InlineQuery and ChosenInlineQuery are stored in the Database. (**new!**)

-----
This code is available on
[Github](https://github.com/akalongman/php-telegram-bot). Pull requests are welcome.
LONGMAN's avatar
LONGMAN committed
36

MBoretto's avatar
MBoretto committed
37
## Instructions
38

MBoretto's avatar
MBoretto committed
39
### Create your first bot
LONGMAN's avatar
LONGMAN committed
40

MBoretto's avatar
MBoretto committed
41 42 43
1. Message @botfather https://telegram.me/botfather with the following
text: `/newbot`
   If you don't know how to message by username, click the search
44
field on your Telegram app and type `@botfather`, where you should be able
MBoretto's avatar
MBoretto committed
45 46
to initiate a conversation. Be careful not to send it to the wrong
contact, because some users has similar usernames to `botfather`.
LONGMAN's avatar
LONGMAN committed
47

LONGMAN's avatar
LONGMAN committed
48
   ![botfather initial conversation](http://i.imgur.com/aI26ixR.png)
LONGMAN's avatar
LONGMAN committed
49

MBoretto's avatar
MBoretto committed
50 51
2. @botfather replies with `Alright, a new bot. How are we going to
call it? Please choose a name for your bot.`
LONGMAN's avatar
LONGMAN committed
52 53 54

3. Type whatever name you want for your bot.

55
4. @botfather replies with ```Good. Now let's choose a username for your
MBoretto's avatar
MBoretto committed
56
bot. It must end in `bot`. Like this, for example: TetrisBot or
57
tetris_bot.```
LONGMAN's avatar
LONGMAN committed
58

MBoretto's avatar
MBoretto committed
59 60
5. Type whatever username you want for your bot, minimum 5 characters,
and must end with `bot`. For example: `telesample_bot`
LONGMAN's avatar
LONGMAN committed
61 62 63

6. @botfather replies with:

64
    ```
MBoretto's avatar
MBoretto committed
65
    Done! Congratulations on your new bot. You will find it at
66 67 68
    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.
LONGMAN's avatar
LONGMAN committed
69 70

    Use this token to access the HTTP API:
71
    123456789:AAG90e14-0f8-40183D-18491dDE
LONGMAN's avatar
LONGMAN committed
72

MBoretto's avatar
MBoretto committed
73
    For a description of the Bot API, see this page:
74 75
    https://core.telegram.org/bots/api
    ```
LONGMAN's avatar
LONGMAN committed
76 77 78 79 80

7. Note down the 'token' mentioned above.

8. Type `/setprivacy` to @botfather.

LONGMAN's avatar
LONGMAN committed
81
   ![botfather later conversation](http://i.imgur.com/tWDVvh4.png)
LONGMAN's avatar
LONGMAN committed
82 83 84

9. @botfather replies with `Choose a bot to change group messages settings.`

85
10. Type (or select) `@telesample_bot` (change to the username you set at step 5
MBoretto's avatar
MBoretto committed
86
above, but start it with `@`)
LONGMAN's avatar
LONGMAN committed
87 88 89

11. @botfather replies with

90 91
    ```
    'Enable' - your bot will only receive messages that either start with the '/' symbol or mention the bot by username.
LONGMAN's avatar
LONGMAN committed
92 93
    'Disable' - your bot will receive all messages that people send to groups.
    Current status is: ENABLED
94
    ```
LONGMAN's avatar
LONGMAN committed
95

96
12. Type (or select) `Disable` to let your bot receive all messages sent to a
MBoretto's avatar
MBoretto committed
97
group. This step is up to you actually.
LONGMAN's avatar
LONGMAN committed
98 99 100

13. @botfather replies with `Success! The new status is: DISABLED. /help`

MBoretto's avatar
MBoretto committed
101
### Require this package with Composer
102

MBoretto's avatar
MBoretto committed
103 104 105
Install this package through [Composer](https://getcomposer.org/).
Edit your project's `composer.json` file to require
`longman/telegram-bot`.
LONGMAN's avatar
LONGMAN committed
106

107
Create *composer.json* file
LONGMAN's avatar
LONGMAN committed
108 109 110 111 112
```js
{
    "name": "yourproject/yourproject",
    "type": "project",
    "require": {
LONGMAN's avatar
LONGMAN committed
113
        "php": ">=5.5.0",
LONGMAN's avatar
LONGMAN committed
114 115 116 117
        "longman/telegram-bot": "*"
    }
}
```
118
and run `composer update`
LONGMAN's avatar
LONGMAN committed
119

120 121 122
**or**

run this command in your command line:
LONGMAN's avatar
LONGMAN committed
123 124 125 126

```
composer require longman/telegram-bot
```
LONGMAN's avatar
LONGMAN committed
127

MBoretto's avatar
MBoretto committed
128
### Choose how to retrieve Telegram updates
129

MBoretto's avatar
MBoretto committed
130
The bot can handle updates with **webhook** or **getUpdate** method:
LONGMAN's avatar
LONGMAN committed
131

132
|      | Webhook | getUpdate |
MBoretto's avatar
MBoretto committed
133
| ---- | :----: | :----: |
134
| Description | Telegram sends the updates directly to your host | You have to fetch Telegram updates manually |
MBoretto's avatar
MBoretto committed
135
| Host with https | Required | Not required |
136 137
| MySQL | Not required | Required  |

LONGMAN's avatar
LONGMAN committed
138

MBoretto's avatar
MBoretto committed
139
## Webhook installation
140 141 142 143

In order to set a [Webhook](https://core.telegram.org/bots/api#setwebhook) you need a server with https and composer support.
(For a [self signed certificate](#self-signed-certificate) you need to add some extra code)

144
Create *set.php* (or just copy and edit *examples/set.php*) and put into it:
LONGMAN's avatar
LONGMAN committed
145 146
```php
<?php
147 148
// Load composer
require __DIR__ . '/vendor/autoload.php';
LONGMAN's avatar
LONGMAN committed
149

LONGMAN's avatar
LONGMAN committed
150
$API_KEY = 'your_bot_api_key';
151
$BOT_NAME = 'namebot';
152
$hook_url = 'https://yourdomain/path/to/hook.php';
LONGMAN's avatar
LONGMAN committed
153
try {
154
    // Create Telegram API object
LONGMAN's avatar
LONGMAN committed
155
    $telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME);
156 157 158

    // Set webhook
    $result = $telegram->setWebHook($hook_url);
MBoretto's avatar
MBoretto committed
159 160 161
    if ($result->isOk()) {
        echo $result->getDescription();
    }
LONGMAN's avatar
LONGMAN committed
162
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
163
    echo $e;
LONGMAN's avatar
LONGMAN committed
164
}
LONGMAN's avatar
LONGMAN committed
165
```
166

167
Open your *set.php* via the browser to register the webhook with Telegram.
LONGMAN's avatar
LONGMAN committed
168

169
Now, create *hook.php* (or just copy and edit *examples/hook.php*) and put into it:
LONGMAN's avatar
LONGMAN committed
170 171
```php
<?php
172 173
// Load composer
require __DIR__ . '/vendor/autoload.php';
LONGMAN's avatar
LONGMAN committed
174

LONGMAN's avatar
LONGMAN committed
175
$API_KEY = 'your_bot_api_key';
176
$BOT_NAME = 'namebot';
LONGMAN's avatar
LONGMAN committed
177
try {
178
    // Create Telegram API object
MBoretto's avatar
MBoretto committed
179
    $telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME);
180

181
    // Handle telegram webhook request
LONGMAN's avatar
LONGMAN committed
182 183
    $telegram->handle();
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
184
    // Silence is golden!
LONGMAN's avatar
LONGMAN committed
185
    // log telegram errors
186
    // echo $e;
LONGMAN's avatar
LONGMAN committed
187
}
LONGMAN's avatar
LONGMAN committed
188
```
189

190 191 192
### Self Signed Certificate

To upload the certificate, add the certificate path as a parameter in *set.php*:
193
```php
194
$result = $telegram->setWebHook($hook_url, $certificate_path);
195 196
```

197 198 199 200
### Unset Webhook

Edit *example/unset.php* with your bot credentials and execute it.

201
## getUpdate installation
LONGMAN's avatar
LONGMAN committed
202

203 204 205
The MySQL database must be active!

Create *getUpdateCLI.php* (or just copy and edit *examples/getUpdateCLI.php*) and put into it:
MBoretto's avatar
MBoretto committed
206
```php
MBoretto's avatar
MBoretto committed
207 208
#!/usr/bin/env php
<?php
209
require __DIR__ . '/vendor/autoload.php';
MBoretto's avatar
MBoretto committed
210 211 212

$API_KEY = 'your_bot_api_key';
$BOT_NAME = 'namebot';
213 214 215 216 217 218
$mysql_credentials = [
   'host'     => 'localhost',
   'user'     => 'dbuser',
   'password' => 'dbpass',
   'database' => 'dbname',
];
MBoretto's avatar
MBoretto committed
219 220

try {
221
    // Create Telegram API object
MBoretto's avatar
MBoretto committed
222
    $telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME);
223 224 225 226 227

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

    // Handle telegram getUpdate request
MBoretto's avatar
MBoretto committed
228 229 230
    $telegram->handleGetUpdates();
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
    // log telegram errors
231
    echo $e;
232
}
MBoretto's avatar
MBoretto committed
233
```
MBoretto's avatar
MBoretto committed
234

235
give the file permission to execute:
MBoretto's avatar
MBoretto committed
236 237 238 239 240 241 242
```
chmod 775 getUpdateCLI.php
```
then run
```
./getUpdateCLI.php
```
MBoretto's avatar
MBoretto committed
243

244 245 246
## Support

### Types
247 248 249 250 251

All types are implemented according to Telegram API (20 January 2016).

### Inline Query

MBoretto's avatar
MBoretto committed
252
Full support for inline query according to Telegram API (20 January 2016).
253

MBoretto's avatar
MBoretto committed
254 255
### Methods

256 257 258 259 260
All methods are implemented according to Telegram API (20 January 2016).

#### Send Message

Messages longer than 4096 characters are split up into multiple messages.
MBoretto's avatar
MBoretto committed
261 262 263 264 265

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

266 267 268
#### Send Photo

To send a local photo, provide the file path as the second parameter:
269 270

```php
271 272
$data = ['chat_id' => $chat_id];
$result = Request::sendPhoto($data, $telegram->getUploadPath() . '/image.jpg');
273 274
```

275
If you know the `file_id` of a previously uploaded file, just include it in the data array:
MBoretto's avatar
MBoretto committed
276 277

```php
278 279 280 281
$data = [
    'chat_id' => $chat_id,
    'photo'   => $file_id,
];
MBoretto's avatar
MBoretto committed
282 283 284
$result = Request::sendPhoto($data);
```

285
*sendAudio*, *sendDocument*, *sendSticker*, *sendVideo* and *sendVoice* all work in the same way.
286
See *examples/Commands/ImageCommand.php* for a full example.
287 288

#### Send Chat Action
MBoretto's avatar
MBoretto committed
289 290 291 292 293

```php
Request::sendChatAction(['chat_id' => $chat_id, 'action' => 'typing']);
```

294 295
#### getUserProfilePhoto

296
Retrieve the user photo, see *src/Commands/WhoamiCommand.php* for a full example.
297 298 299

#### getFile and dowloadFile

300
Get the file path and download it, see *src/Commands/WhoamiCommand.php* for a full example.
MBoretto's avatar
MBoretto committed
301

MBoretto's avatar
MBoretto committed
302
#### Send message to all active chats
303 304

To do this you have to enable the MySQL connection.
MBoretto's avatar
MBoretto committed
305 306 307
Here's an example of use:

```php
308 309 310 311 312 313 314
$results = Request::sendToActiveChats(
        'sendMessage', // callback function to execute (see Request.php for available methods)
        ['text' => 'Hey! Check out the new features!!'], // Data to pass to the request
        true, // Send to chats (group chat)
        true, // Send to chats (super group chat)
        true, // Send to users (single chat)
        null, // 'yyyy-mm-dd hh:mm:ss' date range from
315
        null, // 'yyyy-mm-dd hh:mm:ss' date range to
MBoretto's avatar
MBoretto committed
316 317
    );
```
MBoretto's avatar
MBoretto committed
318

319
You can also broadcast a message to users, from the private chat with your bot. Take a look at the [admin commands](#admin-commands) below.
320 321

## Utils
LONGMAN's avatar
LONGMAN committed
322

323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
### MySQL storage (Recommended)

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

```php
$mysql_credentials = [
   'host'     => 'localhost',
   'user'     => 'dbuser',
   'password' => 'dbpass',
   'database' => 'dbname',
];

$telegram->enableMySQL($mysql_credentials);
MBoretto's avatar
MBoretto committed
338
```
339
You can set a custom prefix to all the tables while you are enabling MySQL:
340 341

```php
342
$telegram->enableMySQL($mysql_credentials, $BOT_NAME . '_');
343
```
344

MBoretto's avatar
MBoretto committed
345
Consider to use the *utf8mb4* branch if you find some special characters problems.
MBoretto's avatar
MBoretto committed
346
You can also store inline query and chosen inline query in the database.
347 348 349 350

### Channels Support

All methods implemented can be used to manage channels.
351
With [admin commands](#admin-commands) you can manage your channel directly with your bot private chat.
352

MBoretto's avatar
MBoretto committed
353
### Commands
354 355

The bot is able to recognise commands in a chat with multiple bots (/command@mybot).
356 357
It can execute command triggering a chat event. Here's the list:

MBoretto's avatar
MBoretto committed
358 359
- New chat participant (**NewchatparticipantCommand.php**)
- Left chat participant (**LeftchatparticipantCommand.php**)
MBoretto's avatar
MBoretto committed
360 361 362 363 364
- New chat title (**NewchattitleCommand.php**)
- Delete chat photo (**DeletechatphotoCommand.php**)
- Group chat created (**GroupchatcreatedCommand.php**)
- Super group chat created (**SupergroupchatcreatedCommand.php**)
- Channel chat created (**ChannelchatcreatedCommand.php**)
MBoretto's avatar
MBoretto committed
365 366 367
- Inline query (**InlinequeryCommand.php**)
- Chosen inline result (**ChoseninlineresultCommand.php**)

368
**GenericCommand.php** lets you handle commands that don't exist or to
MBoretto's avatar
MBoretto committed
369
use commands as a variable:
370

MBoretto's avatar
MBoretto committed
371
Favourite colour? **/black, /red**
372

MBoretto's avatar
MBoretto committed
373
Favourite number? **/1, /134**
MBoretto's avatar
MBoretto committed
374

375
**GenericmessageCommand.php** lets you handle any type of message.
MBoretto's avatar
MBoretto committed
376

MBoretto's avatar
MBoretto committed
377
Maybe you would like to develop your own commands. A good practice is
378
to store them outside *vendor/*. This can be done using:
MBoretto's avatar
MBoretto committed
379

MBoretto's avatar
MBoretto committed
380
```php
381 382
$commands_folder = __DIR__ . '/Commands/';
$telegram->addCommandsPath($commands_folder);
383 384
```

385
Inside *examples/Commands/* there are some samples that show how to use types.
MBoretto's avatar
MBoretto committed
386

MBoretto's avatar
MBoretto committed
387
#### Commands Configuration
388 389

With this method you can set some command specific parameters, for
MBoretto's avatar
MBoretto committed
390 391
example, google geocode/timezone api key for date command:
```php
MBoretto's avatar
MBoretto committed
392
$telegram->setCommandConfig('date', ['google_api_key' => 'your_google_api_key_here']);
MBoretto's avatar
MBoretto committed
393 394
```

395
### Admin Commands
396

397
Enabling this feature, the admin bot can perform some super user commands like:
MBoretto's avatar
MBoretto committed
398 399
- Send message to all chats */sendtoall*
- List all the chats started with the bot */chats*
MBoretto's avatar
MBoretto committed
400
- Send a message to a channel */sendtochannel* (NEW! see below how to configure it)
401
You can specify one or more admins with this option:
402

403
```php
404
$telegram->enableAdmins(['your_telegram_user_id', 'other_telegram_user_id']);
405
```
MBoretto's avatar
MBoretto committed
406 407
Telegram user id can be retrieved with the command **/whoami**.
Admin commands are stored in *src/Admin/* folder.
408 409 410
To get a list of all available commands, type **/help**.

#### Channel Administration
MBoretto's avatar
MBoretto committed
411

412
To enable this feature follow these steps:
MBoretto's avatar
MBoretto committed
413 414
- 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.
415
- Enter your channel name as a parameter for the */sendtochannel* command:
MBoretto's avatar
MBoretto committed
416
```php
417
$telegram->setCommandConfig('sendtochannel', ['your_channel' => '@type_here_your_channel']);
418
```
MBoretto's avatar
MBoretto committed
419 420 421
- Enjoy!

### Upload and Download directory path
422 423

You can override the default Upload and Download directory with:
424
```php
425 426
$telegram->setDownloadPath('yourpath/Download');
$telegram->setUploadPath('yourpath/Upload');
MBoretto's avatar
MBoretto committed
427
```
428

MBoretto's avatar
MBoretto committed
429
### Logging
430

431 432 433
Thrown Exceptions are stored in *TelegramException.log* file (in the base directory).

Incoming update (json string from webhook and getUpdates) can be logged in a text file. Set those options with the methods:
MBoretto's avatar
MBoretto committed
434
```php
435
$telegram->setLogRequests(true);
436
$telegram->setLogPath($BOT_NAME . '.log');
MBoretto's avatar
MBoretto committed
437
```
LONGMAN's avatar
LONGMAN committed
438

439
Set verbosity to 3 to also log curl requests and responses from the bot to Telegram:
MBoretto's avatar
MBoretto committed
440 441 442

```php
$telegram->setLogRequests(true);
443
$telegram->setLogPath($BOT_NAME . '.log');
444
$telegram->setLogVerbosity(3);
MBoretto's avatar
MBoretto committed
445 446
```

447
## Documentation
448

MBoretto's avatar
MBoretto committed
449 450 451
Take a look at the repo [Wiki](https://github.com/akalongman/php-telegram-bot/wiki) for further information and tutorial!
Feel free to improve!

452 453
## Projects with this library

MBoretto's avatar
MBoretto committed
454 455
Here's a list of projects that feats this library, feel free to add yours!
- [Super-Dice-Roll](https://github.com/RafaelDelboni/Super-Dice-Roll) [@superdiceroll_bot](https://telegram.me/superdiceroll_bot)
456

MBoretto's avatar
MBoretto committed
457
## Troubleshooting
458

MBoretto's avatar
MBoretto committed
459
If you like living on the edge, please report any bugs you find on the
460 461
[PHP Telegram Bot issues](https://github.com/akalongman/php-telegram-bot/issues) page.

MBoretto's avatar
MBoretto committed
462
## Contributing
463

464
See [CONTRIBUTING](CONTRIBUTING.md) for more information.
465 466 467 468 469 470

## License

Please see the [LICENSE](LICENSE.md) included in this repository for a full copy of the MIT license,
which this project is licensed under.

LONGMAN's avatar
LONGMAN committed
471 472
## Credits

LONGMAN's avatar
LONGMAN committed
473
Credit list in [CREDITS](CREDITS)