Giter VIP home page Giter VIP logo

core's Introduction

PHP Telegram Bot

PHP Telegram Bot logo

A Telegram Bot based on the official Telegram Bot API

API Version Join the bot support group on Telegram Donate

Tests Code Coverage Code Quality Latest Stable Version Dependencies Total Downloads Downloads Month Minimum PHP Version License

Table of Contents

Introduction

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:

  • Retrieve updates with webhook and getUpdates methods.
  • Supports all types and methods according to Telegram Bot API 6.9 (September 2023).
  • Supports supergroups.
  • Handle commands in chat with other bots.
  • Manage Channel from the bot admin interface.
  • Full support for inline bots.
  • Inline keyboard.
  • Messages, InlineQuery and ChosenInlineQuery are stored in the Database.
  • Conversation feature.

This code is available on GitHub. Pull requests are welcome.

Instructions

Create your first bot

  1. 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 initial conversation

  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.
    
  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.
    
    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
    
  7. Note down the 'token' mentioned above.

Optionally set the bot privacy:

  1. Send /setprivacy to @BotFather.

    BotFather later conversation

  2. @BotFather replies with:

    Choose a bot to change group messages settings.
    
  3. Type (or select) @telesample_bot (change to the username you set at step 5 above, but start it with @)

  4. @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
    
  5. Type (or select) Disable to let your bot receive all messages sent to a group.

  6. @BotFather replies with:

    Success! The new status is: DISABLED. /help
    

Require this package with Composer

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

Choose how to retrieve Telegram updates

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

Using a custom Bot API server

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().

Webhook installation

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();
}

Self Signed Certificate

Upload the certificate and add the path as a parameter in set.php:

$result = $telegram->setWebhook($hook_url, ['certificate' => '/path/to/certificate']);

Unset Webhook

Edit unset.php with your bot credentials and execute it.

getUpdates installation

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

getUpdates without database

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();

Filter Update

โ— 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.

Support

Types

All types are implemented according to Telegram API 6.9 (September 2023).

Inline Query

Full support for inline query according to Telegram API 6.9 (September 2023).

Methods

All methods are implemented according to Telegram API 6.9 (September 2023).

Send Message

Messages longer than 4096 characters are split up into multiple messages.

$result = Request::sendMessage([
    'chat_id' => $chat_id,
    'text'    => 'Your utf8 text ๐Ÿ˜œ ...',
]);

Send Photo

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.

Send Chat Action

Request::sendChatAction([
    'chat_id' => $chat_id,
    'action'  => Longman\TelegramBot\ChatAction::TYPING,
]);

getUserProfilePhoto

Retrieve the user photo. (see WhoamiCommand.php for a full example)

getFile and downloadFile

Get the file path and download it. (see WhoamiCommand.php for a full example)

Send message to all active chats

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.

Utils

MySQL storage (Recommended)

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.

External Database connection

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)

Channels Support

All methods implemented can be used to manage channels. With admin commands you can manage your channels directly with your bot private chat.

Commands

Predefined Commands

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.

Custom Commands

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]);

Commands Configuration

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',
]);

Admin Commands

Enabling this feature, the bot admin can perform some super user commands like:

  • List all the chats started with the bot /chats
  • Clean up old database entries /cleanup
  • Show debug information about the bot /debug
  • Send message to all chats /sendtoall
  • Post any content to your channels /sendtochannel
  • Inspect a user or a chat with /whois

Take a look at all default admin commands stored in the src/Commands/AdminCommands/ folder.

Set Admins

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.

Channel Administration

To enable this feature follow these steps:

  • 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.
  • Enter your channel name as a parameter for the /sendtochannel command:
$telegram->setCommandConfig('sendtochannel', [
    'your_channel' => [
        '@type_here_your_channel',
    ]
]);
  • If you want to manage more channels:
$telegram->setCommandConfig('sendtochannel', [
    'your_channel' => [
        '@type_here_your_channel',
        '@type_here_another_channel',
        '@and_so_on',
    ]
]);
  • Enjoy!

Upload and Download directory path

To use the Upload and Download functionality, you need to set the paths with:

$telegram->setDownloadPath('/your/path/Download');
$telegram->setUploadPath('/your/path/Upload');

Documentation

Take a look at the repo Wiki for further information and tutorials! Feel free to improve!

Assets

All project assets can be found in the assets repository.

Example bot

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).

Projects with this library

