i'm making a Telegram bot using php language, i want to add a cooldown to a command, i already tried with sleep(), but the result still the same, it doesn't work, someone can help me?
At least this is possible? or i need to re code the bot in another language?
here the code:
<?php
namespace Longman\TelegramBot\Commands\UserCommands;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;
class DiscordCommand extends UserCommand{
protected $name = 'discord';
protected $description = 'Linka server discord';
protected $usage = '/discord';
protected $version = '1.0.0';
public function execute()
{
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
$message_id = $message->getMessageId();
$text = 'Ciaoo';
$data = [
'chat_id' => $chat_id,
'text' => $text];
$started_at = time();
if($current_time==$started_at)
return Request::sendMessage($data);
$cooldown = 60*60*1; //1 minutes
$current_time = time();
$timeLeft = $current_time - $started_at;
if($timeLeft >= $cooldown)
return Request::sendMessage($data);
I will comment your code, I see some possible errors here:
$started_at = time();
if($current_time==$started_at) // You're using $current_time, but is not set
return Request::sendMessage($data);
$cooldown = 60*60*1; //This is not 1 minutes, 60*60*1 is 1 hour
$current_time = time();
$timeLeft = $current_time - $started_at;
if($timeLeft >= $cooldown)
return Request::sendMessage($data);
Related
How can i sum times into array using Carbon?
<?php
namespace App\Models;
use Carbon\Carbon;
class Appointment extends BaseModel
{
public static function total_time()
{
$appointments = Appointment::get();
$sumtimes = [];
foreach($appointments as $a){
$dti = Carbon::parse($a->dateinitial);
$dtf = Carbon::parse($a->datefinal);
$time = $dti->diff($dtf)->format('%H:%I:%S');
$sumtimes[] = $time;
}
$sumtimes= sum($sumtimes);
return $sumtimes;
}
inside sum_times, there is a list of times that need to be summed like:
$sum_times[0] = "00:01:18"
$sum_times[1] = "00:03:11"
$sum_times[2] = "01:01:18"
$sum_times[3] = "00:01:28"
I need it to return "01:07:15"
<?php
public static function total_time(): string
{
$seconds = 0;
foreach(Appointment::get() as $appointment){
$dateinitial = Carbon::parse($appointment->dateinitial);
$datefinal = Carbon::parse($appointment->datefinal);
$seconds += $datefinal->diffInSeconds($dateinitial);
}
return gmdate('H:i:s', $seconds);
}
Also you must set for your fields (dateinitial, datefinal) cast datetime for automated parsing to Carbon type. Docs for date casts.
Each result of diff can be continuously added to a datum. At the end of the loop we get the sum as the difference from the base date to the date. Carbon is an extension of DateTime. I show the sample code with the base class so that it is reproducible for everyone.
$data = [
['from' => '2022-03-01 16:00', 'to' => '2022-03-02 12:00'], //20:00:00
['from' => '2022-03-02 12:30', 'to' => '2022-03-02 22:02'], //09:32:00
]; //total 29:32:00
$basis = '2000-01-01';
$dateBase = date_create('2000-01-01');
$date = clone $dateBase;
foreach($data as $dates){
$dateFrom = date_create($dates['from']);
$dateTo = date_create($dates['to']);
$diff = $dateFrom->diff($dateTo);
$date->add($diff);
}
$totalDiff = $dateBase->diff($date);
$hours = $totalDiff->d *24 + $totalDiff->h; //days * 24 + hours
echo 'Sum: '.$hours.$totalDiff->format(':%I:%S');
//Sum: 29:32:00
Try self on 3v4l.org
I am trying to seed DB table in Laravel. There is a time column which I need to have unique or at least not same for every record in that table.
Currently, I am using this; which does give the result to somewhat I am looking for but it's not complete.
mt_rand(0,23).":".str_pad(mt_rand(0,59), 2, "0", STR_PAD_LEFT)
My issue is that the single digit time don't have a 0 in front and sec are missing. Normally, what I was planning is the below code but it game me same results over and over:
date('H:i:s', strtotime( ((srand(0,1) ? '-'.mt_rand(1,24) : '+'.mt_rand(1,24).' '.rand(0,1) ? 'minute' : 'hour')), strtotime(date('H:i:s')))),
Result is "05:30:00" always so I am confused as to what to do next.
You said you are using Laravel, so why not just use the built-in Faker library for DateTime generation?
$faker = Faker::create();
$faker->time('H:i')
From the documentation, here is the available DateTime related outputs:
unixTime($max = 'now') // 58781813
dateTime($max = 'now', $timezone = null) // DateTime('2008-04-25 08:37:17', 'UTC')
dateTimeAD($max = 'now', $timezone = null) // DateTime('1800-04-29 20:38:49', 'Europe/Paris')
iso8601($max = 'now') // '1978-12-09T10:10:29+0000'
date($format = 'Y-m-d', $max = 'now') // '1979-06-09'
time($format = 'H:i:s', $max = 'now') // '20:49:42'
dateTimeBetween($startDate = '-30 years', $endDate = 'now', $timezone = null) // DateTime('2003-03-15 02:00:49', 'Africa/Lagos')
dateTimeInInterval($startDate = '-30 years', $interval = '+ 5 days', $timezone = null) // DateTime('2003-03-15 02:00:49', 'Antartica/Vostok')
dateTimeThisCentury($max = 'now', $timezone = null) // DateTime('1915-05-30 19:28:21', 'UTC')
dateTimeThisDecade($max = 'now', $timezone = null) // DateTime('2007-05-29 22:30:48', 'Europe/Paris')
dateTimeThisYear($max = 'now', $timezone = null) // DateTime('2011-02-27 20:52:14', 'Africa/Lagos')
dateTimeThisMonth($max = 'now', $timezone = null) // DateTime('2011-10-23 13:46:23', 'Antarctica/Vostok')
amPm($max = 'now') // 'pm'
dayOfMonth($max = 'now') // '04'
dayOfWeek($max = 'now') // 'Friday'
month($max = 'now') // '06'
monthName($max = 'now') // 'January'
year($max = 'now') // '1993'
century // 'VI'
timezone // 'Europe/Paris'
While #leek's answer is probably better considering you're using Laravel, a more generic way of getting what you need is the following:
$dt = new DateTime();
var_dump($dt->format('H:i:s'));
However, this will not be unique enough if you're running the script more than once a second. And of course, it will (potentially) not be unique if you run it over more than 1 day.
I beg to excuse me for my poor english.
So, I have Laravel 5 ORM, and i need to make request that should add date to some rows, like MySQL DATE_ADD. Input is single date interval and array of id's, output is rows of database, that was changed by adding date interval. Ideally, it should be one ORM request. I know that it is possible to use "bad" way and get all rows, update it in a code, and insert to database, but imho it's not good.
I hope answer will be link to some help site or some code if it's does not complicate you. Thanks for your attention!
public function update($id)
{
$user_id = Auth::user()->id;
$rep_task = RepTask::find($id);
$cl_task = \Request::has('json') ? json_decode(\Request::input('json'),true) : \Request::all();
$ids = [];
$task_id = $rep_task->task_id;
$rep_tasks = RepTask::where('task_id', '=', $task_id)
->select('id')
->get();
$new_date = date_create_from_format(self::DATE_FULLCALENDAR_FORMAT, $cl_task['new_date']);
$selected_task_date = date_create_from_format(self::DATE_MYSQL_FORMAT, $rep_task->start_date);
$diff = date_diff($selected_task_date, $new_date);
if(\Request::has('json'))
{
$ids = [1,2,3]; //this for easy understanding
DB::table('rep_task')
->whereIn('id', $ids)
->update(['start_date' => DB::raw('DATE_ADD(start_date, INTERVAL ' . $diff->d . ' DAY)')]);
$out_json = ['updated' => $ids];
return json_encode($out_json, JSON_UNESCAPED_UNICODE);
}
else
{
$start_date = 0;
$end_date = 0;
if (!isset($cl_task['name']) || !isset($cl_task['text']))
return "{'error':'columns are not defined'}";
if (isset($cl_task['start_date']) && isset($cl_task['end_date']))
{
$dt = date_create_from_format(self::DATE_FULLCALENDAR_FORMAT, $cl_task['start_date']);
$start_date = $dt->format(self::DATE_MYSQL_FORMAT);
$dt = date_create_from_format(self::DATE_FULLCALENDAR_FORMAT,$cl_task['end_date']);
$end_date = $dt->format(self::DATE_MYSQL_FORMAT);
}
$rep_task->name = $cl_task['name'];
$rep_task->text = $cl_task['text'];
$rep_task->start_date = $start_date;
$rep_task->end_date = $end_date;
$rep_task->users_id = $user_id;
$rep_task->save();
}
$user_id = Auth::user()->id;
$tasks = Task::getAllTasksByUserFullcalendar($user_id);
return view(
'task.index',
[
'tasks' => $tasks
]
);
}
i am using jquery countdown timer but the problem is that timer start from value set every time on page refresh . I want to get time on first time and Save in PHP Session and subtract second time from frist time and update session etc. In Simple Word i want to create php countdown timer run only 50 using php
here is my controller code
public function actionViewtimer($id) {
$session = Yii::app()->session;
$this->layout = 'countdownlayout';
if (empty($session['countdowntime'])) {
$orderTime = microtime(true); #when user first time enter timer start from 50 mins
$session->add('countdowntime', array($orderTime)); //replace this line
} else {
$time_end = microtime(true);
$orderTime = $time_end - $time_start;
unset($session['countdowntime']);//unset old session
$session->add('countdowntime', array($orderTime)); //when user enter second
}
$getMinutes = $getMinutes_from_orderTime ; #please tell me how we extact minutes and pass them to view
$session->add('timersession', array($rand));
$this->render('viewtimerpage', array(
'getMinutes' => $getMinutes
));
}
here is my jquery code
<script>
$(function() {
$('#xlarge').countdowntimer({
minutes: 50<?php echo $getMinutes; ?>,
size: "lg",
timeUp: timeisUp
});
});
function timeisUp() {
alert('Time Complete');
return false;
}
</script>
Sorry, I've not used Yii so this example will be in plain PHP.
session_start();
if(!isset($_POST['counter']) || !is_array($_POST['counter')) {
$duration = 50;
$counter = array(
'start_time' => new DateTime()->format('Y-m-d H:i:s'),
'end_time' => new DateTime()->modify("+{$duration} minute")->format('Y-m-d H:i:s'),
'duration' => $duration
);
$_SESSION['counter'] = $counter;
}
$counter = $_POST['counter'];
$now = new DateTime();
$end_time = new DateTime($counter['end_time']);
$time_left = $end_time->getTimestamp() - $now->getTimestamp();
echo "{$time_left} seconds left";
This should be simple enough to convert, and you can easily convert seconds to minutes.
Don't destroy the session variable. Just set it the first time when its empty and then plug that value always into your countdown timer.
Inside you action
$session = Yii::app()->session;
$this->layout = 'countdownlayout';
if (empty($session['countdowntime'])) {
$date = new DateTime();
$date->modify('+50 minutes'); // Add 50 minutes to current time
$session['countdowntime'] = $date->format('Y/m/d H:i:s'); // Store date in session
}
$this->render('viewtimerpage', array(
'countdowntime' => $session['countdowntime'];
));
jQuery Code
$(function() {
$('#xlarge').countdowntimer({
dateAndTime : "<?php echo $countdowntime; ?>",
size: "lg",
timeUp: timeisUp
});
});
As I understand you want to show difference between 2 dates. Default value = 50 minutes(value for session if user first time opened page). If user refresh page after 10 minutes in view must show difference(40). It will be something like that:
public function actionViewtimer($id) {
$this->layout = 'countdownlayout';
/** #var CHttpSession $session */
$session = Yii::app()->session;
$minutes = 50; //default value for minutes
if (!$session->offsetExists('countdowntime')) {
$session->add('countdowntime', new DateTime()); //set value to session
} else {
$timeEnd = new DateTime();
/** #var DateTime $countDownTime */
$countDownTime = $session->get('countdowntime');
$interval = $countDownTime->diff($timeEnd);
$countMinutes = $interval->days * 24 * 60;
$countMinutes += $interval->h * 60;
$countMinutes += $interval->i;
$minutes -= $countMinutes;
$session->add('countdowntime', $timeEnd); //refresh value
}
// $session->add('timersession', array($rand)); don't know for what is it
$this->render('viewtimerpage', array(
'getMinutes' => $minutes
));
}
And js:
<script>
$(function() {
$('#xlarge').countdowntimer({
minutes: <?php echo $getMinutes; ?>, //without 50
I export every day the sales of yesterday (Magento) by a custom phpscript.
Since we got directbanking i had to change the code a bit.
The idea was to set the value "direct" in the CC_Type(Visa,JBC,...) so that we have good looking data for our analytics.
The csv looks actually clean and when i do a manually import (where you customize the import) with excel or mssql it works as wished. But when i let it open by it self (like our system would do to import the data in the night) strange things happen.
In the data-/functionbar (fx) you can see that the curser is ON the D and if I insert more letters they are appendet AFTER the p from onlineshop.
the header (first line) and every following dataline become imported without the "", I know that excel sometimes does this, but it never did before with this document.
Well thats a lie i never payed attation if it is so or not, because it simply worked.
//
class Mage_Shell_Compiler extends Mage_Shell_Abstract {
const OUTPUT = false;
const DEL = "\t";
const BR = "\r\n";
const FILEPATH = '../var/export/';
const FILENAME = 'tdtaCash';
protected $_orders = array();
protected $_csv_output = '';
protected $_headers = array(
"dtTag" => false, // Bestelldatum
"fiCBox" => 94,
"fiCashier" => "onlineshop",
"fiCurrency" => array('Visa', 'MC', 'Amex', 'DC', 'JCB', 'Direct'), // Zahlungsart
"dtRev" => false // Bruttoumsatz an diesem Tag mit dieser Zahlungsart
);
/// #see $_headers for details
protected function addOrderToRows($order, $rows) {
$order_data = $order->getOrigData();
$type = $order->getPayment()->getAdditionalInformation('CC_BRAND');
switch ($type) {
case 'VISA':
$type = 'Visa';
break;
case 'MasterCard':
$type = 'MC';
break;
case 'American Express':
$type = 'Amex';
break;
case 'Diners Club':
$type = 'DC';
break;
case 'JCB':
$type = 'JCB';
break;
default:
$brand = $order->getPayment()->getAdditionalInformation('BRAND');
if ($brand == 'DirectEbankingAT') {
$type = 'Direct';
}
break;
}
if (empty($rows[$type])) {
$row = $this->_headers;
$row["dtRev"] = 0;
} else
$row = $rows[$type];
//$row['dtTag'] = date('Y-m-d', strtotime($order_data['created_at']));
$row['dtTag'] = $this->formatDate($order_data['created_at'], 'exportdate', true);
$row["fiCurrency"] = $type;
$row["dtRev"] += $order_data['grand_total'];
$rows[$type] = $row;
return $rows;
}
protected function __($msg) {
if (self::OUTPUT)
print $msg . "\n";
}
/**
* Get Orders instance
*
* #return Mage_Sales_Model_Order
*/
protected function _getOrders($day = 1) {
$timeZoneOffset = Mage::getModel('core/date')->getGmtOffset();
$yesterday = date('Y-m-d', strtotime("-$day day")) . ' 00:00:00';
$yesterday = date('Y-m-d H:i:s', strtotime($yesterday) - $timeZoneOffset);
$day--;
$today = date('Y-m-d', strtotime("-$day day")) . ' 00:00:00';
$today = date('Y-m-d H:i:s', strtotime($today) - $timeZoneOffset);
if (!$this->_orders)
$this->_orders = Mage::getResourceModel('sales/order_collection')
->addAttributeToSelect('*')
/// #note uncommented to remove daily filter
->addAttributeToFilter('created_at', array("from" => $yesterday, "to" => $today))
->addAttributeToFilter('status', array('nin' => array('holded', 'canceled', 'pending_payment', 'pending')));
return $this->_orders;
}
protected function addRowToOutput($row) {
if (isset($row["dtRev"]))
$row["dtRev"] = number_format($row["dtRev"], 2);
$this->_csv_output .= '"' . implode('"' . self::DEL . '"', $row) . '"' . self::BR;
}
protected function addCsvHeader() {
$this->addRowToOutput(array_keys($this->_headers));
}
/**
* Run script
*
*/
public function run() {
if ($this->getArg('export')) {
$day = is_numeric($this->getArg('day')) ? $this->getArg('day') : 1;
$file = self::FILEPATH . self::FILENAME . '.csv';
$this->__('orders to export ' . count($this->_getOrders($day)));
// add header if file is empty
if (!strlen(trim(file_get_contents(dirname(__FILE__) . '/' . $file))))
$this->addCsvHeader();
$rows = array();
foreach ($this->_getOrders($day) as $order)
$rows = $this->addOrderToRows($order, $rows);
while ($row = array_shift($rows))
$this->addRowToOutput($row);
file_put_contents(dirname(__FILE__) . '/' . $file, $this->_csv_output, FILE_APPEND);
$this->__($this->_csv_output);
} else {
echo $this->usageHelp();
}
}
/**
* Retrieve Usage Help Message
*
*/
public function usageHelp() {
return <<<USAGE
Usage: php -f export_tdtaCash.php -- [options]
export ... Appends data to file tdtaCash.csv in Directory var/export/
day ... days to count back
help ... This help
USAGE;
}
}
$shell = new Mage_Shell_Compiler();
$shell->run();
So my question is, may someone can explain me what kind of sourcery is responsable for this effect, and what can i do preventive to not get such results again?!
EDIT:
here is a screenshot of the CSV opend in Notepad++
Change file resolution from CSV to TXT and use Import file, specify TAB character as separator - and you'll be fine!
That's not a C SV, it's a T SV, a tab separated values file.
Excel won't know that unless you tell it and misinterprets the data.