1672281742
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.
Documentation for the SDK can be found on the website.
If you're using this SDK to build your Telegram Bots, We'd love to know and share the bot with the world. Tell us about it - here
Check out the Who's Using Telegram Bot SDK wiki page to know more about what people have been building with this SDK.
Any issues, feedback, suggestions or questions please use issue tracker here.
Thank you for considering contributing to the project. Please review the CONTRIBUTING guidelines before submitting any pull requests.
This project and its author is neither associated, nor affiliated with Telegram in anyway. See License section for more details.
Author: irazasyed
Source Code: https://github.com/irazasyed/telegram-bot-sdk
License: BSD-3-Clause license
#bot #php #laravel #composer #sdk
1666259580
A Telegram Bot based on the official Telegram Bot API
This is a pure PHP Telegram Bot, fully extensible via plugins.
Telegram announced official support for a Bot API, allowing integrators of all sorts to bring automated interactions to the mobile platform. This Bot aims to provide a platform where one can simply write a bot and have interactions in a matter of minutes.
The Bot can:
This code is available on GitHub. Pull requests are welcome.
Message @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
, where you should be able to initiate a conversation. Be careful not to send it to the wrong contact, because some users have similar usernames to BotFather
.
@BotFather
replies with:
Alright, a new bot. How are we going to call it? Please choose a name for your bot.
Type whatever name you want for your bot.
@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.
Type whatever username you want for your bot, minimum 5 characters, and must end with bot
. For example: telesample_bot
@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.
Use this token to access the HTTP API:
123456789:AAG90e14-0f8-40183D-18491dDE
For a description of the Bot API, see this page:
https://core.telegram.org/bots/api
Note down the 'token' mentioned above.
Optionally set the bot privacy:
Send /setprivacy
to @BotFather
.
@BotFather
replies with:
Choose a bot to change group messages settings.
Type (or select) @telesample_bot
(change to the username you set at step 5 above, but start it with @
)
@BotFather
replies with:
'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
Type (or select) Disable
to let your bot receive all messages sent to a group.
@BotFather
replies with:
Success! The new status is: DISABLED. /help
Install this package through Composer. Edit your project's composer.json
file to require longman/telegram-bot
.
Create composer.json file
{
"name": "yourproject/yourproject",
"type": "project",
"require": {
"php": ">=7.3",
"longman/telegram-bot": "*"
}
}
and run composer update
or
run this command in your command line:
composer require longman/telegram-bot
The bot can handle updates with Webhook or getUpdates method:
Webhook | getUpdates | |
---|---|---|
Description | Telegram sends the updates directly to your host | You have to fetch Telegram updates manually |
Host with https | Required | Not required |
MySQL | Not required | (Not) Required |
For advanced users only!
As from Telegram Bot API 5.0, users can run their own Bot API server to handle updates. This means, that the PHP Telegram Bot needs to be configured to serve that custom URI. Additionally, you can define the URI where uploaded files to the bot can be downloaded (note the {API_KEY}
placeholder).
Longman\TelegramBot\Request::setCustomBotApiUri(
$api_base_uri = 'https://your-bot-api-server', // Default: https://api.telegram.org
$api_base_download_uri = '/path/to/files/{API_KEY}' // Default: /file/bot{API_KEY}
);
Note: If you are running your bot in --local
mode, you won't need the Request::downloadFile()
method, since you can then access your files directly from the absolute path returned by Request::getFile()
.
Note: For a more detailed explanation, head over to the example-bot repository and follow the instructions there.
In order to set a Webhook you need a server with HTTPS and composer support. (For a self signed certificate you need to add some extra code)
Create set.php with the following contents:
<?php
// Load composer
require __DIR__ . '/vendor/autoload.php';
$bot_api_key = 'your:bot_api_key';
$bot_username = 'username_bot';
$hook_url = 'https://your-domain/path/to/hook.php';
try {
// Create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username);
// Set webhook
$result = $telegram->setWebhook($hook_url);
if ($result->isOk()) {
echo $result->getDescription();
}
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
// log telegram errors
// echo $e->getMessage();
}
Open your set.php via the browser to register the webhook with Telegram. You should see Webhook was set
.
Now, create hook.php with the following contents:
<?php
// Load composer
require __DIR__ . '/vendor/autoload.php';
$bot_api_key = 'your:bot_api_key';
$bot_username = 'username_bot';
try {
// Create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username);
// Handle telegram webhook request
$telegram->handle();
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
// Silence is golden!
// log telegram errors
// echo $e->getMessage();
}
Upload the certificate and add the path as a parameter in set.php:
$result = $telegram->setWebhook($hook_url, ['certificate' => '/path/to/certificate']);
Edit unset.php with your bot credentials and execute it.
For best performance, the MySQL database should be enabled for the getUpdates
method!
Create getUpdatesCLI.php with the following contents:
#!/usr/bin/env php
<?php
require __DIR__ . '/vendor/autoload.php';
$bot_api_key = 'your:bot_api_key';
$bot_username = 'username_bot';
$mysql_credentials = [
'host' => 'localhost',
'port' => 3306, // optional
'user' => 'dbuser',
'password' => 'dbpass',
'database' => 'dbname',
];
try {
// Create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username);
// Enable MySQL
$telegram->enableMySql($mysql_credentials);
// Handle telegram getUpdates request
$telegram->handleGetUpdates();
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
// log telegram errors
// echo $e->getMessage();
}
Next, give the file permission to execute:
$ chmod +x getUpdatesCLI.php
Lastly, run it!
$ ./getUpdatesCLI.php
If you choose to / or are obliged to use the getUpdates
method without a database, you can replace the $telegram->useMySQL(...);
line above with:
$telegram->useGetUpdatesWithoutDatabase();
:exclamation: Note that by default, Telegram will send any new update types that may be added in the future. This may cause commands that don't take this into account to break!
It is suggested that you specifically define which update types your bot can receive and handle correctly.
You can define which update types are sent to your bot by defining them when setting the webhook or passing an array of allowed types when using getUpdates.
use Longman\TelegramBot\Entities\Update;
// For all update types currently implemented in this library:
// $allowed_updates = Update::getUpdateTypes();
// Define the list of allowed Update types manually:
$allowed_updates = [
Update::TYPE_MESSAGE,
Update::TYPE_CHANNEL_POST,
// etc.
];
// When setting the webhook.
$telegram->setWebhook($hook_url, ['allowed_updates' => $allowed_updates]);
// When handling the getUpdates method.
$telegram->handleGetUpdates(['allowed_updates' => $allowed_updates]);
Alternatively, Update processing can be allowed or denied by defining a custom update filter.
Let's say we only want to allow messages from a user with ID 428
, we can do the following before handling the request:
$telegram->setUpdateFilter(function (Update $update, Telegram $telegram, &$reason = 'Update denied by update_filter') {
$user_id = $update->getMessage()->getFrom()->getId();
if ($user_id === 428) {
return true;
}
$reason = "Invalid user with ID {$user_id}";
return false;
});
The reason for denying an update can be defined with the $reason
parameter. This text gets written to the debug log.
All types are implemented according to Telegram API 6.2 (August 2022).
Full support for inline query according to Telegram API 6.2 (August 2022).
All methods are implemented according to Telegram API 6.2 (August 2022).
Messages longer than 4096 characters are split up into multiple messages.
$result = Request::sendMessage([
'chat_id' => $chat_id,
'text' => 'Your utf8 text đ ...',
]);
To send a local photo, add it properly to the $data
parameter using the file path:
$result = Request::sendPhoto([
'chat_id' => $chat_id,
'photo' => Request::encodeFile('/path/to/pic.jpg'),
]);
If you know the file_id
of a previously uploaded file, just use it directly in the data array:
$result = Request::sendPhoto([
'chat_id' => $chat_id,
'photo' => 'AAQCCBNtIhAoAAss4tLEZ3x6HzqVAAqC',
]);
To send a remote photo, use the direct URL instead:
$result = Request::sendPhoto([
'chat_id' => $chat_id,
'photo' => 'https://example.com/path/to/pic.jpg',
]);
sendAudio, sendDocument, sendAnimation, sendSticker, sendVideo, sendVoice and sendVideoNote all work in the same way, just check the API documentation for the exact usage. See the ImageCommand.php for a full example.
Request::sendChatAction([
'chat_id' => $chat_id,
'action' => Longman\TelegramBot\ChatAction::TYPING,
]);
Retrieve the user photo. (see WhoamiCommand.php for a full example)
Get the file path and download it. (see WhoamiCommand.php for a full example)
To do this you have to enable the MySQL connection. Here's an example of use (check DB::selectChats()
for parameter usage):
$results = Request::sendToActiveChats(
'sendMessage', // Callback function to execute (see Request.php methods)
['text' => 'Hey! Check out the new features!!'], // Param to evaluate the request
[
'groups' => true,
'supergroups' => true,
'channels' => false,
'users' => true,
]
);
You can also broadcast a message to users, from the private chat with your bot. Take a look at the admin commands below.
If you want to save messages/users/chats for further usage in commands, create a new database (utf8mb4_unicode_520_ci
), import structure.sql and enable MySQL support BEFORE handle()
method:
$mysql_credentials = [
'host' => 'localhost',
'port' => 3306, // optional
'user' => 'dbuser',
'password' => 'dbpass',
'database' => 'dbname',
];
$telegram->enableMySql($mysql_credentials);
You can set a custom prefix to all the tables while you are enabling MySQL:
$telegram->enableMySql($mysql_credentials, $bot_username . '_');
You can also store inline query and chosen inline query data in the database.
It is possible to provide the library with an external MySQL PDO connection. Here's how to configure it:
$telegram->enableExternalMySql($external_pdo_connection);
//$telegram->enableExternalMySql($external_pdo_connection, $table_prefix)
All methods implemented can be used to manage channels. With admin commands you can manage your channels directly with your bot private chat.
The bot is able to recognise commands in a chat with multiple bots (/command@mybot).
It can also execute commands that get triggered by events, so-called Service Messages.
Maybe you would like to develop your own commands. There is a guide to help you create your own commands.
Also, be sure to have a look at the example commands to learn more about custom commands and how they work.
You can add your custom commands in different ways:
// Add a folder that contains command files
$telegram->addCommandsPath('/path/to/command/files');
//$telegram->addCommandsPaths(['/path/to/command/files', '/another/path']);
// Add a command directly using the class name
$telegram->addCommandClass(MyCommand::class);
//$telegram->addCommandClasses([MyCommand::class, MyOtherCommand::class]);
With this method you can set some command specific parameters, for example:
// Google geocode/timezone API key for /date command
$telegram->setCommandConfig('date', [
'google_api_key' => 'your_google_api_key_here',
]);
// OpenWeatherMap API key for /weather command
$telegram->setCommandConfig('weather', [
'owm_api_key' => 'your_owm_api_key_here',
]);
Enabling this feature, the bot admin can perform some super user commands like:
Take a look at all default admin commands stored in the src/Commands/AdminCommands/ folder.
You can specify one or more admins with this option:
// Single admin
$telegram->enableAdmin(your_telegram_user_id);
// Multiple admins
$telegram->enableAdmins([
your_telegram_user_id,
other_telegram_user_id,
]);
Telegram user id can be retrieved with the /whoami command.
To enable this feature follow these steps:
$telegram->setCommandConfig('sendtochannel', [
'your_channel' => [
'@type_here_your_channel',
]
]);
$telegram->setCommandConfig('sendtochannel', [
'your_channel' => [
'@type_here_your_channel',
'@type_here_another_channel',
'@and_so_on',
]
]);
To use the Upload and Download functionality, you need to set the paths with:
$telegram->setDownloadPath('/your/path/Download');
$telegram->setUploadPath('/your/path/Upload');
Take a look at the repo Wiki for further information and tutorials! Feel free to improve!
All project assets can be found in the assets repository.
We're busy working on a full A-Z example bot, to help get you started with this library and to show you how to use all its features. You can check the progress of the example-bot repository).
Here's a list of projects that feats this library, feel free to add yours!
If you like living on the edge, please report any bugs you find on the PHP Telegram Bot issues page.
See CONTRIBUTING for more information.
See SECURITY for more information.
Available as part of the Tidelift Subscription.
The maintainers of PHP Telegram Bot
and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.
Credit list in CREDITS
Author: php-telegram-bot
Source Code: https://github.com/php-telegram-bot/core
License: MIT license
1595396220
As more and more data is exposed via APIs either as API-first companies or for the explosion of single page apps/JAMStack, API security can no longer be an afterthought. The hard part about APIs is that it provides direct access to large amounts of data while bypassing browser precautions. Instead of worrying about SQL injection and XSS issues, you should be concerned about the bad actor who was able to paginate through all your customer records and their data.
Typical prevention mechanisms like Captchas and browser fingerprinting wonât work since APIs by design need to handle a very large number of API accesses even by a single customer. So where do you start? The first thing is to put yourself in the shoes of a hacker and then instrument your APIs to detect and block common attacks along with unknown unknowns for zero-day exploits. Some of these are on the OWASP Security API list, but not all.
Most APIs provide access to resources that are lists of entities such as /users
or /widgets
. A client such as a browser would typically filter and paginate through this list to limit the number items returned to a client like so:
First Call: GET /items?skip=0&take=10
Second Call: GET /items?skip=10&take=10
However, if that entity has any PII or other information, then a hacker could scrape that endpoint to get a dump of all entities in your database. This could be most dangerous if those entities accidently exposed PII or other sensitive information, but could also be dangerous in providing competitors or others with adoption and usage stats for your business or provide scammers with a way to get large email lists. See how Venmo data was scraped
A naive protection mechanism would be to check the take count and throw an error if greater than 100 or 1000. The problem with this is two-fold:
skip = 0
while True: response = requests.post('https://api.acmeinc.com/widgets?take=10&skip=' + skip), headers={'Authorization': 'Bearer' + ' ' + sys.argv[1]}) print("Fetched 10 items") sleep(randint(100,1000)) skip += 10
To secure against pagination attacks, you should track how many items of a single resource are accessed within a certain time period for each user or API key rather than just at the request level. By tracking API resource access at the user level, you can block a user or API key once they hit a threshold such as âtouched 1,000,000 items in a one hour periodâ. This is dependent on your API use case and can even be dependent on their subscription with you. Like a Captcha, this can slow down the speed that a hacker can exploit your API, like a Captcha if they have to create a new user account manually to create a new API key.
Most APIs are protected by some sort of API key or JWT (JSON Web Token). This provides a natural way to track and protect your API as API security tools can detect abnormal API behavior and block access to an API key automatically. However, hackers will want to outsmart these mechanisms by generating and using a large pool of API keys from a large number of users just like a web hacker would use a large pool of IP addresses to circumvent DDoS protection.
The easiest way to secure against these types of attacks is by requiring a human to sign up for your service and generate API keys. Bot traffic can be prevented with things like Captcha and 2-Factor Authentication. Unless there is a legitimate business case, new users who sign up for your service should not have the ability to generate API keys programmatically. Instead, only trusted customers should have the ability to generate API keys programmatically. Go one step further and ensure any anomaly detection for abnormal behavior is done at the user and account level, not just for each API key.
APIs are used in a way that increases the probability credentials are leaked:
If a key is exposed due to user error, one may think you as the API provider has any blame. However, security is all about reducing surface area and risk. Treat your customer data as if itâs your own and help them by adding guards that prevent accidental key exposure.
The easiest way to prevent key exposure is by leveraging two tokens rather than one. A refresh token is stored as an environment variable and can only be used to generate short lived access tokens. Unlike the refresh token, these short lived tokens can access the resources, but are time limited such as in hours or days.
The customer will store the refresh token with other API keys. Then your SDK will generate access tokens on SDK init or when the last access token expires. If a CURL command gets pasted into a GitHub issue, then a hacker would need to use it within hours reducing the attack vector (unless it was the actual refresh token which is low probability)
APIs open up entirely new business models where customers can access your API platform programmatically. However, this can make DDoS protection tricky. Most DDoS protection is designed to absorb and reject a large number of requests from bad actors during DDoS attacks but still need to let the good ones through. This requires fingerprinting the HTTP requests to check against what looks like bot traffic. This is much harder for API products as all traffic looks like bot traffic and is not coming from a browser where things like cookies are present.
The magical part about APIs is almost every access requires an API Key. If a request doesnât have an API key, you can automatically reject it which is lightweight on your servers (Ensure authentication is short circuited very early before later middleware like request JSON parsing). So then how do you handle authenticated requests? The easiest is to leverage rate limit counters for each API key such as to handle X requests per minute and reject those above the threshold with a 429 HTTP response.
There are a variety of algorithms to do this such as leaky bucket and fixed window counters.
APIs are no different than web servers when it comes to good server hygiene. Data can be leaked due to misconfigured SSL certificate or allowing non-HTTPS traffic. For modern applications, there is very little reason to accept non-HTTPS requests, but a customer could mistakenly issue a non HTTP request from their application or CURL exposing the API key. APIs do not have the protection of a browser so things like HSTS or redirect to HTTPS offer no protection.
Test your SSL implementation over at Qualys SSL Test or similar tool. You should also block all non-HTTP requests which can be done within your load balancer. You should also remove any HTTP headers scrub any error messages that leak implementation details. If your API is used only by your own apps or can only be accessed server-side, then review Authoritative guide to Cross-Origin Resource Sharing for REST APIs
APIs provide access to dynamic data thatâs scoped to each API key. Any caching implementation should have the ability to scope to an API key to prevent cross-pollution. Even if you donât cache anything in your infrastructure, you could expose your customers to security holes. If a customer with a proxy server was using multiple API keys such as one for development and one for production, then they could see cross-pollinated data.
#api management #api security #api best practices #api providers #security analytics #api management policies #api access tokens #api access #api security risks #api access keys
1672281742
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.
Documentation for the SDK can be found on the website.
If you're using this SDK to build your Telegram Bots, We'd love to know and share the bot with the world. Tell us about it - here
Check out the Who's Using Telegram Bot SDK wiki page to know more about what people have been building with this SDK.
Any issues, feedback, suggestions or questions please use issue tracker here.
Thank you for considering contributing to the project. Please review the CONTRIBUTING guidelines before submitting any pull requests.
This project and its author is neither associated, nor affiliated with Telegram in anyway. See License section for more details.
Author: irazasyed
Source Code: https://github.com/irazasyed/telegram-bot-sdk
License: BSD-3-Clause license
1601381326
Weâve conducted some initial research into the public APIs of the ASX100 because we regularly have conversations about what others are doing with their APIs and what best practices look like. Being able to point to good local examples and explain what is happening in Australia is a key part of this conversation.
The method used for this initial research was to obtain a list of the ASX100 (as of 18 September 2020). Then work through each company looking at the following:
With regards to how the APIs are shared:
#api #api-development #api-analytics #apis #api-integration #api-testing #api-security #api-gateway
1642259940
If you're using this SDK to build your Telegram Bots, We'd love to know and share the bot with the world. Tell us about it - here
Check out the Who's Using Telegram Bot SDK wiki page to know more about what people have been building with this SDK.
Any issues, feedback, suggestions or questions please use issue tracker here.
Thank you for considering contributing to the project. Please review the CONTRIBUTING guidelines before submitting any pull requests.
Documentation for the SDK can be found on the website.
Download Details:
Author: irazasyed
Source Code: https://github.com/irazasyed/telegram-bot-sdk
License: BSD-3-Clause License