Here's a list of projects that feats this library, feel free to add yours!

Troubleshooting

If you like living on the edge, please report any bugs you find on the PHP Telegram Bot issues page.

Contributing

See CONTRIBUTING for more information.

Security

See SECURITY for more information.

Donate

All work on this bot consists of many hours of coding during our free time, to provide you with a Telegram Bot library that is easy to use and extend. If you enjoy using this library and would like to say thank you, donations are a great way to show your support.

Donations are invested back into the project ๐Ÿ‘

Thank you for keeping this project alive ๐Ÿ™

For enterprise

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.

License

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

Credits

Credit list in CREDITS


core's People

Contributors

1int avatar akalongman avatar alesinicio avatar andreybolonin avatar cookieseater avatar crazyredscorp avatar dva-re avatar enescakir avatar habetdin avatar hutattedonmyarm avatar imanghafoori1 avatar jacklul avatar jyxjjj avatar lichtscheu avatar maxiride avatar mboretto avatar mlocati avatar noplanman avatar oxmohsen avatar sabas avatar sedovserge avatar setnemo avatar smoqadam avatar taeir avatar tiifuchs avatar uspilot avatar volandku avatar vrcif avatar wright-tw avatar zahhar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

core's Issues

DB fatal error after forward photo to bot!

I forwarded one photo from a third person to my bot and now when I try to run "getUpdatesCLI.php", below error added on error log:

[18-Sep-2015 10:54:19] PHP Catchable fatal error: Object of class Longman\TelegramBot\Entities\User could not be converted to string in /home/x/xxx.com/telegram/vendor/longman/telegram-bot/src/DB.php on line 230

Catchable fatal error - could not be converted to string

I've cloned and upload on my host the LAST VERSION (packagist v0.17.0), but if i run example-set.php on a host with php 5.4 and i will get this error:

Catchable fatal error: Object of class Longman\TelegramBot\Entities\ServerResponse could not be converted to string in /var/www/vhosts/XXXXXXXXXXX/XXXXXXXXXX/weiddolo/set.php on line 16

getUpdateCLI.php - SSL certificate problem: self signed certificate in certificate chain

Hi, i used getUpdate Method and when opened getUpdateCLI.php , bot does not reply to me , i get this error:

exception 'Longman\TelegramBot\Exception\TelegramException' with message 'SSL certificate problem: self signed certificate in certificate chain' in C:\xampp\htdocs\Longman\TelegramBot\src\Request.php:161 Stack trace: #0 C:\xampp\htdocs\Longman\TelegramBot\src\Request.php(239): Longman\TelegramBot\Request::executeCurl('getUpdates', Array) #1 C:\xampp\htdocs\Longman\TelegramBot\src\Request.php(394): Longman\TelegramBot\Request::send('getUpdates', Array) #2 C:\xampp\htdocs\Longman\TelegramBot\src\Telegram.php(364): Longman\TelegramBot\Request::getUpdates(Array) #3 C:\xampp\htdocs\Longman\TelegramBot\example-getUpdatesCLI.php(42): Longman\TelegramBot\Telegram->handleGetUpdates() #4 {main}

This is my getUpdateCLI.php:

