php-telegram-bot / example-bot Goto Github PK
View Code? Open in Web Editor NEW[WIP] An A-Z example of a PHP Telegram Bot.
License: MIT License
[WIP] An A-Z example of a PHP Telegram Bot.
License: MIT License
How to start the Bot?
I don't get any result by help command.
i created database using structure.sql from bellow link
988a9fc
but when i send /survey command i got bellow error
[17-Feb-2018 19:44:39 Asia/Calcutta] PHP Warning: PDOStatement::execute(): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'media_group_id' in 'field list' in vendor/longman/telegram-bot/src/DB.php on line 905
how to create custom database read and insert method like ConversationDB.php inside Commands folder
by using php-telegram-bot database handle method like
class ConversationDB extends DB
Hi there,
i'm trying to user ure php telegram bot and i got this error code in my apache log file:
[Thu Feb 08 13:39:39.778757 2018] [:error] [pid 31072] [client 149.154.167.229:42151] PHP Parse error: syntax error, unexpected '?' in /vendor/php-telegram-bot/telegram-bot-manager/src/BotManager.php on line 65
I am using this PHP 7.0.27-0+deb9u1
This is the function what my apache/php is curious about (marked it with double **):
public function __construct(array $params)
{
// Initialise logging before anything else, to allow errors to be logged.
**$this->initLogging($params['logging'] ?? []);**
$this->params = new Params($params);
$this->action = new Action($this->params->getScriptParam('a'));
// Set up a new Telegram instance.
$this->telegram = new Telegram(
$this->params->getBotParam('api_key'),
$this->params->getBotParam('bot_username')
);
}
What can i do to avoid this error?
Thanks for your help in advance!
It is more question than issue.
You have named action 'genericmessage' in Group/GenericmessageCommand.php and in Message/GenericmessageCommand.php.
When execute() apply only one method will action.
Is it something i didn't understand or it's normal behavior?
i am working on expense manager bot , i already have laravel website for this , i want to control my databse with bot commands, for example to add record or update etc,
is this bot suppport the functionality to do so ,
if so which function i have to use.??
Hello 😄
For some reason, I'd like my bot to send a peanut Gif to every message in a conversation containing the word "peanut".
However, I couldn't find any way to do this as I am only able to create commands for message starting with a slash (e.g. /start, /help, ...).
Is there any way to trigger an action to arbitrary messages as well?
Thank you
Hi,
I am configuring the bot to try to build my bot, but I cannot make the upload works... I have configured database, upload paths, etc, but after the upload the bot does not reply. When i send /upload command it replies with "Please upload the file now", after the upload I cannot get any response.
I'm using PHP7.4.
In the apache logs I can see that apache responds with a 200 response code and I have no PHP errors :-(
Hello, please help. My Start command stopped working a month ago. In the beginning of April I've upgraded OS server successfully and I've updated your php-telegram-bot (source code and DB). Everything looks to be working fine, but commands. I've checked everything but I can't find the error
Here is my start command:
<?php
namespace Longman\TelegramBot\Commands\SystemCommands;
use Longman\TelegramBot\Request;
use Longman\TelegramBot\DB;
use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Exception\TelegramException;
use Longman\TelegramBot\Commands\SystemCommand;
/**
* Переопределение системной команды /start
*/
class StartCommand extends SystemCommand {
protected $name = 'start';
protected $description = 'Подключение к боту';
protected $usage = '/start';
protected $version = '1.0.0';
protected $private_only = true;
public function execute(): ServerResponse {
try {
$message = $this->getMessage();
$chatid = $message->getChat()->getId();
$text = "";
return Request::sendMessage([
'chat_id'=>$chatid,
'text'=>$text
]);
} catch (TelegramException $e) {
\Yii::error(__METHOD__.$e->getTraceAsString());
}
return Request::emptyResponse();
}
}
My hook:
public function actionHook() {
// Load composer
require __DIR__.'/../vendor/autoload.php';
try {
$BOT_NAME = Yii::$app->params["telebot"];
// Create Telegram API object
$telegram = new Telegram(Yii::$app->params["telekey"], $BOT_NAME);
$commands_paths = [
Yii::getAlias("@app")."/bot"
];
$telegram->addCommandsPaths($commands_paths);
$mysql_credentials = require('../config/dbot.php');
$telegram->enableMySQL($mysql_credentials);
//set bot admin
$USER_ID = ---------; //получить у @myidbot
$telegram->enableAdmin($USER_ID);
TelegramLog::initialize(
new Logger($BOT_NAME, [
(new StreamHandler(Yii::getAlias("@app").'/botlog/debug.log', Logger::DEBUG))->setFormatter(new LineFormatter(null, null, true)),
(new StreamHandler(Yii::getAlias("@app").'/botlog/error.log', Logger::ERROR))->setFormatter(new LineFormatter(null, null, true)),
]),
new Logger($BOT_NAME."_updates", [
(new StreamHandler(Yii::getAlias("@app").'/botlog/update.log', Logger::INFO))->setFormatter(new LineFormatter(null, null, true)),
]));
TelegramLog::debug(print_r($telegram->getCommandsPaths()));
$telegram->handle();
} catch (TelegramException $e) {
// Silence is golden!
// log telegram errors
//echo $e->getMessage();
Yii::error(__METHOD__.$e->getMessage());
}
}
Before handle I set commands path and check it - via this line:
TelegramLog::debug(print_r($telegram->getCommandsPaths()));
But in the debug.log I see a message:
[2022-05-11T09:44:26.745532+00:00] zvezdo_bot.DEBUG: 1 [] []
It means that commands path haven't set. But why? What's wrong and how to fix it?
How can I send more than one message like video and text message simultaneously?
This 49 line in execute() method in class GenericCommand sometimes get null on edited and liked messages in supergroup chats
$message = $this->getMessage();
And then next line generating error message because is no any methods in null.
$user_id = $message->getFrom()->getId();
Is this error of this example implimentation of core and we must check is there any mesage. Or Core bot must never exectute() method on edited or liked messages with null message?
I don't know how to use callbackquerycommand
Hello,
first of all, thank you for the good example as a base for devs.
I'm trying to use newchatmembers and leftchatmember commands. I assigned my bot as admin for a group, but no messsages on chat after joinin or leaving the group.
Do the functions really work?
Hi
i have error in hook.php
Longman\TelegramBot\Exception\TelegramException: Duplicate update received! in /var/www/example.me/public_html/vendor/longman/telegram-bot/src/DB.php:486
I'm used webhook method.
please help me
When I tried "NewchatmembersCommand.php", I found my bot sent welcome message whether new member is a bot or not.
If changes the code below, it works as expect.
from (line 51)
if (!$message->botAddedInChat()) {
to
if (!$member->getIsBot()) {
Please check. Any idea or advice would be highly appreciate.
Thanks in advance.
2018/09/20 11:52:12 [error] 7896#7896: *1558 FastCGI sent in stderr: "PHP message: PHP Fatal error: Uncaught Error: Call to undefined method Longman\TelegramBot\Telegram::deleteWebhook() in /home/vhosts/telegram/htdocs/unset.php:16
Tested the Tutorial and found this in my error-logs. Used here: Tutorial
Is it possible to start a conservation by pressing a InlineKeyboardButton (handle new Conversation() in CallbackqueryCommand.php)?
Hi, and thanks for the fantastic bot code. I need to send a massage on a channel with an inline button that contains a url like: tg://resolve?Domain=mybot&start=onecommand
I would need to read the "onecommand" as i have to process it depending on its content. How can i do that?
What should i change to make the bot read "onecommand" as a command even if it doesn't start with "/"?
Thanks in advance
PHP Version 7.1.8-2+ubuntu14.04.1+deb.sury.org+4
guzzlehttp/guzzle 6.3.0
guzzlehttp/promises v1.3.1
guzzlehttp/psr7 1.4.2 PSR-7
longman/ip-tools 1.2.1
longman/telegram-bot 0.45.0
monolog/monolog 1.23.0 S
php-telegram-bot/telegram-bot-manager 1.2.1
psr/http-message 1.0.1
psr/log 1.0.2
After setting bot username (with and without '@'), api key, and all the required information for webhook running it in browser http://mywebsite.com/botexamples/manager.php?s=mysecretkey&a=set
result in fatal error :
Fatal error: Uncaught TelegramBot\TelegramBotManager\Exception\InvalidAccessException: Invalid access in /var/www/html/botexamples/vendor/php-telegram-bot/telegram-bot-manager/src/BotManager.php:578 Stack trace: #0 /var/www/html/botexamples/vendor/php-telegram-bot/telegram-bot-manager/src/BotManager.php(130): TelegramBot\TelegramBotManager\BotManager->validateRequest() #1 /var/www/html/botexamples/manager.php(80): TelegramBot\TelegramBotManager\BotManager->run() #2 {main} thrown in /var/www/html/botexamples/vendor/php-telegram-bot/telegram-bot-manager/src/BotManager.php on line 578
Running it from command line using sudo php manager.php a=set
works, but example like /whoami doesn't work, and logging filename shows {$bot_username}_debug.log
instead of @mybotname_debug.log
However setting it manually using set.php runs just fine (all modules works, log filenames also shown correctly).
I have an inline keyboard with callback data. I want to change this keyboard on pressing one of its buttons after operating callback data.
How to do this?
$this->replyToChat
is not working in CallbackqueryCommand
.I was looking arround in the example commands directory and came accros the ShortenerCommand.php example at https://github.com/php-telegram-bot/example-bot/blob/90bfde028f71bda1aedd51bdc225984a68b5c276/Commands/ShortenerCommand.php.
I see the example uses Botan which has been discontinued according to the readme of the core project: https://github.com/php-telegram-bot/core/blob/78024d7bc55cebf3987247b465a1009b5186060a/CHANGELOG.md#removed-4
According to this pull request it would have been removed in the development branch: #31 Schouldn't the change be merged to the master branch too?
Maybe the example can replaced by another shortener service?
I'm sorry if this question may sound stupid to you. I'm not quite an expert with git and Github.
Hello,
I'm trying to test cron.php but I can't get it to work.
I see that, according to the line 35 comment 'Check hook.php
for configuration code to be added here.', I should insert extra hook.php configurations, but it still doesn't work.
I create the new Telegram instance, activate admins, activate Mysql, add the command path, but still nothing... Could you see a complete code example of cron.php?
Thanks!
Hi
I cloned the example bot. Each command is working properly except the survey.
It asks the name and i reply then nothing happens.
I create the bot just like the one in the example... I even set the webhook using manager.php but it doesnt work: if I try to give /start command it doesnt respond...
Good afternoon, I beg you to help me, is it possible to somehow attach the code to the button, I'm new to php and according to your guide I can't figure out how to make a button with this function. I would be very grateful for help
/**
* User "/newfollowup" command
*/
class NewfollowupCommand extends UserCommand
{
/**
* @var string
*/
protected $name = 'newfollowup';
/**
* @var string
*/
protected $description = 'Add a new followup to a ticket on GLPI via TelegramBot.';
/**
* @var string
*/
protected $usage = '/newfollowup <ticket_id>**<text>';
/**
* @var string
*/
protected $version = '1.0.0';
/**
* Command execute method
*
* @return \Longman\TelegramBot\Entities\ServerResponse
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public function execute()
{
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$user_chat = $message->getFrom()->getUsername();
$text = trim($message->getText(true));
$response = \PluginTelegrambotTicket::newFollowup($chat_id, $user_chat, $text);
if(!$response){
$response = 'Command usage: ' . $this->getUsage();
}
$data = [
'chat_id' => $chat_id,
'text' => $response,
];
return Request::sendMessage($data);
}
}
Please provide an option on init to set verify peer to false in guzzle.
Thanks.
Just recently update using "composer update" (and adding is_bot field in user table), now bot core is version 0.48 and telegram bot manager 1.2.2, when trying SurveyCommand after first question the bot didn't step to next question, is there incompability on conversation with the latest core?
I instantiate Redis in CallbackqueryCommand and want to write the data of CallbackqueryCommand into the list. But I don't know what went wrong
Hello,
in SurveyCommand.php stuck on "Type your surname:" not goes to next case Type your age
Where is problem?
Can you please update SurveyCommand.php
Thank you,
Guys sorry for my english, I'm Brazilian.
I'm having trouble making the callback return display the text normally with other Inlinekeyboards, but I can only display it in an alert format.
I have as basis only the InlinekeyboardCommand.php and CallbackqueryCommand.php files
I started from this example and today tried to make my own bot from this: the set.php was was a success and my files where like the example's one but I just added start command. When I try to start from telegram it doesnt respond... How can I check if the bot is working?
[SOLVED] I would like to access Codeigniter functions in one of the command's file. The composer packages reside in codeigniter's application/vendor directory, while this package reside in application/third_party directory.
$CI &= get_instance() does not work in command file.
Please help. TQ
Hi,
When i type /survey command, its asking for "Type your name:" question. After i write the the text nothing happens.
I tested on php 7.4.3.
Regards
PHP Fatal error: Class 'TelegramBot\TelegramBotManager\BotManager' not found in manager.php
anyone can help me?
Hi! I am using this template for my custom bot. I need a functionality like the /survey one, but since I am testing it only asks for the name (the first question), i write the name and then nothing happens. It is stuck there. I already h¡gave a look to the database and it is saving the conversation, but only the "state" var. I think it is not coming again from client to bot or viceversa when I write a answert. Could you help me please?
uncommenting and editing this in manager.php :
'commands' => [
'paths' => [
__DIR__ . '/Commands',
],
'configs' => [
'weather' => ['own_api_key' => 'my_own_api_key_here'],
],
],
then running the WeatherCommand result in "api-key not set response", did I do something wrong in settings?
I created a sample app same as this project and using bot-manager, after run handle action via browser (l parameter = 2000), the bot sends too many messages (Avg 30 in a minute) to the user (me).
when I run handle action, the bot starts to send messages defined in StartCommand class.
why did this happen?
why doesn't command class handle requested commands from users?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.