php laravel telegram bot
Php laravel telegram bot
Материал является вольным переводом статьи Build A Telegram Bot with Laravel and BotMan с сайта scotch.io.
В данном материале для создания Telegram-бота мы используем известную библиотеку BotMan (botman.io).
На рисунке вы можете видеть результат работы созданного по этому материалу Telegram-бота. Здесь по команде /random бот вернул ссылку на случайную картинку собаки: Естественно, кроме этой команды, бот будет понимать и другие.
В первую очередь установим Botman Studio. Если вы не знаете, что это, то знайте, Botman Studio – это стандартное Laravel-приложение с уже включенной в него библиотекой Botman. Так что если вы уже работали с Laravel ранее, то большинство действий из этого материала будет для вас знакомо.
А теперь продолжим, и создадим новый проект командой: После того, как все установится проверьте работает ли оно. Для этого наберите в браузере: [адрес вашего сайта]/botman/tinker (например, у меня было так: site1.com/botman/tinker), и в результате вы должны увидеть следующую страницу: Здесь нас интересует первая ссылка Tinker. Перейдя по ней, вы увидите поле ввода, через которое можно «пообщаться» с ботом. Например, если ввести слово «Hi», в ответ вы получите «Hello!».
Проверили, что все работает, можем продолжить.
Запрос ссылки на случайную картинку из всех пород собак (команда /random)
Для того, чтобы получить случайную картинку собаки из всех пород собак пользователю нужно будет ввести команду /random. Научим наш бот правильно реагировать на эту команду.
Откроем файл routes/botman.php и добавим туда новую строчку: Далее создадим новый контроллер с помощью команды: Его содержимое должно выглядеть следующим образом: Здесь мы используем класс DogService (app/services/DogService.php), который будет отвечать за запросы к Dog API и возвращении полученной ссылки на картинку с собакой. Содержимое этого файла должно быть следующим:
Запрос ссылки на случайную картинку с указанием породы (например, /b dachshund)
Запрос ссылки на случайную картинку с указанием породы и подпороды (например, /s hound:afghan)
Диалог с выбором желаемого действия (команда Start conversation)
Неизвестные команды
Установка Telegram-драйвера
Создание нового Telegram-бота
Открываем доступ извне к проекту с помощью ngrok
Чтобы не выкладывать свой тестовый проект на отдельный сервер в сети, воспользуемся утилитой ngrok. С помощью этой утилиты ваш проект на localhost станет доступен по отдельному адресу в Интернете. Если у вас еще не установлен ngrok, используйте официальную страницу (https://ngrok.com/download) для установки.
После того, как вы установите ngrok запустите Laravel-сервер: После чего перейдите в папку с ngrok и выполните команду: Теперь ваш проект будет доступен из сети по адресам, которые указаны в строчках Forwarding: Для работы Telegram-бота нужен https-адрес, поэтому используйте его.
Связываем наш проект с Telegram
Если вы все сделали правильно, то команда должна вернуть следующий результат: На этом все, результат работы в Telegram приведен на картинке:
Php laravel telegram bot
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.
Are You Using Telegram Bot SDK?
If you’re using this SDK to build your Telegram Bots or have a project that’s relevant to this SDK, We’d love to know and share it with the world.
Head over to Awesome Telegram Bots to share, discover, and learn more.
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.
Thanks to these companies for providing access to their products that have been very useful in developing this SDK. Please go check them out!
This project and its author is neither associated, nor affiliated with Telegram in anyway. See License section for more details.
This project is released under the BSD 3-Clause License.
About
🤖 Telegram Bot API PHP SDK. Lets you build Telegram Bots easily! Supports Laravel out of the box.
Php laravel telegram bot
Telegram Bot Package for Laravel 6.x, 7.x, and 8.x
This package helps easily integrate PHP Telegram Bot library in Laravel application.
Install this package through Composer.
Edit your project’s composer.json file to require php-telegram-bot/laravel
Create composer.json file:
And run composer update
Or run a command in your command line:
Copy the package config and migrations to your project with the publish command:
After run migration command
In the config you have to specify Telegram API KEY
You can inject PhpTelegramBot\Laravel\PhpTelegramBotContract in anywhere and use bot instance
More details about usage you can see on the PHP Telegram Bot docs: https://github.com/php-telegram-bot/core#instructions
If you like living on the edge, please report any bugs you find on the php-telegram-bot/laravel issues page.
Pull requests are welcome. See CONTRIBUTING.md for information.
Please see the LICENSE included in this repository for a full copy of the MIT license, which this project is licensed under.
Telegram Bot with Laravel Framework Tutorial
Chat bot’s popularity has been growing these past years because of it’s great functionality and reliability to handle some cases in business. And also, Bot has been supported by lots of instant messaging service provider such as Telegram, Line, Facebook, etc. On the other side, Laravel is one of the most popular framework to build web applications written in PHP.
In this article we will try to make a simple chat bot for Telegram messaging platform. This tutorial will cover some topics such as:
Getting Started
Here are some requirements before getting started:
The finished project example is available on GitHub.
Create a new Laravel Project
You may install the project in any directory in your machine as you like. For further information to create a Laravel project, check out instructions in the official docs.
Open your terminal and in your local directory simply run
Create a Telegram Bot
Great! Now we have our Laravel project ready to roll. Next, let’s create our Telegram Bot! If you want to learn more about Telegram bot, I prefer you to explore about it here.
First, open your Telegram app, and go find @BotFather. BotFather is a bot created by Telegram to manage all other bots (imagine BotFather is a GodFather of all bots).
Done! Congratulations on your new bot. You will find it at t.me/YOUR_BOT_USERNAME. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you’ve finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this.
Use this token to access the HTTP API:
In the message sent by BotFather, you will get your bot’s access token. This token will be use to identify your bot and work as your bot’s secret signature key. Make sure you keep this private because if someone else got your token, they could access and do commands on your bot’s behalf.
Okay! Now we have our Bot, our BOT_TOKEN and our Laravel project ready to go!
Integrating Telegram Bot to Laravel
In this tutorial, we will use telegram-bot-sdk. This SDK helps us to do any methods or operations easily from our Laravel project. This time, we will use dev-develop version (the stable version is quite out-dated; this article will be updated after the v3.0 became stable version).
Now, let’s connect everything we’ve done so far! Inside telegram.php you should see lots of config regarding to the bot. Let’s take a look at «bots» key. Here inside mybot key, change username value to your Telegram bot username and change token value to your access token given by BotFather.
Handling Telegram Updates
Now, we got our Bot access token linked with our project. Next, let’s handle Telegram Updates.
What is Telegram Update? According to official docs,
So by that, Updates are an Object containing every interaction made to our bots. For example when someone initiate a chat with our bot, an update will be made. Or when our bot added to a chat group/supergroup, an update will be made.
Alrighty! We got API route called /bot/getupdates to retrieve updates from Telegram server. And also, don’t forget to use Telegram class. By successfully getting Updates, we could choose how to act accordingly to every action user did with our bot including inviting to chat group, processing commands, or just simply replying to a chat.
This method of getting updates is using long polling to fetch updates. For advanced usage, you can set up webhook for better experience.
Sending Messages
Lastly, sending messages.
Let’s get through the details. As we can see, sendMessage receive few parameters such as :
Note: You could only send a message to user using this method if the specific user ever started a conversation with the bot. For group, supergroup or channel, the bot need to be set as Admin to be able to send messages.
Other Methods
Other methods as listed in Telegram API official documentation are available and fully supported by this SDK.
If you have any questions or help, feel free to hit me up at twitter.
Php laravel telegram bot
Laravel Telegram Bot
Require this package, with Composer:
Add the service provider to the providers array of your config/app.php :
Publish the config file:
To use a self-signed certificate, you should also specify the certificate path:
Define the default webhook route in your route file:
Set up the webhook url:
To ensure the bot is ready, send the /ping message:
You can change the default webhook route to your own:
Create a new Bot Command in the app/Http/BotCommands directory:
Edit the handle method of app/Http/BotCommands/NameCommand.php :
Use the Client’s send method to call any of the available methods.
Use the Client’s save method to save Telegram files.
Add the new command to the commands array of your config/telegram.php :
Send the /name Johnny message:
Add facades to the aliases array of your config/app.php :
Send a photo to your chat:
Save incoming files:
To extend the Client, add a new macro to the boot method of your app/Providers/AppServiceProvider.php :
Send an uploaded photo to your chat:
The Client uses Guzzle Http Client to interact with Telegram API, so you can handle Guzzle Exceptions:
Require this package, with Composer:
Add the service provider to the Register Service Providers section of your bootstrap/app.php :
Copy the vendor’s telegram.php config file to your config directory:
Define the default webhook route in your route file:
Laravel Telegram Bot is licensed under The MIT License (MIT).
About
Create your Telegram Bot in 5 minutes with Laravel