'localhost:3306', 'user'=>'root', 'password'=>'XXXXX', 'database'=>'dbname'); try { // create Telegram API object $telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME); $telegram->enableMySQL($credentials); $telegram->handleGetUpdates(); //Options // $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'); //$telegram->setLogVerbosity(3); //$telegram->setDownloadPath("../Download"); //$telegram->setUploadPath("../Upload"); // $results = $telegram->sendToActiveChats( // 'sendMessage', //callback function to execute (see Request.php methods) // 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 // null //'yyyy-mm-dd hh:mm:ss' date range to // ); // $results = $telegram->handle(); // handle telegram getUpdate request } catch (Longman\TelegramBot\Exception\TelegramException $e) { // log telegram errors echo $e; }

error in composer

Hi dear, when I use this command " composer require longman/telegram-bot " I got this error
"
Using version dev-master for longman/telegram-bot
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
- The requested package longman/telegram-bot No version set (parsed as 1.0.0
) could not be found.

Potential causes:

Read https://getcomposer.org/doc/articles/troubleshooting.md for further commo
n problems.

Installation failed, reverting ./composer.json to its original content.
"

Can u say me, What should I do ????

Smart Interfaces

Hello! The bot holds command like:
/commands@bot args
But this isn't the best way to create a user friendly interface.

I would like to build an interface like this:
user: /weather@bot
bot: Enter location
user: London
bot: Show weather in London

Have you aver think about a way to track all the massage and execute a command at the end?

Custom commands name problems

Hello there, i noticed that some custom name commands work and others not.
I didn't set any custom path, i directly wrote inside the original commands path... i made a command that allows to see the user stats, it just works fine but only under specific names "/slap"...i tried it with "/SeeStats" and it didn't work. I also created another command under the name "/SetWelcome" and this works. What can i do?

Installation

Hello! Very nice work!
I manage to install it becouse the method:
$telegram->setWebHook('https://yourdomain/yourpath_to_hook.php');
does not exist!
I tryed to add it like this
public function setWebHook($url_hook){
return Request::send('setWebhook',array('url'=>urlencode($url_hook)));
}

but i get a bad request from telegram api

finally i set up the web hook simply with:
https://api.telegram.org/bot{token}/setWebhook?url=https://yourdomain.org/yourpath/hook.php

Seems to me that telegram api don't accept escaped slash like:
https://yourdomain.org/yourpath/hook.php

tests folder showing empty

runned tests folder all pages but showing webpage null.no information.what is the use of tests folder

MySQL logging works only with no other commands active, but then HTTP/500

I can only get hook.php running if I take ./vendor/longman/telegram-bot/example-hook.php and uncomment $telegram->enableMySQL($credentials);.

Then all commands sent to the bot are logged in the MySQL table messages while hook.php answers the HTTP request from the Telegram API server with a HTTP/500 and also the error reported in #38 is logged.

If I activate another command, e.g. $telegram->addCommandsPath($COMMANDS_FOLDER);, hook.php answers with a HTTP/200 and no error logged, but nothing is written into the messages table โ€“ very strange!

New commands not work

I have wrote a new command based on help command

<?php
namespace Longman\TelegramBot\Commands;

use Longman\TelegramBot\Request;
use Longman\TelegramBot\Command;
use Longman\TelegramBot\Entities\Update;

class NicoCommand extends Command
{
    public function execute() {
        $update = $this->getUpdate();
        $message = $this->getMessage();

        $chat_id = $message->getChat()->getId();
        $text = $message->getText(true);

        $data = array();
        $data['chat_id'] = $chat_id;
        $data['text'] = "Sorry, ........";

        $result = Request::sendMessage($data);
    }
}

But when I write /nico it not work ๐Ÿ˜ข

What's wrong ?

(Sorry for my bad english ๐Ÿ˜ )

one question , array or object

i appreciate your effort for this library .
but i have one question , trying to figure out why

$a_result= json_decode($result, true) // parse as array, not object
$o_message = new Message($a_result,$c_bot_name) // make messageobject from array

my question is, why decode with a array,
is there any problem or some other reasons that you do not make a target object from object?
(example)
$o_result= json_decode($result) // parse as object
$o_message = new Message($o_result,$c_bot_name) // make object from object

First response

When I run the code nothing happens ("Input is empty!")
What should I do, what I would write to the bot (for example /newcommand) and he will respone "Hello Dmitry!" ?
Please, help me to write my first simple bot app.

Use custom path

Hi! I want use multiple bots.
I added this to file hook.php
$telegram->addCommandsPath(BASE_PATH.'/Commands/MuzUzBot');
I created file to folder /vendor/longmang/telegram-bot/src/Commands/MuzUzBot and file HelpCommand.php

This command not working :( How to use it?

Fail fetch updates

can you explain step by step installation after creating telegram bot.
i got this error Fail fetch updates

Disabling WebHook

It is valid to set URL to an empty string to disable a webhook.
Either not throw exception when URL is empty in setWebHook() or create a disableWebHook() method.
Thanks!!!

Sending long messages

Can't send long messages (over 6000).
How to correctly split message and send each part as separate messages?

Sending emojis

Hi,

First of all thanks for your code and work, it makes very easy to make a bot.

I want to send emojis and I can't see how to do it.

I've sent to a log file all messages I recive and I sent in the conversation with the bot. Then I sent to the bot all the emojis I want. Then I tried to resent the message I recived and the emoji was shown.

But, when I try to send the text I have in my log file, it doesn't work at all...

My log:
2015-10-29 8:48:31 Jontxu ha puesto lo siguiente : \ud83d\udc4e\n\n"

In my code I tried all I find:

$data['text'] .= "\n" . '\ud83d\udc4e\n\n'

OR

$data['text'] .= "\n" . utf8_encode('\ud83d\udc4e\n\n')

OR

$data['text'] .= "\n" . utf8_decode('\ud83d\udc4e\n\n')

OR as I have read here: http://stackoverflow.com/questions/31279158/unicode-characters-like-emoticons-in-telegram-bot-message-or-keyboard

$data['text'] .= "\n" . '\xF0\x9F\x91\x8E'

Can you please give me a clue?

Thanks!

Sequential chat

Hi, is possible to make sequential chat?

I would like to build an interface like this:
user: /weather
bot: Enter location
user: Barcelona
bot: Show weather in Barcelona

persian command

i want use persian command in my telegram bot
How can I do this?

Command in chat group with other bot doesn't work

Hello! I've notice that in chat with other bots the command are send like:
/echo@bot1
/weather@bot2
and so on..
So this bot is able to recognise /echo but not /echo@mybot

I would like to contribute developing this feature

Dealing with undefined commands

Hi!

If the bot receives an undefined command something like that is thrown in the apache logs:

[Mon Aug 31 10:55:02.370494 2015] [:error] [pid 17414] [client 149.154.167.198:47253] PHP Fatal error:  Class 'Longman\\TelegramBot\\Commands\\GeloCommand' not found in /var/www/html/bot/vendor/longman/telegram-bot/src/Telegram.php

How can I deal with that? Which class do I need to tamper with to catch that error and, for example, reply some text to suggest the use of /help??

Thanks!

/command@BotName not working

First of all thank you for this incredible library ๐Ÿ‘
My problem is: In a channel with two other bots (ImageBot and PollBot) when I try to use the command /help@MyBot it does not work, using only /help the command is executed correctly but triggers the same command over the other two bots. Is there anything else that needs to be configured so the command /help@MyBot can be used? I'm using the latest release.

Looking for some help

I just started looking into telegram bots and I've found this really nice repo with a lot of interesting stuff. I tried to follow the instructions to install it, but I fail somewhere (I've never installed a php application actually, so I was just shooting in the dark), so I'm asking if someone could help me to get the bot working please.

I'm struck at the point where I pull the whole repo in my computer and I do "php composer.phar install". Now I'm stuck.
How can I start the php server?

what about Receiving messages?

Hello.

I want my bot to receive some messages and store them on local database (mysql).
what is your suggestion?
please help me.

Regards.

Calc command doesn't work

Due to an error in the Hoa packages the entire bots hangs on the /calc example. The other examples are clear enough to understand the API and how to implement your own commands. Took me a few hours to debug the whole thing to finally come to the conclusion its not this package that causes the problems.

Problem with getting /echo working โ€“ please provide minimum working example

I try to set up hook.php but with little success so far.

  1. The minimum example:
try {
   $telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME);
   $telegram->enableMySQL($credentials);
   // later commands are handled here
   $telegram->handle();
}

