PHP (PHP: Hypertext Preprocessor) is a widely used, high-level, dynamic, object-oriented and interpreted scripting language primarily designed for server-side web development.
1
4answers
Reasons for MySQL authentication error: “Access denied for user 'xxx'@'yyy'”?
Hi, I could not find any good answer using Google. I've made a Telegram bot linked to a webhook itself linked with a MySQL db. I cannot bring to Telegram the.
What possible reasons could exist for MySQL giving the error “Access denied for user 'xxx'@'yyy'” when trying to access a database using PHP-mysqli and working fine when using the command-line mysql ...
Raphael Schweikert15.3k55 gold badges4949 silver badges6464 bronze badges
1
3answers
How best to resize images off-server
I have a site that users upload images to. Those images are resized to various dimensions. I currently do that on my server, but was thinking of processing that on AWS or something similar. Is that a ...
ed2094,7951616 gold badges5858 silver badges8181 bronze badges
1
7answers
How do I display mysql data in row span using PHP?
I have data from MySQL showing all organisations a customer got, with all details of employess in each organisation. I want to list each organisation name only once i.e. in a single cell ( row span) ...
hash56022 gold badges99 silver badges1717 bronze badges
1
3answers
Custom php template engine: Am i finally on the right track?
Since I keep showing up late for answering questions tagged php where i actually know the answer i figured i'd try asking a question myself.I've been working on so many complete rewrites of a custom ...
Kris29.4k88 gold badges6464 silver badges9292 bronze badges
1
4answers
Using PHP to write to OS X's log database?
Do any apps/packages exist that will support writing to OS X's log database from external sources. I'm not too familiar with the specifics of the database, beyond the fact that you can view its ...
Wilco16.1k4343 gold badges121121 silver badges157157 bronze badges
1
3answers
PHP - Custom error handling. Redirected 404 is being hijacked by AVG Anti-Virus. How to stop?
I have a website which uses the custom 404 error handling in PHP/Apache to display specific pages.e.g. http://metachat.org/recent I've a feeling this is a bad way of doing this, but it's code I ...
seanyboy4,38177 gold badges3838 silver badges5656 bronze badges
1
3answers
What are some use cases of Named Routes in Laravel?
After reading the documentation, I still only have a vague idea of what Named Routes are in Laravel.Could you help me understand?Route::get('user/profile', function () { //})->name('...
1
2answers
What are arrow functions in php and how to use them?
Arrow functions are new in PHP 7.4. How do I use them? Is there a specific way to use them or they are just like javascript? Will they make my PHP code shorter and readable?
1
3answers
Dynamically add dimension to PHP array
I thought about it a lot before posting this question. The question is more conceptual than anything else.Starting from a classic array, I want to dynamically transform it into multidinamic with ...
Oscar Zarrus46811 gold badge66 silver badges1616 bronze badges
1
2answers
How to initialize foreach functions or variables to 0
Using the most current versions of PHP 7 I present the following error message: Warning: A non-numeric value encountered It seems that in PHP 7.1, a Warning will be emitted if a non-numeric value ...
1
5answers
Build string on one line PHP
I want to build a combination of numbers and letters separated by - (minus sign). i.e 1-R-3. The first number are in an array called $Points ,the letters are stored in a array called $Color and the ...
1
2answers
Eloquent query with two models
I need your help, please!I have two models customer and membership. Customer hasMany Memberships.I need to extract all customers with a membership active. I did this but it extracts only memberships,...
1
2answers
Get part of URL in PHP is not completely working
I've this code here:$url = 'https://www.my-page.de/account/show/4913';echo substr( $url, strrpos( $url, '/' ) + 1 ); This returns me the needed id:4913 Now the problem begins. In some cases ...
1
3answers
SQL Count returns 0
I have been trying to count the number of paths present in my table. I am trying the following query$db_con->query('SELECT COUNT(path) FROM mytable WHERE username='Rbiaali' AND path='C:MAMP...
1
3answers
Iteration of loop should produce 16 names not 4
I have the loop below which iterates 4 times. Within this look is another which defines my group names. I would like to produce the outputGroup 01Group 02Group 03....Group 15Group 16 instead ...
user318973436811 gold badge33 silver badges2222 bronze badges
prev 1…1580315804158051580615807…86158 next
A Telegram Bot based on the official Telegram Bot API
A Telegram Bot based on the official Telegram Bot API
Table of Contents
- Instructions
- Webhook installation
- getUpdates installation
- Support
- Utils
- MySQL storage (Recommended)
- Commands
- Admin Commands
Introduction
This is a pure PHP Telegram Bot, fully extensible via plugins.Telegram recently announced official support for a BotAPI allowing integrators ofall sorts to bring automated interactions to the mobile platform. ThisBot aims to provide a platform where one can simply write a pluginand 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 API (25 May 2016).
- 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 onGithub. Pull requests are welcome.
Instructions
Create your first bot
- Message @botfather https://telegram.me/botfather with the followingtext:
/newbot
If you don't know how to message by username, click the searchfield on your Telegram app and type@botfather
, where you should be ableto initiate a conversation. Be careful not to send it to the wrongcontact, because some users has similar usernames tobotfather
. - @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:
- Note down the 'token' mentioned above.
- Type
/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 5above, but start it with@
) - @botfather replies with
- Type (or select)
Disable
to let your bot receive all messages sent to agroup. This step is up to you actually. - @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
and run
composer update
or
run this command in your command line:
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 |
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:
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:
Self Signed Certificate
To upload the certificate, add the certificate path as a parameter in set.php:
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:
Next, give the file permission to execute:
Lastly, run it!
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:Support
Types
All types are implemented according to Telegram API (20 January 2016).
Inline Query
Full support for inline query according to Telegram API (20 January 2016).
Methods
All methods are implemented according to Telegram API (20 January 2016).
Send Message
Messages longer than 4096 characters are split up into multiple messages.
Send Photo
To send a local photo, add it properly to the
$data
parameter using the file path:If you know the
file_id
of a previously uploaded file, just use it directly in the data array:To send a remote photo, use the direct URL instead:
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
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):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 after object creation and BEFORE handle()
method:You can set a custom prefix to all the tables while you are enabling MySQL:
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:
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 execute commands that get triggered by chat events.
Here's the list:
- StartCommand.php (A new user starts to use the bot.)
- NewChatMembersCommand.php (A new member(s) was added to the group, information about them.)
- LeftChatMemberCommand.php (A member was removed from the group, information about them.)
- NewChatTitleCommand.php (A chat title was changed to this value.)
- NewChatPhotoCommand.php (A chat photo was changed to this value.)
- DeleteChatPhotoCommand.php (Service message: the chat photo was deleted.)
- GroupChatCreatedCommand.php (Service message: the group has been created.)
- SupergroupChatCreatedCommand.php (Service message: the supergroup has been created.)
- ChannelChatCreatedCommand.php (Service message: the channel has been created.)
- MigrateToChatIdCommand.php (The group has been migrated to a supergroup with the specified identifier.)
- MigrateFromChatIdCommand.php (The supergroup has been migrated from a group with the specified identifier.)
- PinnedMessageCommand.php (Specified message was pinned.)
- GenericmessageCommand.php (Handle any type of message.)
- GenericCommand.php (Handle commands that don't exist or to use commands as a variable.)
- Favourite colour? /black, /red
- Favourite number? /1, /134
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.
Commands Configuration
With this method you can set some command specific parameters, for example:
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:
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:
- If you want to manage more channels:
- Enjoy!
Upload and Download directory path
To use the Upload and Download functionality, you need to set the paths with:
Documentation
Take a look at the repo Wiki for further information and tutorials!Feel free to improve!
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!
- Inline Games (@inlinegamesbot)
- Super-Dice-Roll (@superdiceroll_bot)
Troubleshooting
If you like living on the edge, please report any bugs you find on thePHP Telegram Bot issues page.
Contributing
See CONTRIBUTING for more information.
Security
See SECURITY 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 ?
- PayPal.me/noplanman (account of @noplanman)
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