gpt4 book ai didi

python - 如何在特定时间发送消息 TelegramBot

转载 作者:行者123 更新时间:2023-12-02 06:47:21 26 4
gpt4 key购买 nike

您好,我想在特定时间从机器人发送消息(没有来 self 的消息),例如每周六早上 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)

但是 ofc 这不起作用。尝试过

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

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

最佳答案

我遇到了同样的问题,我能够使用 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)))

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

关于python - 如何在特定时间发送消息 TelegramBot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48288124/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com