works so far.

  1. However, if I add commands (is it correct to do this before the method $telegram->handle()?), MySQL logging stops working and the web server error_log logs 500 Internal Server Error (see #39).
  2. Exceptions are logged but not when (1) happened. I can have an exception logged by calling php hook.php from command line, then the exception says exception 'Longman\TelegramBot\Exception\TelegramException' with message 'Input is empty!' so exception logging should work.
  3. My basic question is: What is the exact way to add any functionality to above minimum example such as echo or whoami?

Is this correct?

$echo = new Longman\TelegramBot\Commands\EchoCommand;    
$echo->execute();

Or this way?

$telegram->executeCommand('echo', $update);

Or both? I cannot figure this out without diving into the classes but it should be clear in the documentation already.

The point is, I believe that Telegram API stops sending me requests if I produce to many server errors. Because after trying this out, even the basic example above stops working (MySQL no longer logs anything) and I have to wait a day or so and suddenly it works again.

Please provide a minimum working example in README.md with which users can instantly get at least the /echo Telegram bot command working.

I don't know if this would be a minimum working example, but please add something like the following to README.md to make it clear and instantly get a working bot:

try {
   $telegram = new Longman\TelegramBot\Telegram($API_KEY, $BOT_NAME);
   $telegram->enableMySQL($credentials);
   $echo = new Longman\TelegramBot\Commands\EchoCommand; // or whatever is correct to activate "/echo"
   $echo->execute();
   $telegram->handle();
}

If this would be easy to get started with, I think it will be a great success! Thank you.

Error when sending message to channel

It is now possible to send messages to channels using @channelname as chat_id in the sendMessage method.
However the curl_exec in executeCurl of Request.php breaks since a @ is interpreted as prefixing a file to upload.

Suggested fix is to add:

        if (!empty($data['chat_id']) && substr($data['chat_id'], 0, 1) === '@') {
            curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
        }

before curl_setopt_array($ch, $curlConfig) in function executeCurl

/stats command

Hi guys,
it would be great to develop the /stats admin command!
This command should use as input the messages collected in the DB and then show the number of request per day to the bot.
Is someone interested? Some volunters in the develop of this feature? ;)

getUpdateCLI.php Fail fetch updates

Hi, I tried php-telegram-bot in my local server using Fail fetch getUpdateCLI.php

I just copied getUpdateCLI.php from D:\xampp\htdocs\tgbot\vendor\longman\telegram-bot
to D:\xampp\htdocs\tgbot and edit botkey and boname, I'm also edit database config and import structure.sql.

when I tried to run getUpdateCLI.php, it said 2015-09-12 16:19:13 - Fail fetch updates

but, when I'm using https://api.telegram.org/bot-key/getUpdates
It can give me the updates.

Can u tell me, what's wrong? Am I miss someting?

Extend mysql access to custom commands

Good morning!

I'm testing the code, trying to implement a command that uses mysql as storage.

I've seen that on a recent update of the source now the pdo variable it's inside a new DB class... but I cannot figure out how to use the class to make custom queries to the database...

Can anyone help me please?

Thanks in advance, Sergio

Create custom command and keyboard

Hi;
Thanks for this cool script. ๐Ÿ‘

I wish that I could find more detailed documentation for your script.

I started to use your script recently and everything seems nice BUT
need to know :
How can I write my own commands?
I did create a class named testCommand in commands folder but this way didn't work.

Would you please help me to create my own command and custom keyboard?

_Thanks in Advance_

nginx php-fpm running error

Hello, after install and setup properly I got this error:

FastCGI sent in stderr: "PHP message: PHP Fatal error: Call to a member function isEnabled() on a non-object in /var/www/vendor/longman/telegram-bot/src/Commands/HelpCommand.php

could you please help me this that?

Is it possible to send a message to a user given just the phone number or user name?

Hello,

I was playing around this (great) library and I noticed that most of the examples use the chat_id as the key for sending messages.

I was wondering if there was a way to send a message to a specific user given the phone number or the user name (knowing both would be awesome). Also, is there a way to initiate a secure chat with such a user?

Cheers and keep up the amazing job!

/Nesh

send message to all our bot members

i wanna to send 10 or more message in one action to all my bot members

telegram permit us to this action. i mean, can i send a message for all my bot members with out any theirs request?

CurlFile class not found

Good afternoon. If you try to send a local file, I come across an error PHP Fatal error: Class 'CURLFile' not found in ... /src/Request.php on line 224
I have no idea how to fix it. Thank you.

Input is empty! - hook.php

I first used getUpdatesCLI.php and works properly every time i will refresh the page manually (Each refresh of the page the bot reply to me). It's ok!

Now I wanted to try to set webhook. After setting the webhook (set.php - Webhook was set!), i try to write in the chat, but the bot does not reply to me .. Then I go to to hook.php page and i get this error:
Input is empty!

What wrong?

The same configuration for getUpdatesCLI.php works

This is my hook.php:

    //Composer Loader
    $loader = require __DIR__.'/vendor/autoload.php';
    
    $API_KEY = 'XXXXXXXXXXXXX:XXXXXXXXXXXXX';
    $BOT_NAME = 'XXXXXXXXXXXXX';
    //$COMMANDS_FOLDER = __DIR__.'/src/Commands/';
    $credentials = array('host'=>'localhost', 'user'=>'XXXXXXXXXXXXX', 'password'=>'XXXXXXXXXXXXX', 'database'=>'XXXXXXXXXXXXX');
    
    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();
    }

Errors in logs

There are some errors in logs when I'm trying to use any command (excluding /echo):

[Fri Sep 04 15:29:57 2015] [error] [client 149.154.167.198] PHP Warning:  Missing argument 2 for Longman\\TelegramBot\\Entities\\Message::__construct(), called in /home/vavoluk/bot/vendor/longman/telegram-bot/src/Entities/Message.php on line 107 and defined in /home/vavoluk/bot/vendor/longman/telegram-bot/src/Entities/Message.php on line 64
[Fri Sep 04 15:29:57 2015] [error] [client 149.154.167.198] PHP Notice:  Undefined variable: bot_name in /home/vavoluk/bot/vendor/longman/telegram-bot/src/Entities/Message.php on line 66

How to fix this?

/whoami command fails if you don't have a profile picture

The /whoami build-in command fails if you don't have a profile picture.
It would show "xxxxxbot is typing..."
And that disappears.

The following Stack-trace is then thrown:

2015-12-10 21:39:57 exception 'Longman\TelegramBot\Exception\TelegramException' with message 'total_count is empty!' in /var/www/vhosts/test/httpdocs/hooks/vendor/longman/telegram-bot/src/Entities/UserProfilePhotos.php:26
Stack trace:
#0 /var/www/vhosts/test/httpdocs/hooks/vendor/longman/telegram-bot/src/Entities/ServerResponse.php(38): Longman\TelegramBot\Entities\UserProfilePhotos->__construct(Array)
#1 /var/www/vhosts/test/httpdocs/hooks/vendor/longman/telegram-bot/src/Request.php(249): Longman\TelegramBot\Entities\ServerResponse->__construct(Array, 'xxxxxxxbot')
#2 /var/www/vhosts/test/httpdocs/hooks/vendor/longman/telegram-bot/src/Request.php(392): Longman\TelegramBot\Request::send('getUserProfileP...', Array)
#3 /var/www/vhosts/test/httpdocs/hooks/vendor/longman/telegram-bot/src/Commands/WhoamiCommand.php(55): Longman\TelegramBot\Request::getUserProfilePhotos(Array)
#4 /var/www/vhosts/test/httpdocs/hooks/vendor/longman/telegram-bot/src/Command.php(53): Longman\TelegramBot\Commands\WhoamiCommand->execute()
#5 /var/www/vhosts/test/httpdocs/hooks/vendor/longman/telegram-bot/src/Telegram.php(477): Longman\TelegramBot\Command->preExecute()
#6 /var/www/vhosts/test/httpdocs/hooks/vendor/longman/telegram-bot/src/Telegram.php(432): Longman\TelegramBot\Telegram->executeCommand('whoami', Object(Longman\TelegramBot\Entities\Update))
#7 /var/www/vhosts/test/httpdocs/hooks/vendor/longman/telegram-bot/src/Telegram.php(390): Longman\TelegramBot\Telegram->processUpdate(Object(Longman\TelegramBot\Entities\Update))
#8 /var/www/vhosts/test/httpdocs/hooks/index.php(34): Longman\TelegramBot\Telegram->handle()
#9 {main}

Reply Markup

I'm working on class that build the json query to fill the reply_markup parameters in send message, this will let you create keyboard faster.

Types implementation

In the latest release I've attached some new class in order to complete the avaiable type.
They are not linked to message entities and not tested yet.
They also have to been upgraded to the last changelog in the telegram api https://core.telegram.org/bots/api.

set.php gives type error for ServerResponse::__construct()

When I set up the bot as described in README.md and call set.php, I get:

PHP Catchable fatal error:  Argument 1 passed to Longman\\TelegramBot\\Entities\\ServerResponse::__construct() must be of the type array, null given, called in /myproject/vendor/longman/telegram-bot/src/Request.php on line 152 and defined in /myproject/vendor/longman/telegram-bot/src/Entities/ServerResponse.php on line 26

Can not add other command

Hello
First of all thanks for implementing the robot code
My problem is on adding new commands to my robot, for example I copied echo command and changed command name to test and rename the file to TestCommand.php but when I enter /test command in my rovot in telegram it just says Command: test not found :(
would you please help about this issue ?

Thanks alot.

Code style, content

Dear developers,

I'm glad a fairly popular php client such as this one exists for the telegram bot API. However, as I am walking through the source code, trying to figure out how it works internally, I get confused.

At this point I am thinking whether I should start contributing on this project or not. I would like to, but such things above make it a bit of a challenge. I would recommend to clean up the code a bit to make it easier for external developers to start contributing. This is just my opinion, but I think it would help the project.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.