Commit ae4d21ec authored by MBoretto's avatar MBoretto

Merge branch 'master' into hotfix

parents 34634ffa f0db603e
# PHP Telegram Bot
======================
[![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)
[![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)
[![Build Status](https://travis-ci.org/akalongman/php-telegram-bot.svg?branch=master)](https://travis-ci.org/akalongman/php-telegram-bot)
[![Latest Stable Version](https://img.shields.io/packagist/v/Longman/telegram-bot.svg)](https://packagist.org/packages/longman/telegram-bot)
[![Latest Stable
Version](https://img.shields.io/packagist/v/Longman/telegram-bot.svg)](https://packagist.org/packages/longman/telegram-bot)
[![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)
[![License](https://img.shields.io/packagist/l/Longman/telegram-bot.svg)](https://packagist.org/packages/longman/telegram-bot)
A Telegram Bot based on the official [Telegram Bot API](https://core.telegram.org/bots/api)
A Telegram Bot based on the official [Telegram Bot
API](https://core.telegram.org/bots/api)
## Introduction
This is a pure php Telegram Bot, fully extensible via plugins. 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 Bot aims to provide a platform where one could simply write a plugin and have interactions in a matter of minutes.
The Bot supports Reply Markup and handle commands in group chat with multiple bot.
### Introduction
This is a pure php Telegram Bot, fully extensible via plugins.
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
Bot aims to provide a platform where one could simply write a plugin
and have interactions in a matter of minutes.
- The Bot supports Reply Markup and handle commands in group chat with
multiple bot.
- The Bot can retrive update with webhook and by getUpdate methods.
Instructions
============
## Instructions
### Create your first bot
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 field on your Telegram app and type `@botfather`, you should be able to initiate a conversation. Be careful not to send it to the wrong contact, because some users has similar usernames to `botfather`.
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
field on your Telegram app and type `@botfather`, you should be able
to initiate a conversation. Be careful not to send it to the wrong
contact, because some users has similar usernames to `botfather`.
![botfather initial conversation](http://i.imgur.com/aI26ixR.png)
2. @botfather replies with `Alright, a new bot. How are we going to call it? Please choose a name for your bot.`
2. @botfather replies with `Alright, a new bot. How are we going to
call it? Please choose a name for your bot.`
3. Type whatever name you want for your bot.
4. @botfather replies with `Good. Now let's choose a username for your bot. It must end in `bot`. Like this, for example: TetrisBot or tetris_bot.`
4. @botfather replies with `Good. Now let's choose a username for your
bot. It must end in `bot`. Like this, for example: TetrisBot or
tetris_bot.`
5. Type whatever username you want for your bot, minimum 5 characters, and must end with `bot`. For example: `telesample_bot`
5. Type whatever username you want for your bot, minimum 5 characters,
and must end with `bot`. For example: `telesample_bot`
6. @botfather replies with:
Done! Congratulations on your new bot. You will find it at 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.
Done! Congratulations on your new bot. You will find it at
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.
Use this token to access the HTTP API:
<b>123456789:AAG90e14-0f8-40183D-18491dDE</b>
For a description of the Bot API, see this page: https://core.telegram.org/bots/api
For a description of the Bot API, see this page:
https://core.telegram.org/bots/api
7. Note down the 'token' mentioned above.
......@@ -51,27 +73,28 @@ Instructions
9. @botfather replies with `Choose a bot to change group messages settings.`
10. Type `@telesample_bot` (change to the username you set at step 5 above, but start it with `@`)
10. Type `@telesample_bot` (change to the username you set at step 5
above, but start it with `@`)
11. @botfather replies with
'Enable' - your bot will only receive messages that either start with the '/' symbol or mention the bot by username.
'Enable' - your bot will only receive messages that either start
with the '/' symbol or mention the bot by username.
'Disable' - your bot will receive all messages that people send to groups.
Current status is: ENABLED
12. Type `Disable` to let your bot receive all messages sent to a group. This step is up to you actually.
12. Type `Disable` to let your bot receive all messages sent to a
group. This step is up to you actually.
13. @botfather replies with `Success! The new status is: DISABLED. /help`
### Require this package with Composer
Install this package through [Composer](https://getcomposer.org/).
Edit your project's `composer.json` file to require
`longman/telegram-bot`.
## Installation
You need server with https and composer support.
Install this package through [Composer](https://getcomposer.org/). Edit your project's `composer.json` file to require `longman/telegram-bot`.
Create composer.json file:
Create *composer.json* file:
```js
{
"name": "yourproject/yourproject",
......@@ -90,14 +113,19 @@ And run composer update
composer require longman/telegram-bot
```
###### Bot token
You will notice that the Telegram Bot wants a value for `API_KEY`. This token may be obtained via a telegram client for your bot. See [this](https://core.telegram.org/bots#botfather) link if you are unsure of how to so this.
### Choose how to retrieve Telegram updates
The bot can handle updates with **webhook** or **getUpdate** method:
| Method | Webhook | getUpdate |
| ---- | :----: | :----: |
| Description | Telegram send the update directy to your host | Yuo have to fetch Telegram updates |
| Host with https | Required | Not required |
| Mysql | Not required | Required |
## Usage
## Webhook installation
You need server with https and composer support.
You must set a [WebHook](https://core.telegram.org/bots/api#setwebhook)
Create set.php and put into it:
Create *set.php* (just edit *example-set.php*) and put into it:
```php
<?php
$loader = require __DIR__.'/vendor/autoload.php';
......@@ -114,10 +142,10 @@ try {
echo $e->getMessage();
}
```
And open your set.php via browser
And open your *set.php* via browser.
After create hook.php and put:
After create *hook.php* (just edit *example-hook.php*) and put:
```php
<?php
$loader = require __DIR__.'/vendor/autoload.php';
......@@ -127,9 +155,7 @@ $BOT_NAME = 'namebot';
try {
// create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($API_KEY,$BOT_NAME);
// here you can set some command specified parameters, for example, google geocode/timezone api key for date command:
$telegram->setCommandConfig('date', array('google_api_key'=>'your_google_api_key_here'));
$telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME);
// handle telegram webhook request
$telegram->handle();
......@@ -138,25 +164,44 @@ try {
// echo $e->getMessage();
}
```
## getUpdate installation NEW!
You need the database Mysql active.
##MySQL storage
If you want insert in database messages/users for further usage in commands, create database and import structure.sql and enable mysql support after object creation and BEFORE handle method
Create *getUpdateCLI.php* (just edit *example-getUpdateCLI.php*) and
put into it:
```php
code
```
give to the file the permission for execution:
```
chmod 775 getUpdateCLI.php
```
then run
```
./getUpdateCLI.php
```
## Utilis
### MySQL storage (Recomended)
If you want insert in database messages/users/chats for further usage
in commands, create database and import *structure.sql* and enable
Mysql support after object creation and BEFORE handle method:
```php
<?php
$credentials = array('host'=>'localhost', 'user'=>'dbuser', 'password'=>'dbpass', 'database'=>'dbname');
$credentials = array('host'=>'localhost', 'user'=>'dbuser',
'password'=>'dbpass', 'database'=>'dbname');
$telegram->enableMySQL($credentials);
```
You can set a custom prefix to all the tables while you are enabling mysql:
You can set a custom prefix to all the tables while you are enabling Mysql:
```php
$telegram->enableMySQL($credentials, $BOT_NAME.'_');
```
##Commands
The bot is able to recognise commands in chat with multiple bot.
### Commands
The bot is able to recognise commands in chat with multiple bot(
/command@mybot ).
It can execute command triggering a chat event. Here's the list:
- Group chat created (**GroupchatcreatedCommand.php**)
......@@ -165,38 +210,47 @@ It can execute command triggering a chat event. Here's the list:
- New chat title (**NewchattitleCommand.php**)
- Left chat participant (**LeftchatparticipantCommand.php**)
**GenericCommand.php** lets you handle commands that don't exist or to use commands as a variable:
**GenericCommand.php** lets you handle commands that don't exist or to
use commands as a variable:
Favourite colour? **/black, /red**
Favourite number? **/1, /134**
Maybe you would like to develop your own commands. A good practice is to store them outside vendor/. This can be done adding the method:
Maybe you would like to develop your own commands. A good practice is
to store them outside vendor/. This can be done adding the method:
```php
$COMMANDS_FOLDER = __DIR__.'/Commands/';
$telegram->addCommandsPath($COMMANDS_FOLDER);
```
##Admin Commands (new!)
Enabling this feature, the admin bot can perform some super user command like send message to all.
### Admin Commands (new!)
Enabling this feature, the admin bot can perform some super user
command like send message to all.
You can specify one or more admin with this option:
```php
$telegram->enableAdmins(array('TelegramUserID','Othersid'));
```
Telegram user id can be retrieved with the command /whoami.
Admin commands are stored in src/Admin/ folder.
To know all the commands avaiable type /help.
Telegram user id can be retrieved with the command **/whoami**.
Admin commands are stored in *src/Admin/* folder.
To know all the commands avaiable type **/help**.
##Send message to all active chats
To do this you have to enable the mysql connection.
### Commands Configuration
With this method you can set some command specified parameters, for
example, google geocode/timezone api key for date command:
```php
$telegram->setCommandConfig('date',
array('google_api_key'=>'your_google_api_key_here'));
```
### Send message to all active chats
To do this you have to enable the Mysql connection.
Here's an example of use:
```php
$results = $telegram->sendToActiveChats(
'sendMessage', //callback function to execute (see Request.php methods)
array('text'=>'Hey! Checkout the new feature!!'), //Param to evaluate the request
array('text'=>'Hey! Checkout the new feature!!'), //Param to
evaluate the request
true, //Send to chats (group chat)
true, //Send to users (single chat)
null, //'yyyy-mm-dd hh:mm:ss' date range from
......@@ -206,28 +260,26 @@ $results = $telegram->sendToActiveChats(
print_r($results);
```
##Utilis
You can also log incoming messages on a text file, set this option with the methods:
### Logging
You can also log incoming messages on a text file, set this option
with the methods:
```php
$telegram->setLogRequests(true);
$telegram->setLogPath($BOT_NAME.'.log');
```
-----
This code is available on [Github](https://github.com/akalongman/php-telegram-bot). Pull requests are welcome.
This code is available on
[Github](https://github.com/akalongman/php-telegram-bot). Pull
requests are welcome.
##Troubleshooting
If you like living on the edge, please report any bugs you find on the [PHP Telegram Bot issues](https://github.com/akalongman/php-telegram-bot/issues) page.
##Contributing
## Troubleshooting
If you like living on the edge, please report any bugs you find on the
[PHP Telegram Bot
issues](https://github.com/akalongman/php-telegram-bot/issues) page.
## Contributing
See [CONTRIBUTING.md](CONTRIBUTING.md) for information.
## Credits
Credit list in [CREDITS](CREDITS)
#!/usr/bin/env php
<?php
#bash script
#while true; do ./getUpdatesCLI.php; done
//Composer Loader
$loader = require __DIR__.'/vendor/autoload.php';
$API_KEY = 'your_bot_api_key';
$BOT_NAME = 'namebot';
//$COMMANDS_FOLDER = __DIR__.'/Commands/';
$credentials = array('host'=>'localhost', 'user'=>'dbuser', 'password'=>'dbpass', 'database'=>'dbname');
try {
// create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME);
//Options
$telegram->enableMySQL($credentials);
//$telegram->enableMySQL($credentials, $BOT_NAME.'_');
//$telegram->addCommandsPath($COMMANDS_FOLDER);
//here you can set some command specified parameters,
//for example, google geocode/timezone api key for date command:
//$telegram->setCommandConfig('date', array('google_api_key'=>'your_google_api_key_here'));
//$telegram->setLogRequests(true);
//$telegram->setLogPath($BOT_NAME.'.log');
// handle telegram getUpdate request
$telegram->handleGetUpdates();
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
// log telegram errors
echo $e->getMessage();
}
<?php
//Composer Loader
$loader = require __DIR__.'/vendor/autoload.php';
$API_KEY = 'your_bot_api_key';
$BOT_NAME = 'namebot';
//$COMMANDS_FOLDER = __DIR__.'/Commands/';
//$credentials = array('host'=>'localhost', 'user'=>'dbuser', 'password'=>'dbpass', 'database'=>'dbname');
try {
// create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME);
//Options
//$telegram->enableMySQL($credentials);
//$telegram->enableMySQL($credentials, $BOT_NAME.'_');
//$telegram->addCommandsPath($COMMANDS_FOLDER);
// here you can set some command specified parameters,
// for example, google geocode/timezone api key for date command:
//$telegram->setCommandConfig('date', array('google_api_key'=>'your_google_api_key_here'));
//$telegram->setLogRequests(true);
//$telegram->setLogPath($BOT_NAME.'.log');
// handle telegram webhook request
$telegram->handle();
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
// log telegram errors
// echo $e->getMessage();
}
<?php
//Composer Loader
$loader = require __DIR__.'/vendor/autoload.php';
$API_KEY = 'your_bot_api_key';
$BOT_NAME = 'namebot';
try {
// create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME);
// set webhook
echo $telegram->setWebHook('https://yourdomain/yourpath_to_hook.php');
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
echo $e->getMessage();
}
......@@ -11,19 +11,33 @@
namespace Longman\TelegramBot\Commands;
use Longman\TelegramBot\Request;
use Longman\TelegramBot\DB;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Entities\Update;
use Longman\TelegramBot\Exception\TelegramException;
class SendtoallCommand extends Command
{
protected $name = 'sendall';
protected $name = 'sendtoall';
protected $description = 'Send the message to all the user\'s bot';
protected $usage = '/sendall <message to send>';
protected $version = '1.2.0';
protected $enabled = true;
protected $public = true;
//need Mysql
protected $need_mysql = true;
public function executeNoDB()
{
//Database not setted or without connection
//Preparing message
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$data = array();
$data['chat_id'] = $chat_id;
$data['text'] = 'Sorry no database connection, unable to execute '.$this->name.' command.';
return Request::sendMessage($data);
}
public function execute()
{
......@@ -37,7 +51,7 @@ class SendtoallCommand extends Command
if (empty($text)) {
$text = 'Write te message to sent: /sendall <message>';
} else {
$results = $this->telegram->sendToActiveChats(
$results = DB::sendToActiveChats(
'sendMessage', //callback function to execute (see Request.php methods)
array('text'=> $text), //Param to evaluate the request
true, //Send to chats (group chat)
......
......@@ -23,6 +23,7 @@ abstract class Command
protected $description = 'Command help';
protected $usage = 'Command usage';
protected $version = '1.0.0';
protected $need_mysql = false;
protected $enabled = true;
protected $name = '';
......@@ -42,8 +43,24 @@ abstract class Command
return $this;
}
public function preExecute()
{
if (!$this->need_mysql |
$this->need_mysql & $this->telegram->isDbEnabled() & DB::isDbConnected()
) {
return $this->execute();
}
return $this->executeNoDB();
}
abstract public function execute();
//this methods is executed if $need_mysql is true but DB connection for some reason is not avaiable
public function executeNoDB()
{
}
public function getUpdate()
{
return $this->update;
......
<?php
/*
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
* Written by Marco Boretto <marco.bore@gmail.com>
*/
namespace Longman\TelegramBot;
use Longman\TelegramBot\Entities\Update;
use Longman\TelegramBot\Exception\TelegramException;
/**
* @package Telegram
* @author Avtandil Kikabidze <akalongman@gmail.com>
* @copyright Avtandil Kikabidze <akalongman@gmail.com>
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
* @link http://www.github.com/akalongman/php-telegram-bot
*/
class DB
{
/**
* MySQL credentials
*
* @var array
*/
static protected $mysql_credentials = array();
/**
* PDO object
*
* @var \PDO
*/
static protected $pdo;
/**
* Initialize
*
* @param array credential, string table_prefix
*/
public static function initialize(array $credentials, $table_prefix = null)
{
if (empty($credentials)) {
throw new TelegramException('MySQL credentials not provided!');
}
self::$mysql_credentials = $credentials;
$dsn = 'mysql:host=' . $credentials['host'] . ';dbname=' . $credentials['database'];
$options = array(\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',);
try {
$pdo = new \PDO($dsn, $credentials['user'], $credentials['password'], $options);
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_WARNING);
//Define table
define('TB_MESSAGES', $table_prefix.'messages');
define('TB_USERS', $table_prefix.'users');
define('TB_CHATS', $table_prefix.'chats');
define('TB_USERS_CHATS', $table_prefix.'users_chats');
} catch (\PDOException $e) {
throw new TelegramException($e->getMessage());
}
self::$pdo = $pdo;
}
/**
* check if database Connection has been created
*
* @return bool
*/
public static function isDbConnected()
{
if (empty(self::$pdo)) {
return false;
} else {
return true;
}
}
/**
* fetch message from DB
*
* @param fetch Message from the DB
*
* @return bool/ array with data
*/
public static function selectMessages($limit = null)
{
if (!self::isDbConnected()) {
return false;
}
try {
$query = 'SELECT * FROM `'.TB_MESSAGES.'`';
$query .= ' ORDER BY '.TB_MESSAGES.'.`update_id` DESC';
$tokens = [];
if (!is_null($limit)) {
//$query .=' LIMIT :limit ';
//$tokens[':limit'] = $limit;
$query .=' LIMIT '.$limit;
}
//echo $query;
$sth = self::$pdo->prepare($query);
//$sth->execute($tokens);
$sth->execute();
$results = $sth->fetchAll(\PDO::FETCH_ASSOC);
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
return $results;
}
/**
* Convert from unix timestamp to timestamp
*
* @return string
*/
protected static function toTimestamp($time)
{
return date('Y-m-d H:i:s', $time);
}
/**
* Insert request in db
*
* @return bool
*/
public static function insertRequest(Update $update)
{
if (!self::isDbConnected()) {
return false;
}
$message = $update->getMessage();
try {
//Users table
$sth1 = self::$pdo->prepare('INSERT INTO `'.TB_USERS.'`
(
`id`, `username`, `first_name`, `last_name`, `created_at`, `updated_at`
)
VALUES (
:id, :username, :first_name, :last_name, :date, :date
)
ON DUPLICATE KEY UPDATE `username`=:username, `first_name`=:first_name,
`last_name`=:last_name, `updated_at`=:date
');
$from = $message->getFrom();
$date = self::toTimestamp($message->getDate());
$user_id = $from->getId();
$username = $from->getUsername();
$first_name = $from->getFirstName();
$last_name = $from->getLastName();
$sth1->bindParam(':id', $user_id, \PDO::PARAM_INT);
$sth1->bindParam(':username', $username, \PDO::PARAM_STR, 255);
$sth1->bindParam(':first_name', $first_name, \PDO::PARAM_STR, 255);
$sth1->bindParam(':last_name', $last_name, \PDO::PARAM_STR, 255);
$sth1->bindParam(':date', $date, \PDO::PARAM_STR);
$status = $sth1->execute();
//chats table
$sth2 = self::$pdo->prepare('INSERT INTO `'.TB_CHATS.'`
(
`id`, `title`, `created_at` ,`updated_at`
)
VALUES (:id, :title, :date, :date)
ON DUPLICATE KEY UPDATE `title`=:title, `updated_at`=:date
');
$chat_id = $message->getChat()->getId();
$chat_title = $message->getChat()->getTitle();
$sth2->bindParam(':id', $chat_id, \PDO::PARAM_INT);
$sth2->bindParam(':title', $chat_title, \PDO::PARAM_STR, 255);
$sth2->bindParam(':date', $date, \PDO::PARAM_STR);
$status = $sth2->execute();
//user_chat table
$sth3 = self::$pdo->prepare('INSERT IGNORE INTO `'.TB_USERS_CHATS.'`
(
`user_id`, `chat_id`
)
VALUES (:user_id, :chat_id)
');
$sth3->bindParam(':user_id', $user_id, \PDO::PARAM_INT);
$sth3->bindParam(':chat_id', $chat_id, \PDO::PARAM_INT);
$status = $sth3->execute();
//Messages Table
$sth = self::$pdo->prepare('INSERT IGNORE INTO `'.TB_MESSAGES.'`
(
`update_id`, `message_id`, `user_id`, `date`, `chat_id`, `forward_from`,
`forward_date`, `reply_to_message`, `text`
)
VALUES (:update_id, :message_id, :user_id, :date, :chat_id, :forward_from,
:forward_date, :reply_to_message, :text)');
$update_id = $update->getUpdateId();
$message_id = $message->getMessageId();
$forward_from = $message->getForwardFrom();
$forward_date = self::toTimestamp($message->getForwardDate());
$reply_to_message = $message->getReplyToMessage();
if (is_object($reply_to_message)) {
$reply_to_message = $reply_to_message->toJSON();
}
$text = $message->getText();
$sth->bindParam(':update_id', $update_id, \PDO::PARAM_INT);
$sth->bindParam(':message_id', $message_id, \PDO::PARAM_INT);
$sth->bindParam(':user_id', $user_id, \PDO::PARAM_INT);
$sth->bindParam(':date', $date, \PDO::PARAM_STR);
$sth->bindParam(':chat_id', $chat_id, \PDO::PARAM_STR);
$sth->bindParam(':forward_from', $forward_from, \PDO::PARAM_STR);
$sth->bindParam(':forward_date', $forward_date, \PDO::PARAM_STR);
$sth->bindParam(':reply_to_message', $reply_to_message, \PDO::PARAM_STR);
$sth->bindParam(':text', $text, \PDO::PARAM_STR);
$status = $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
return true;
}
/**
* Send Message in all the active chat
*
* @param date string yyyy-mm-dd hh:mm:ss
*
* @return bool
*/
//TODO separe send from query?
public static function sendToActiveChats(
$callback_function,
array $data,
$send_chats = true,
$send_users = true,
$date_from = null,
$date_to = null
) {
if (!self::isDbConnected()) {
return false;
}
$callback_path = __NAMESPACE__ .'\Request';
if (! method_exists($callback_path, $callback_function)) {
throw new TelegramException('Methods: '.$callback_function.' not found in class Request.');
}
if (!$send_chats & !$send_users) {
return false;
}
try {
$query = 'SELECT * ,
'.TB_CHATS.'.`id` AS `chat_id`,
'.TB_CHATS.'.`updated_at` AS `chat_updated_at`
FROM `'.TB_CHATS.'` LEFT JOIN `'.TB_USERS.'`
ON '.TB_CHATS.'.`id`='.TB_USERS.'.`id`';
//Building parts of query
$chat_or_user = '';
$where = [];
$tokens = [];
if ($send_chats & !$send_users) {
$where[] = TB_CHATS.'.`id` < 0';
} elseif (!$send_chats & $send_users) {
$where[] = TB_CHATS.'.`id` > 0';
}
if (! is_null($date_from)) {
$where[] = TB_CHATS.'.`updated_at` >= :date_from';
$tokens[':date_from'] = $date_from;
}
if (! is_null($date_to)) {
$where[] = TB_CHATS.'.`updated_at` <= :date_to';
$tokens[':date_to'] = $date_to;
}
$a=0;
foreach ($where as $part) {
if ($a) {
$query .= ' AND '.$part;
} else {
$query .= ' WHERE '.$part;
++$a;
}
}
$query .= ' ORDER BY '.TB_CHATS.'.`updated_at` ASC';
//echo $query."\n";
$sth = self::$pdo->prepare($query);
$sth->execute($tokens);
$results = [];
while ($row = $sth->fetch(\PDO::FETCH_ASSOC)) {
//print_r($row);
$data['chat_id'] = $row['chat_id'];
$results[] = call_user_func_array($callback_path.'::'.$callback_function, array($data));
}
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
return $results;
}
}
......@@ -104,7 +104,7 @@ class Message extends Entity
$this->reply_to_message = isset($data['reply_to_message']) ? $data['reply_to_message'] : null;
if (!empty($this->reply_to_message)) {
$this->reply_to_message = new self($this->reply_to_message);
$this->reply_to_message = new Message($this->reply_to_message, $this->bot_name);
}
$this->new_chat_participant = isset($data['new_chat_participant']) ? $data['new_chat_participant'] : null;
......
......@@ -22,29 +22,52 @@ class ServerResponse extends Entity
protected $error_code;
protected $description;
public function __construct(array $data, $bot_name)
{
if (isset($data['ok']) & isset($data['result'])) {
if ($data['ok'] & $data['result'] != 1) {
if (is_array($data['result'])) {
if ($data['ok'] & !$this->isAssoc($data['result'])) {
//update id
$this->ok = $data['ok'];
//$this->result =[];
foreach ($data['result'] as $update) {
$this->result[] = new Update($update, $bot_name);
}
$this->error_code = null;
$this->description = null;
} elseif ($data['ok'] & $this->isAssoc($data['result'])) {
//Response from sendMessage set
$this->ok = $data['ok'];
$this->result = new Message($data['result'], $bot_name);
$this->error_code = null;
$this->description = null;
} elseif ($data['ok'] & $data['result'] == 1) {
}
} else {
if ($data['ok'] & $data['result'] == true) {
//Response from setWebhook set
$this->ok = $data['ok'];
$this->result = $data['result'];
$this->result = true;
$this->error_code = null;
$this->description = $data['description'];
if (isset($data['description'])) {
$this->description = $data['description'];
} else {
$this->description = '';
}
} else {
$this->ok = false;
$this->result = null;
$this->error_code = $data['error_code'];
$this->description = $data['description'];
}
}
} else {
//webHook not set
$this->ok = false;
......@@ -71,6 +94,11 @@ class ServerResponse extends Entity
}
}
//must be an array
protected function isAssoc(array $array)
{
return (bool)count(array_filter(array_keys($array), 'is_string'));
}
public function isOk()
{
return $this->ok;
......@@ -87,45 +115,4 @@ class ServerResponse extends Entity
{
return $this->description;
}
//Succes request
//Array
//(
// [ok] => 1
// [result] => Array
// (
// [message_id] => 3582
// [from] => Array
// (
// [id] => 12345678
// [first_name] => name
// [username] => botname
// )
//
// [chat] => Array
// (
// [id] => 123456789
// [first_name] => name
// [username] => Surname
// )
//
// [date] => 1441194780
// [text] => hello
// )
//
//)
// Error Request
//
//Array
//(
// [ok] =>
// [error_code] => 401
// [description] => Error: Unauthorized
//)
//Array
//(
// [chat_id] => 110751663
// [text] => ciao
//)
}
......@@ -17,6 +17,7 @@ class Request
{
private static $telegram;
private static $input;
private static $server_response;
private static $methods = array(
'getMe',
......@@ -36,7 +37,11 @@ class Request
public static function initialize(Telegram $telegram)
{
if (is_object($telegram)) {
self::$telegram = $telegram;
} else {
throw new TelegramException('Telegram pointer is empty!');
}
}
public static function getInput()
......@@ -50,6 +55,18 @@ class Request
return self::$input;
}
public static function getUpdates($data)
{
if ($update = self::$telegram->getCustomUpdate()) {
self::$input = $update;
} else {
self::$input = self::send('getUpdates', $data);
}
self::log(); //TODO
return self::$input;
}
private static function log()
{
if (!self::$telegram->getLogRequests()) {
......@@ -65,25 +82,42 @@ class Request
return $status;
}
public static function send($action, array $data = null)
public static function generateGeneralFakeServerSesponse($data = null)
{
//PARAM BINDED IN PHPUNIT TEST FOR TestServerResponse.php
//Maybe this is not the best possible implementation
if (!in_array($action, self::$methods)) {
throw new TelegramException('This methods doesn\'t exixt!');
}
//No value set in $data ie testing setWekhook
//Provided $data['chat_id'] ie testing sendMessage
if (defined('PHPUNIT_TESTSUITE')) {
$fake_response['ok'] = 1; // :)
$fake_response['ok'] = true; // :)
if (!isset($data)) {
$fake_response['result'] = true;
}
//some fake data just to let iniatilize the class method SendMessage
//some data to let iniatilize the class method SendMessage
if (isset($data['chat_id'])) {
$data['message_id'] = '123';
$data['date'] = '123';
$data['message_id'] = '1234';
$data['date'] = '1441378360';
$data['from'] = array( 'id' => 123456789 ,'first_name' => 'botname', 'username'=> 'namebot');
$data['chat'] = array('id'=> $data['chat_id'] );
$data['from'] = array( 'id' => 123,'first_name' => 'botname', 'username'=> 'namebot');
$fake_response['result'] = $data;
}
return $fake_response;
}
public static function send($action, array $data = null)
{
if (!in_array($action, self::$methods)) {
throw new TelegramException('This methods doesn\'t exixt!');
}
if (defined('PHPUNIT_TESTSUITE')) {
$fake_response = self::generateGeneralFakeServerSesponse($data);
return new ServerResponse($fake_response, self::$telegram->getBotName());
}
......@@ -109,10 +143,13 @@ class Request
$response['ok'] = 1;
$response['error_code'] = 1;
$response['description'] = 'Empty server response';
$result =json_encode($response);
}
//return json_decode($result, true);
return new ServerResponse(json_decode($result, true), self::$telegram->getBotName());
//return $result;
$bot_name = self::$telegram->getBotName();
return new ServerResponse(json_decode($result, true), $bot_name);
}
public static function sendMessage(array $data)
......
......@@ -30,7 +30,7 @@ class Telegram
*
* @var string
*/
protected $version = '0.16.0';
protected $version = '0.17.0';
/**
* Telegram API key
......@@ -86,22 +86,7 @@ class Telegram
*
* @var boolean
*/
protected $mysql_enabled;
/**
* MySQL credentials
*
* @var array
*/
protected $mysql_credentials = array();
/**
* PDO object
*
* @var \PDO
*/
protected $pdo;
protected $mysql_enabled = false;
/**
* Commands config
......@@ -111,7 +96,6 @@ class Telegram
protected $commands_config;
/**
* Message types
*
......@@ -158,26 +142,14 @@ class Telegram
}
/**
* Set custom update string for debug purposes
*
* @param string $update
* Initialize
*
* @return \Longman\TelegramBot\Telegram
* @param array credential, string table_prefix
*/
public function setCustomUpdate($update)
public function enableMySQL(array $credential, $table_prefix = null)
{
$this->update = $update;
return $this;
}
/**
* Get custom update string for debug purposes
*
* @return string $update
*/
public function getCustomUpdate()
{
return $this->update;
DB::initialize($credential, $table_prefix);
$this->mysql_enabled = true;
}
/**
......@@ -276,8 +248,71 @@ class Telegram
return $this->log_path;
}
/**
* Set custom update string for debug purposes
*
* @param string $update
*
* @return \Longman\TelegramBot\Telegram
*/
public function setCustomUpdate($update)
{
$this->update = $update;
return $this;
}
/**
* Get custom update string for debug purposes
*
* @return string $update in json
*/
public function getCustomUpdate()
{
return $this->update;
}
/**
* Handle bot request
* Handle getUpdates method
*
* @return \Longman\TelegramBot\Telegram
*/
public function handleGetUpdates($limit = null, $timeout = null)
{
//DB Query
$last_message = DB::selectMessages(1);
if (isset($last_message[0]['update_id'])) {
//As explained in the telegram bot api documentation
$offset = $last_message[0]['update_id']+1;
} else {
$offset = null;
}
//arrive a server Response object
$ServerResponse = Request::getUpdates([
'offset' => $offset ,
'limit' => $limit,
'timeout' => $timeout
]);
if ($ServerResponse->isOk()) {
$results = '';
$n_update = count($ServerResponse->getResult());
for ($a = 0; $a < $n_update; $a++) {
$result = $this->processUpdate($ServerResponse->getResult()[$a]);
}
print(date('Y-m-d H:i:s', time()).' - Processed '.$a." updates\n");
} else {
print(date('Y-m-d H:i:s', time())." - Fail fetch updates\n");
}
//return $results
}
/**
* Handle bot request from wekhook
*
* @return \Longman\TelegramBot\Telegram
*/
......@@ -294,6 +329,17 @@ class Telegram
}
$update = new Update($post, $this->bot_name);
return $this->processUpdate($update);
}
/**
* Process Handle bot request
*
* @return \Longman\TelegramBot\Telegram
*/
public function processUpdate(update $update)
{
//Load admin Commands
if ($this->admin_enabled) {
......@@ -311,11 +357,10 @@ class Telegram
}
}
$this->insertRequest($update);
$message = $update->getMessage();
DB::insertRequest($update);
// check type
$message = $update->getMessage();
$type = $message->getType();
switch ($type) {
......@@ -323,38 +368,41 @@ class Telegram
case 'text':
// do nothing
break;
case 'command':
// execute command
$command = $message->getCommand();
return $this->executeCommand($command, $update);
break;
case 'new_chat_participant':
// trigger new participant
return $this->executeCommand('Newchatparticipant', $update);
break;
$command = 'Newchatparticipant';
return $this->executeCommand($command, $update);
break;
case 'left_chat_participant':
// trigger left chat participant
return $this->executeCommand('Leftchatparticipant', $update);
break;
$command = 'Leftchatparticipant';
return $this->executeCommand($command, $update);
break;
case 'new_chat_title':
// trigger new_chat_title
return $this->executeCommand('Newchattitle', $update);
break;
$command = 'Newchattitle';
return $this->executeCommand($command, $update);
break;
case 'delete_chat_photo':
// trigger delete_chat_photo
return $this->executeCommand('Deletechatphoto', $update);
break;
$command = 'Deletechatphoto';
return $this->executeCommand($command, $update);
break;
case 'group_chat_created':
// trigger group_chat_created
return $this->executeCommand('Groupchatcreated', $update);
$command = 'Groupchatcreated';
return $this->executeCommand($command, $update);
break;
}
}
......@@ -378,8 +426,9 @@ class Telegram
return false;
}
return $class->execute();
//execute methods will be execute after preexecution
//this for prevent to execute db query witout connection
return $class->preExecute();
}
/**
......@@ -423,7 +472,6 @@ class Telegram
}
}
return false;
}
......@@ -457,260 +505,20 @@ class Telegram
}
/**
*DB Mehods
*
*
*/
/**
* Enable MySQL integration
*
* @param array $credentials MySQL credentials
*
* @return string
*/
public function enableMySQL(array $credentials, $table_prefix = null)
{
if (empty($credentials)) {
throw new TelegramException('MySQL credentials not provided!');
}
$this->mysql_credentials = $credentials;
$dsn = 'mysql:host=' . $credentials['host'] . ';dbname=' . $credentials['database'];
$options = array(\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',);
try {
$pdo = new \PDO($dsn, $credentials['user'], $credentials['password'], $options);
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_WARNING);
//Define table
define('TB_MESSAGES', $table_prefix.'messages');
define('TB_USERS', $table_prefix.'users');
define('TB_CHATS', $table_prefix.'chats');
define('TB_USERS_CHATS', $table_prefix.'users_chats');
} catch (\PDOException $e) {
throw new TelegramException($e->getMessage());
}
$this->pdo = $pdo;
$this->mysql_enabled = true;
return $this;
}
/**
* Convert from unix timestamp to timestamp
*
* @return string
*/
protected function toTimestamp($time)
{
return date('Y-m-d H:i:s', $time);
}
/**
* Insert request in db
* check id user require the db connection
*
* @return bool
*/
// protected function insertRequest(Update $update)
public function insertRequest(Update $update)
public function isDbEnabled()
{
if (empty($this->pdo)) {
return false;
}
$message = $update->getMessage();
try {
//Users table
$sth1 = $this->pdo->prepare('INSERT INTO `'.TB_USERS.'`
(
`id`, `username`, `first_name`, `last_name`, `created_at`, `updated_at`
)
VALUES (
:id, :username, :first_name, :last_name, :date, :date
)
ON DUPLICATE KEY UPDATE `username`=:username, `first_name`=:first_name,
`last_name`=:last_name, `updated_at`=:date
');
$from = $message->getFrom();
$date = $this->toTimestamp($message->getDate());
$user_id = $from->getId();
$username = $from->getUsername();
$first_name = $from->getFirstName();
$last_name = $from->getLastName();
$sth1->bindParam(':id', $user_id, \PDO::PARAM_INT);
$sth1->bindParam(':username', $username, \PDO::PARAM_STR, 255);
$sth1->bindParam(':first_name', $first_name, \PDO::PARAM_STR, 255);
$sth1->bindParam(':last_name', $last_name, \PDO::PARAM_STR, 255);
$sth1->bindParam(':date', $date, \PDO::PARAM_STR);
$status = $sth1->execute();
//chats table
$sth2 = $this->pdo->prepare('INSERT INTO `'.TB_CHATS.'`
(
`id`, `title`, `created_at` ,`updated_at`
)
VALUES (:id, :title, :date, :date)
ON DUPLICATE KEY UPDATE `title`=:title, `updated_at`=:date
');
$chat_id = $message->getChat()->getId();
$chat_title = $message->getChat()->getTitle();
$sth2->bindParam(':id', $chat_id, \PDO::PARAM_INT);
$sth2->bindParam(':title', $chat_title, \PDO::PARAM_STR, 255);
$sth2->bindParam(':date', $date, \PDO::PARAM_STR);
$status = $sth2->execute();
//user_chat table
$sth3 = $this->pdo->prepare('INSERT IGNORE INTO `'.TB_USERS_CHATS.'`
(
`user_id`, `chat_id`
)
VALUES (:user_id, :chat_id)
');
$sth3->bindParam(':user_id', $user_id, \PDO::PARAM_INT);
$sth3->bindParam(':chat_id', $chat_id, \PDO::PARAM_INT);
$status = $sth3->execute();
//Messages Table
$sth = $this->pdo->prepare('INSERT IGNORE INTO `'.TB_MESSAGES.'`
(
`update_id`, `message_id`, `user_id`, `date`, `chat_id`, `forward_from`,
`forward_date`, `reply_to_message`, `text`
)
VALUES (:update_id, :message_id, :user_id, :date, :chat_id, :forward_from,
:forward_date, :reply_to_message, :text)');
$update_id = $update->getUpdateId();
$message_id = $message->getMessageId();
$forward_from = $message->getForwardFrom();
$forward_date = $this->toTimestamp($message->getForwardDate());
$reply_to_message = $message->getReplyToMessage();
if (is_object($reply_to_message)) {
$reply_to_message = $reply_to_message->toJSON();
}
$text = $message->getText();
$sth->bindParam(':update_id', $update_id, \PDO::PARAM_INT);
$sth->bindParam(':message_id', $message_id, \PDO::PARAM_INT);
$sth->bindParam(':user_id', $user_id, \PDO::PARAM_INT);
$sth->bindParam(':date', $date, \PDO::PARAM_STR);
$sth->bindParam(':chat_id', $chat_id, \PDO::PARAM_STR);
$sth->bindParam(':forward_from', $forward_from, \PDO::PARAM_STR);
$sth->bindParam(':forward_date', $forward_date, \PDO::PARAM_STR);
$sth->bindParam(':reply_to_message', $reply_to_message, \PDO::PARAM_STR);
$sth->bindParam(':text', $text, \PDO::PARAM_STR);
$status = $sth->execute();
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
}
if ($this->mysql_enabled) {
return true;
}
/**
* Send Message in all the active chat
*
* @param date string yyyy-mm-dd hh:mm:ss
*
* @return bool
*/
public function sendToActiveChats(
$callback_function,
array $data,
$send_chats = true,
$send_users = true,
$date_from = null,
$date_to = null
) {
if (empty($this->pdo)) {
return false;
}
$callback_path = __NAMESPACE__ .'\Request';
if (! method_exists($callback_path, $callback_function)) {
throw new TelegramException('Methods: '.$callback_function.' not found in class Request.');
}
if (!$send_chats & !$send_users) {
return false;
}
try {
$query = 'SELECT * ,
'.TB_CHATS.'.`id` AS `chat_id`,
'.TB_CHATS.'.`updated_at` AS `chat_updated_at`
FROM `'.TB_CHATS.'` LEFT JOIN `'.TB_USERS.'`
ON '.TB_CHATS.'.`id`='.TB_USERS.'.`id`';
//Building parts of query
$chat_or_user = '';
$where = [];
$tokens = [];
if ($send_chats & !$send_users) {
$where[] = TB_CHATS.'.`id` < 0';
} elseif (!$send_chats & $send_users) {
$where[] = TB_CHATS.'.`id` > 0';
}
if (! is_null($date_from)) {
$where[] = TB_CHATS.'.`updated_at` >= :date_from';
$tokens[':date_from'] = $date_from;
}
if (! is_null($date_to)) {
$where[] = TB_CHATS.'.`updated_at` <= :date_to';
$tokens[':date_to'] = $date_to;
}
$a=0;
foreach ($where as $part) {
if ($a) {
$query .= ' AND '.$part;
} else {
$query .= ' WHERE '.$part;
++$a;
}
}
//echo $query."\n";
$sth = $this->pdo->prepare($query);
$sth->execute($tokens);
$results = [];
while ($row = $sth->fetch(\PDO::FETCH_ASSOC)) {
//print_r($row);
$data['chat_id'] = $row['chat_id'];
$results[] = call_user_func_array($callback_path.'::'.$callback_function, array( $data));
}
} catch (PDOException $e) {
throw new TelegramException($e->getMessage());
return false;
}
return $results;
}
/**
*End DB Mehods
*
*/
/**
* Add custom commands path
......
<?php
/*
* This file is part of the TelegramBot package.
*
* (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
* Written by Marco Boretto
*/
namespace Tests\Unit;
use \Longman\TelegramBot\Entities\ServerResponse;
use \Longman\TelegramBot\Entities\Message;
use \Longman\TelegramBot\Request;
/**
* @package TelegramTest
* @author Avtandil Kikabidze <akalongman@gmail.com>
* @copyright Avtandil Kikabidze <akalongman@gmail.com>
* @license http://opensource.org/licenses/mit-license.php The MIT License (MIT)
* @link http://www.github.com/akalongman/php-telegram-bot
*/
class ServerResponseTest extends TestCase
{
/**
* @var \Longman\TelegramBot\Telegram
*/
private $server;
/**
* setUp
*/
protected function setUp()
{
}
/**
* @test
*/
public function sendMessageOk()
{
return '{
"ok":true,
"result":{
"message_id":1234,
"from":{"id":123456789,"first_name":"botname","username":"namebot"},
"chat":{"id":123456789,"first_name":"john","username":"Mjohn"},
"date":1441378360,
"text":"hello"
}
}';
}
public function testSendMessageOk() {
$result = $this->sendMessageOk();
$this->server = new ServerResponse(json_decode($result, true), 'testbot');
$this->assertTrue($this->server->isOk());
$this->assertInstanceOf('\Longman\TelegramBot\Entities\Message', $this->server->getResult());
$this->assertNull($this->server->getErrorCode());
$this->assertNull($this->server->getDescription());
//Message
$this->assertEquals('1234', $this->server->getResult()->getMessageId());
$this->assertEquals('123456789', $this->server->getResult()->getFrom()->getId());
$this->assertEquals('botname', $this->server->getResult()->getFrom()->getFirstName());
$this->assertEquals('namebot', $this->server->getResult()->getFrom()->getUserName());
$this->assertEquals('123456789', $this->server->getResult()->getChat()->getId());
$this->assertEquals('john', $this->server->getResult()->getChat()->getFirstName());
$this->assertEquals('Mjohn', $this->server->getResult()->getChat()->getUserName());
$this->assertEquals('1441378360', $this->server->getResult()->getDate());
$this->assertEquals('hello', $this->server->getResult()->getText());
//... they are not finished...
}
/**
* @test
*/
public function sendMessageFail()
{
return '{
"ok":false,
"error_code":400,
"description":"Error: Bad Request: wrong chat id"
}';
}
public function testSendMessageFail() {
$result = $this->sendMessageFail();
$this->server = new ServerResponse(json_decode($result, true), 'testbot');
$this->assertFalse($this->server->isOk());
$this->assertNull($this->server->getResult());
$this->assertEquals('400', $this->server->getErrorCode());
$this->assertEquals('Error: Bad Request: wrong chat id', $this->server->getDescription());
}
/**
* @test
*/
public function setWebHookOk()
{
return '{"ok":true,"result":true,"description":"Webhook was set"}';
}
public function testSetWebhookOk() {
$result = $this->setWebhookOk();
$this->server = new ServerResponse(json_decode($result, true), 'testbot');
$this->assertTrue($this->server->isOk());
$this->assertTrue($this->server->getResult());
$this->assertNull($this->server->getErrorCode());
$this->assertEquals('Webhook was set', $this->server->getDescription());
}
/**
* @test
*/
public function setWebHookFail()
{
return '{
"ok":false,
"error_code":400,
"description":"Error: Bad request: htttps:\/\/domain.host.org\/dir\/hook.php"
}';
}
public function testSetWebhookFail() {
$result = $this->setWebHookFail();
$this->server = new ServerResponse(json_decode($result, true), 'testbot');
$this->assertFalse($this->server->isOk());
$this->assertNull($this->server->getResult());
$this->assertEquals(400, $this->server->getErrorCode());
$this->assertEquals("Error: Bad request: htttps://domain.host.org/dir/hook.php", $this->server->getDescription());
}
/**
* @test
*/
public function getUpdatesArray()
{
return '{
"ok":true,
"result":[
{"update_id":123,
"message":{
"message_id":90,
"from":{"id":123456789,"first_name":"John","username":"Mjohn"},
"chat":{"id":123456789,"first_name":"John","username":"Mjohn"},
"date":1441569067,
"text":"\/start"}
},
{"update_id":124,
"message":{
"message_id":91,
"from":{"id":123456788,"first_name":"Patrizia","username":"Patry"},
"chat":{"id":123456788,"first_name":"Patrizia","username":"Patry"},
"date":1441569073,
"text":"Hello!"}
},
{"update_id":125,
"message":{
"message_id":92,
"from":{"id":123456789,"first_name":"John","username":"MJohn"},
"chat":{"id":123456789,"first_name":"John","username":"MJohn"},
"date":1441569094,
"text":"\/echo hello!"}
},
{"update_id":126,
"message":{
"message_id":93,
"from":{"id":123456788,"first_name":"Patrizia","username":"Patry"},
"chat":{"id":123456788,"first_name":"Patrizia","username":"Patry"},
"date":1441569112,
"text":"\/echo the best"
}
}
]
}';
}
/**
* @test
*/
public function getUpdatesEmpty()
{
return '{"ok":true,"result":[]}';
}
/**
* @test
*/
public function testSetGeneralTestFakeResponse() {
//setWebhook ok
$fake_response = Request::generateGeneralFakeServerSesponse();
$this->server = new ServerResponse($fake_response, 'testbot');
$this->assertTrue($this->server->isOk());
$this->assertTrue($this->server->getResult());
$this->assertNull($this->server->getErrorCode());
$this->assertEquals('', $this->server->getDescription());
//sendMessage ok
$fake_response = Request::generateGeneralFakeServerSesponse(['chat_id' => 123456789, 'text' => 'hello']);
$this->server = new ServerResponse($fake_response, 'testbot');
$this->assertTrue($this->server->isOk());
$this->assertInstanceOf('\Longman\TelegramBot\Entities\Message', $this->server->getResult());
$this->assertNull($this->server->getErrorCode());
$this->assertNull($this->server->getDescription());
//Message
$this->assertEquals('1234', $this->server->getResult()->getMessageId());
$this->assertEquals('1441378360', $this->server->getResult()->getDate());
$this->assertEquals('hello', $this->server->getResult()->getText());
//Message //User
$this->assertEquals('123456789', $this->server->getResult()->getFrom()->getId());
$this->assertEquals('botname', $this->server->getResult()->getFrom()->getFirstName());
$this->assertEquals('namebot', $this->server->getResult()->getFrom()->getUserName());
//Message //Chat
$this->assertEquals('123456789', $this->server->getResult()->getChat()->getId());
$this->assertEquals('', $this->server->getResult()->getChat()->getFirstName());
$this->assertEquals('', $this->server->getResult()->getChat()->getUserName());
//... they are not finished...
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment