weather_forecast_thread = threading.Thread(target=send_weather_forecast) NameError: name 'threading' is not define
import telebot
import os
import requests
import json
import time
import sqlite3
bot = telebot.TeleBot('6136345650:AAGfx6__KX1Hb3h9QV3tLEnHIcGbEI9JK4k')
# создаем базу данных для хранения геопозиций пользователей
conn = sqlite3.connect('user_locations.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS user_locations
(user_id INTEGER PRIMARY KEY, latitude REAL, longitude REAL)''')
conn.commit()
# функция для получения прогноза погоды по координатам
def get_weather(lat, lon):
api_key = '39e6bbf429e800651c6c2d41b76d09c0'
url = f'http://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={api_key}&units=metric'
response = requests.get(url)
if response.status_code == 200:
data = json.loads(response.content)
weather = data['weather'][0]['description']
temp = data['main']['temp']
return f'Погода сейчас: {weather}, температура: {temp}°C'
else:
return 'Не удалось получить прогноз погоды'
# функция для отправки прогноза погоды каждые 2 часа
def send_weather_forecast():
while True:
cursor.execute('SELECT * FROM user_locations')
rows = cursor.fetchall()
for row in rows:
user_id = row[0]
lat = row[1]
lon = row[2]
weather_forecast = get_weather(lat, lon)
bot.send_message(chat_id=user_id, text=weather_forecast)
time.sleep(7200) # ждем 2 часа
# обработчик команды /start
@bot.message_handler(commands=['start'])
def start_message(message):
bot.send_message(chat_id=message.chat.id, text='Привет! Отправь мне свою геопозицию, чтобы получать прогноз погоды каждые 2 часа')
# обработчик геопозиции
@bot.message_handler(content_types=['location'])
def location_message(message):
user_id = message.chat.id
lat = message.location.latitude
lon = message.location.longitude
cursor.execute('INSERT OR REPLACE INTO user_locations (user_id, latitude, longitude) VALUES (?, ?, ?)', (user_id, lat, lon))
conn.commit()
bot.send_message(chat_id=user_id, text='Спасибо! Теперь вы будете получать прогноз погоды каждые 2 часа')
запускаем поток для отправки прогноза погоды каждые 2 часа
weather_forecast_thread = threading.Thread(target=send_weather_forecast)
weather_forecast_thread.start()
# обработчик геопозиции
@bot.message_handler(content_types=['location'])
def location_message(message):
user_id = message.chat.id
lat = message.location.latitude
lon = message.location.longitude
cursor.execute('INSERT OR REPLACE INTO user_locations (user_id, latitude, longitude) VALUES (?, ?, ?)', (user_id, lat, lon))
conn.commit()
bot.send_message(chat_id=user_id, text='Спасибо! Теперь вы будете получать прогноз погоды каждые 2 часа')
# отправляем информацию админу
admin_chat_id = 'ADMIN_CHAT_ID'
admin_username = message.chat.username
location_info = f'Пользователь {admin_username} ({user_id}) отправил геопозицию: широта - {lat}, долгота - {lon}'
bot.send_message(chat_id=admin_chat_id, text=location_info)
Выдает ошибку :
weather_forecast_thread = threading.Thread(target=send_weather_forecast) NameError: name 'threading' is not define
Источник: Stack Overflow на русском