简体   繁体   English

如何安排电报机器人发送消息?

[英]how to schedule a telegram bot to send a message?

I am trying to create a Telegram bot that sends a message at a specific time, 5:30pm.我正在尝试创建一个在特定时间(下午 5:30)发送消息的 Telegram 机器人。 However, the ways a was trying are not correct.但是,a 尝试的方法并不正确。

I wanted to trigger send_message regarding to the time and without the necessity of the user to send any /command.我想触发有关时间的 send_message,而无需用户发送任何 / 命令。

import telebot
import datetime

TOKEN = 'MyToken'
bot = telebot.TeleBot(TOKEN)


@bot.message_handler(commands=['start'])
def send_welcome(message):
    message_id=message.chat.id
    bot.reply_to(message,"Welcome")


bot.polling()

Until now I was trying to add something like that, of course it is not python but kind of pseudocode just to explain:到目前为止,我一直在尝试添加类似的东西,当然它不是 python,而是一种伪代码,只是为了解释:

if currenttime=17:30
 send_message(idchat, "mymessage")

Thank you in advance.先感谢您。

If I understand correctly, you need to check your system time before sending a message, you could use the following code [source] :如果我理解正确,您需要在发送消息之前检查您的系统时间,您可以使用以下代码[source]

from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)

To send a message you could use the following code [source] :要发送消息,您可以使用以下代码[source]

def test_send_message():
        text = 'CI Test Message'
        tb = telebot.TeleBot(TOKEN)
        ret_msg = tb.send_message(CHAT_ID, text)
        assert ret_msg.message_id 

To compare the time, you may use:要比较时间,您可以使用:

if current_time=='17:30:00':
    test_send_message()

You can use schedule python library.您可以使用调度python 库。 First of all import the necessary modules首先导入必要的模块

import schedule
import time
import telegram

Then you have to create a function that will repeat in every x time.然后你必须创建一个每 x 次重复的函数。 Here the bot will send me message in every 5 seconds.在这里,机器人将每 5 秒向我发送一次消息。

TOKEN='your_token'
bot = telegram.Bot(token=TOKEN)
def job():
    bot.sendMessage(chat_id=<chat_id>, text="Hello")

schedule.every(5).seconds.do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

For more informations about schedule Read the documentation有关时间表的更多信息 阅读文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM