在特定时间php从电报机器人发送消息



我正在尝试用php开发一个简单的telegram bot。我希望我的机器人每天在同一时间发送消息。我试着插入if,如果我写"/"开始";这个循环:

$tosend = time(); //I find the current time
while(1)
{
sleep(1); 
if(time() > $tosend)  //If the current time exceeds the recorded one, I send the message
{
sendMessage($id, "Ciao");
$tosend += 3600;
}
}

它部分起作用。除了";你好";消息他还发送其他不应该发送的消息,发送消息的频率不是一个小时(如上所述(,机器人程序的其余部分非常慢(我认为是因为无限循环(。有更好的方法吗?或者我可以改进吗?谢谢大家

关于它发送的其他消息,它应该是您放入代码中的switch语句的默认分支。

关于频率,我认为这是Telegram的问题,我也有它没有错误,但它可以解决存储您需要的信息在主机上的.txt文件,以避免在同一小时内发送相同的消息,我尝试为您制作一个脚本:

if(!file_exists("check.txt")){
$myfile = fopen("check.txt", "w+");
fwrite($myfile, time());
fclose($myfile);
}
while(true){
$read = file("check.txt");
$tosend = $read[0];
$tosend += 3600;
while(true){
if(time() < $tosend){
sleep(1); 
}else{
$myfile = fopen("check.txt", "w+");
fwrite($myfile, time());
fclose($myfile);
sendMessage($id, "Ciao");
break 1;
}
}
}

最新更新