【问题标题】:How to send message in specific time TelegramBot如何在特定时间发送消息 TelegramBot
【发布时间】:2018-06-25 13:37:20
【问题描述】:

您好,我想在特定时间从机器人发送消息(没有我的消息),例如每个星期六早上 8:00。 这是我的代码:

import telebot
import config
from datetime import time, date, datetime

bot = telebot.TeleBot(config.bot_token)
chat_id=config.my_id    

@bot.message_handler(commands=['start', 'help'])
def print_hi(message):
    bot.send_message(message.chat.id, 'Hi!')


@bot.message_handler(func=lambda message: False) #cause there is no message
def saturday_message():
    now = datetime.now()
    if (now.date().weekday() == 5) and (now.time() == time(8,0)):
        bot.send_message(chat_id, 'Wake up!')

bot.polling(none_stop=True)

但这不起作用。 尝试过

urlopen("https://api.telegram.org/bot" +bot_id+ "/sendMessage?chat_id=" +chat_id+ "&text="+msg)

但还是没有结果。不知道怎么办,请帮忙指点一下。

【问题讨论】:

  • 问题出在哪里?是时机还是你的机器人根本没有发送任何东西?
  • 机器人不发送消息
  • 没有你的日期检查是否可以工作?
  • 不,只是不知道如何在这里制作循环(如何定期检查条件)
  • 我有同样的问题,但在 C# stackoverflow.com/questions/64918790/…

标签: python python-3.x telegram telegram-bot


【解决方案1】:

您可以使用 cron/at 或类似的方式管理任务。

制作一个脚本,可能叫alarm_telegram.py

#!/usr/bin/env python
import telebot
import config
    
bot = telebot.TeleBot(config.bot_token)
chat_id=config.my_id
bot.send_message(chat_id, 'Wake up!')

然后像这样在 cron 中编程。

00 8 * * 6 /path/to/your/script/alarm_telegram.py

编码愉快!!!

【讨论】:

  • 是的,但这并不有趣 :) 感谢您的建议
  • 没意思?遮阳篷没有解决您的问题?
【解决方案2】:

我遇到了同样的问题,我可以使用 schedule 库解决它。我总是发现例子是最简单的方法:

import schedule
import telebot
from threading import Thread
from time import sleep

TOKEN = "Some Token"

bot = telebot.TeleBot(TOKEN)
some_id = 12345 # This is our chat id.

def schedule_checker():
    while True:
        schedule.run_pending()
        sleep(1)

def function_to_run():
    return bot.send_message(some_id, "This is a message to send.")

if __name__ == "__main__":
    # Create the job in schedule.
    schedule.every().saturday.at("07:00").do(function_to_run)

    # Spin up a thread to run the schedule check so it doesn't block your bot.
    # This will take the function schedule_checker which will check every second
    # to see if the scheduled job needs to be ran.
    Thread(target=schedule_checker).start() 

    # And then of course, start your server.
    server.run(host="0.0.0.0", port=int(os.environ.get('PORT', 5000)))

我希望你觉得这很有用,为我解决了问题:)。

【讨论】:

  • 谢谢!你是唯一一个能够回答这个被问了很多次的问题的人。使用线程是关键。
  • 感谢代码示例,我最近一直在学习线程的概念,但是如果没有示例,很难将这些概念与现实世界的应用程序联系起来。不过我有一个问题,您使用调度程序安排了作业,然后创建了一个线程,但您没有调用 bot.polling?为什么呢。如果您不进行轮询,为什么还需要线程调度?
  • 终于!非常感谢。
  • @shy-tan 抱歉,对此的回复延迟。如果您查看Thread(target=schedule_checker).start() 行,您将看到我创建了一个线程对象,然后调用它的启动方法。这将无限期地在自己的线程中运行schedule_checker。在这种情况下无需使用bot.polling。希望这会有所帮助!
  • 尝试在 VSCode 中使用它。已经 pip 安装了 schedule 包,但是 VSCode 说这个包是无法解析的。你能帮我吗?
猜你喜欢
  • 2019-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-25
  • 1970-01-01
  • 1970-01-01
  • 2018-12-28
  • 1970-01-01
相关资源
最近更新 更多