Answer the question
In order to leave comments, you need to log in
How to make a telegram bot automatically send messages at a given time in Python, Telebot?
I am making a telegram bot to send weather information at a given time.
The automatic weather reporting function does not work.
It is necessary that the bot automatically sends a message, and does not respond to the sent one.
import telebot
import pyowm
from pyowm.exceptions.api_response_error import NotFoundError
import time
from datetime import datetime
bot = telebot.TeleBot("TOKEN")
owm = pyowm.OWM('ID', language='ru')
@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
bot.send_message(message.chat.id,
"*Привет! Я бот прогноза погоды, я могу сообщать данные о погоде в выбранное время.*"
+ '\n\n' + "_Укажите город:_", parse_mode="Markdown")
@bot.message_handler(content_types=['text'])
def get_city(message): # выбор города
try:
owm.weather_at_place(message.text)
city = "Успешно! Город " + "*" + message.text + "*" + " выбран" + "\n\n" \
+ "Теперь введите _время_ *(0-23 часов)*, в которое хотите получать уведомления о погоде:"
bot.send_message(message.chat.id, city, parse_mode="Markdown")
bot.register_next_step_handler(message, get_indicated_time)
return get_city
except pyowm.exceptions.api_response_error.NotFoundError:
bot.send_message(message.chat.id,
"*Город введен не корректно / не найден.* \n\n _Пожалуйста, повторите попытку_",
parse_mode="Markdown")
def get_indicated_time(message): # выбор времени
try:
indicated_time = message.text
if 0 <= int(indicated_time) < 24:
correct_number = "_Время_ выбранно успешно!" + "\n\n" "Уведомление о погоде придет в *" \
+ indicated_time + "* час(a/ов)"
chat_id = message.chat.id
bot.send_message(message.chat.id, correct_number, parse_mode="Markdown", reply_markup=keyboard1)
bot.register_next_step_handler(message, send_notice)
elif int(indicated_time) < 0 or int(indicated_time) > 23:
wrong_number = "*Неверное время*"
bot.send_message(message.chat.id, wrong_number, parse_mode="Markdown")
bot.register_next_step_handler(message, get_indicated_time)
except ValueError:
wrong_answer = "Введите время *(0-23 часов)*:"
bot.send_message(message.chat.id, wrong_answer, parse_mode="Markdown")
bot.register_next_step_handler(message, get_indicated_time)
def send_notice(chat_id): # отправка сообщения о погоде
indicated_time = get_indicated_time
city = get_city
chat_id = get_indicated_time
while indicated_time == datetime.now().hour:
observation = owm.weather_at_place(city)
w = observation.get_weather()
temp = w.get_temperature('celsius')['temp']
notice_city = "*" + city + ":" "*" + "\n" + "Темп. " + "_" + str(temp) \
+ "°C_" + ", " + w.get_detailed_status()
bot.send_message(chat_id, notice_city, parse_mode="Markdown")
break
bot.polling(none_stop=True, interval=0)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question