Skip to content
This repository was archived by the owner on Sep 7, 2022. It is now read-only.
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
a81da3c
add support for local bot API server
zuhri2395 Sep 28, 2021
61250ac
update url in downloadFile method
zuhri2395 Sep 29, 2021
2a81b54
Merge pull request #7 from zuhri2395/master
Lukasss93 Apr 13, 2022
a651eb1
Fix domain url
Lukasss93 Apr 14, 2022
390151d
Fix Telegram Bot API 5.3
Lukasss93 Apr 16, 2022
ca3a8f4
Update to Telegram Bot API 5.4
Lukasss93 Apr 16, 2022
15a9481
Update to Telegram Bot API 5.5
Lukasss93 Apr 16, 2022
44a0f88
Update to Telegram Bot API 5.6
Lukasss93 Apr 16, 2022
472de13
Update to Telegram Bot API 5.7
Lukasss93 Apr 16, 2022
1603053
Moved TelegramBot\Constants namespace to TelegramBot\Enums
Lukasss93 Apr 16, 2022
45e99f3
Added abstract class Enum
Lukasss93 Apr 16, 2022
f03f044
Added ChatMemberType enum
Lukasss93 Apr 16, 2022
cf09c32
Added missing cases to Enum files
Lukasss93 Apr 16, 2022
6c20edf
Update php version to 8.0
Lukasss93 Apr 17, 2022
1a9bfef
Removed useless psr4 namespaces
Lukasss93 Apr 17, 2022
a5047be
Update to Telegram Bot API 6.0
Lukasss93 Apr 17, 2022
77fd70e
Update readme
Lukasss93 Apr 17, 2022
7f76506
Move endpoints to traits
Lukasss93 Apr 17, 2022
0a4444a
Fix generic PassportElementError class
Lukasss93 Apr 19, 2022
437542e
Update phpdoc for all endpoints + changed endpoint name to __FUNCTION__
Lukasss93 Apr 19, 2022
ac0ce25
Update changelog
Lukasss93 Apr 19, 2022
eeff77a
Moved endpoint traits usage to Client trait
Lukasss93 Apr 19, 2022
4e5f5b0
Added Macroable trait to Client trait
Lukasss93 Apr 19, 2022
ca78cc9
Added hydrator interface + implementation
Lukasss93 Apr 19, 2022
fae0aab
Removed auto-splitting long messages
Lukasss93 Apr 19, 2022
0a19b16
Added guzzle library
Lukasss93 Apr 19, 2022
43d1c2a
Added InputFile type
Lukasss93 Apr 21, 2022
1dc99fe
Added abstract class InputMedia
Lukasss93 Apr 21, 2022
10999ef
No method parameters wrap
Lukasss93 Apr 21, 2022
caa8f1c
Optimize requests
Lukasss93 Apr 21, 2022
b6c0ba6
Change config signature
Lukasss93 Apr 21, 2022
9f15384
Add downloadFile method
Lukasss93 Apr 21, 2022
be5cef2
Moved TelegramBot\TelegramException to TelegramBot\Exceptions\Telegra…
Lukasss93 Apr 21, 2022
f0512fb
Remove ij_php_keep_blank_lines_in_code from .editorconfig
Lukasss93 Apr 21, 2022
e1c8729
Remove TelegramHelper
Lukasss93 Apr 21, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ ij_php_align_key_value_pairs = false
ij_php_comma_after_last_array_element = true
ij_php_keep_indents_on_empty_lines = false
ij_php_else_if_style = combine
ij_php_keep_blank_lines_in_code = 1
ij_php_concat_spaces = false
ij_php_blank_lines_before_return_statement = 1
ij_php_space_before_short_closure_left_parenthesis = true
ij_php_method_parameters_wrap = off
ij_php_blank_lines_before_return_statement = 0
32 changes: 32 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,48 @@
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## v2.0 - [UNRELEASED]

### Added

- Added support for local bot API server
- Added support for **PHP 8.0**
- Added `ParseMode::MARKDOWN_LEGACY`

### Changed

- Updated to Telegram Bot API 5.3
- Updated to Telegram Bot API 5.4
- Updated to Telegram Bot API 5.5
- Updated to Telegram Bot API 5.6
- Updated to Telegram Bot API 5.7
- Updated to Telegram Bot API 6.0
- All optional parameters in all endpoints methods must be inside the `array $opt = []`
- The namespace `TelegramBot\Constants` was renamed to `TelegramBot\Enums`
- Better PhpDoc
- Changed `ParseMode::MARKDOWN` value to _MarkdownV2_
- Automatic `json_encode` for mandatory parameters requiring a JSON-serialized object/array

### Removed

- Dropped support for **PHP 7.2**
- Removed the `kickChatMember` method

## v1.14.1 - 2021-09-07

### Fixed

- Fixed php version + updated jsonmapper version
- Removed composer.lock from git

## v1.14 - 2021-07-25

### Changed

- Updated to Telegram Bot API 5.3

## v1.13 - 2021-04-26
Expand Down
16 changes: 7 additions & 9 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,19 @@
}
],
"require": {
"php": "^7.2|^8.0",
"php": "^8.0",
"ext-mbstring": "*",
"ext-curl": "*",
"ext-fileinfo": "*",
"ext-json": "*",
"netresearch/jsonmapper": "^v4.0"
"netresearch/jsonmapper": "^v4.0",
"illuminate/macroable": "^v9.0",
"guzzlehttp/guzzle": "^7.4",
"illuminate/support": "^v9.0"
},
"autoload": {
"psr-4": {
"TelegramBot\\": "src/",
"TelegramBot\\Types\\": "src/Types/",
"TelegramBot\\Constants\\": "src/Constants/"
},
"files": [
"src/TelegramHelper.php"
]
"TelegramBot\\": "src/"
}
}
}
43 changes: 21 additions & 22 deletions readme.md
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
# TelegramBot-PHP

[![API](https://img.shields.io/badge/Telegram%20Bot%20API-5.3%09--%20June%2025%2C%202021-blue.svg)](https://core.telegram.org/bots/api)
![PHP](https://img.shields.io/badge/php-≥%207.2-8892bf.svg)
![CURL](https://img.shields.io/badge/cURL-required-green.svg)

[![Latest Stable Version](https://poser.pugx.org/lukasss93/telegrambot-php/v/stable)](https://packagist.org/packages/lukasss93/telegrambot-php)
[![Total Downloads](https://poser.pugx.org/lukasss93/telegrambot-php/downloads)](https://packagist.org/packages/lukasss93/telegrambot-php)
[![API](https://img.shields.io/badge/Telegram%20Bot%20API-6.0%09--%20April%2016%2C%202022-blue.svg)](https://core.telegram.org/bots/api)
[![License](https://poser.pugx.org/lukasss93/telegrambot-php/license)](https://packagist.org/packages/lukasss93/telegrambot-php)

> A very simple PHP [Telegram Bot API](https://core.telegram.org/bots/api) for sending messages.
> A very simple Telegram Bot Framework

Requirements
---------
This simple framework is object-based, all methods return a Telegram Object contained in TelegramBot/Types namespace.

* PHP ≥ 7.2
## Requirements

* PHP ≥ 8.0
* Curl for PHP must be enabled.
* Telegram API Key, you can get one simply with [@BotFather](https://core.telegram.org/bots#botfather) with simple commands right after creating your bot.

Expand All @@ -24,8 +22,8 @@ Since the August 29 update you can use a self-signed ssl certificate.
For the GetUpdates:
* Some way to execute the script in order to serve messages (for example cronjob)

Installation
---------
## Installation

You can install this library with composer:

`composer require lukasss93/telegrambot-php`
Expand All @@ -37,10 +35,6 @@ Navigate to
https://api.telegram.org/bot(TOKEN)/setWebhook?url=https://yoursite.com/your_update.php
Or use the Telegram class setWebhook method.

Informations
---------

This simple framework is object-based, all methods return a Telegram Object contained in TelegramBot/Types namespace.

Examples
---------
Expand Down Expand Up @@ -210,18 +204,23 @@ $bot->buildForceReply($selective=true);
Show a Reply interface to the user.
Check [ForceReply](https://core.telegram.org/bots/api#forcereply) for more info.

Contact me
------------
You can contact me [via Telegram](https://telegram.me/Lukasss93) but if you have an issue
please [open](https://github.com/Lukasss93/telegrambot-php/issues) one.

To-Do list
----------
* Optional predictive parameters in methods
* Optimize keyboards
* Chat conversations
* Commands listener with callback + events

Changelog
------------
All notable changes to this project will be documented [here](CHANGELOG.md).
## Changelog

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

## Credits

- [Luca Patera](https://github.com/Lukasss93)
- [All Contributors](../../contributors)

## License

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

199 changes: 199 additions & 0 deletions src/Client.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
<?php

namespace TelegramBot;

use Exception;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Support\Traits\Macroable;
use JsonException;
use JsonSerializable;
use Psr\Http\Message\ResponseInterface;
use RuntimeException;
use stdClass;
use TelegramBot\Endpoints\AvailableMethods;
use TelegramBot\Endpoints\Games;
use TelegramBot\Endpoints\GettingUpdates;
use TelegramBot\Endpoints\InlineMode;
use TelegramBot\Endpoints\Passport;
use TelegramBot\Endpoints\Payments;
use TelegramBot\Endpoints\Stickers;
use TelegramBot\Endpoints\UpdatesMessages;
use TelegramBot\Exceptions\TelegramException;
use TelegramBot\Types\File;
use TelegramBot\Types\InputFile;
use TelegramBot\Types\Message;

/**
* @mixin TelegramBot
*/
trait Client
{
use GettingUpdates, AvailableMethods, Games, InlineMode, Passport, Payments, Stickers, UpdatesMessages;
use Macroable;

/**
* Send generic request.
* @param string $endpoint
* @param array $parameters
* @param array $clientOpt
* @return mixed
* @throws GuzzleException
* @throws JsonException
* @throws TelegramException
*/
public function sendRequest(string $endpoint, array $parameters = [], array $clientOpt = []): mixed
{
return $this->requestMultipart($endpoint, $parameters, clientOpt: $clientOpt);
}

/**
* Send a JSON request.
* @param string $endpoint
* @param array|null $json
* @param string $mapTo
* @param array $options
* @return mixed
* @throws JsonException
* @throws TelegramException
* @throws GuzzleException
*/
protected function requestJson(string $endpoint, ?array $json = null, string $mapTo = stdClass::class, array $options = []): mixed
{
try {
$response = $this->http->post($endpoint, array_merge([
'json' => $json,
], $options));
return $this->mapResponse($response, $mapTo);
} catch (RequestException $exception) {
if (!$exception->hasResponse()) {
throw $exception;
}
return $this->mapResponse($exception->getResponse(), $mapTo, $exception);
}
}

/**
* Send a multipart/form-data request.
* @param string $endpoint
* @param array|null $multipart
* @param string $mapTo
* @param array $clientOpt
* @return mixed
* @throws GuzzleException
* @throws JsonException
* @throws TelegramException
*/
protected function requestMultipart(string $endpoint, ?array $multipart = null, string $mapTo = stdClass::class, array $clientOpt = []): mixed
{
$parameters = array_map(static fn ($name, $contents) => match (true) {
$contents instanceof InputFile => [
'name' => $name,
'contents' => $contents->getResource(),
'filename' => $contents->getFilename(),
],
$contents instanceof JsonSerializable => [
'name' => $name,
'contents' => json_encode($contents),
],
default => [
'name' => $name,
'contents' => $contents,
]
}, array_keys($multipart), $multipart);
try {
$response = $this->http->post($endpoint, array_merge(['multipart' => $parameters], $clientOpt));
return $this->mapResponse($response, $mapTo);
} catch (RequestException $exception) {
if (!$exception->hasResponse()) {
throw $exception;
}
return $this->mapResponse($exception->getResponse(), $mapTo, $exception);
}
}

/**
* Send a common multipart/form-data request with fallback to JSON.
* @param int|string $chat_id
* @param string $endpoint
* @param string $param
* @param mixed $value
* @param array $opt
* @param array $clientOpt
* @return Message|null
* @throws GuzzleException
* @throws JsonException
* @throws TelegramException
*/
protected function sendAttachment(int|string $chat_id, string $endpoint, string $param, mixed $value, array $opt = [], array $clientOpt = []): ?Message
{
$required = [
'chat_id' => $chat_id,
$param => $value,
];
if (is_resource($value) || $value instanceof InputFile) {
$required[$param] = $value instanceof InputFile ? $value : new InputFile($value);
return $this->requestMultipart($endpoint, array_merge($required, $opt), Message::class, $clientOpt);
}
return $this->requestJson($endpoint, array_merge($required, $opt), Message::class);
}

/**
* Map a response to a given class.
* @param ResponseInterface $response
* @param string $mapTo
* @param Exception|null $clientException
* @return mixed
* @throws TelegramException
* @throws JsonException
*/
protected function mapResponse(ResponseInterface $response, string $mapTo, Exception $clientException = null): mixed
{
$json = json_decode((string)$response->getBody(), flags: JSON_THROW_ON_ERROR);
if ($json?->ok) {
return match (true) {
is_scalar($json->result) => $json->result,
is_array($json->result) => $this->hydrator->hydrateArray($json->result, new $mapTo),
default => $this->hydrator->hydrate($json->result, new $mapTo)
};
}
throw new TelegramException(
$json?->description ?? 'Client exception',
$json?->error_code ?? 0,
$clientException
);
}

/**
* Get the download url for a File object.
* @param File $file
* @return string|null
*/
public function downloadUrl(File $file): string|null
{
if ($this->config['is_local']) {
return $file->file_path;
}

return $this->getFileUrl($file->file_path);
}

/**
* Save file to disk.
* @param File $file
* @param string $path
* @param array $clientOpt
* @return bool
* @throws GuzzleException
*/
public function downloadFile(File $file, string $path, array $clientOpt = []): bool
{
if (!is_dir(dirname($path)) && !mkdir($concurrentDirectory = dirname($path), true,
true) && !is_dir($concurrentDirectory)) {
throw new RuntimeException(sprintf('Error creating directory "%s"', $concurrentDirectory));
}

$response = $this->http->get($this->downloadUrl($file), array_merge(['sink' => $path], $clientOpt));
return $response->getStatusCode() === 200;
}
}
9 changes: 0 additions & 9 deletions src/Constants/ParseModes.php

This file was deleted.

Loading