G
G
Gleb2020-02-23 03:03:18
Python
Gleb, 2020-02-23 03:03:18

The terminal gives an error when launching a file with a bot and the weather does not work correctly. Can you help?

# Telegram HlebetsBot
import pyowm
import telebot
import random
import config

from telebot import types

owm = pyowm.OWM('...', language = "ru")
bot = telebot.TeleBot(config.TOKEN)

@bot.message_handler(commands=['start'])
def welcome(message):
    sti = open('/contents/sticker.webp', 'rb')
    bot.send_sticker(message.chat.id, sti)

    #keyboard
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    item1 = types.KeyboardButton("Случайное число")
    item2 = types.KeyboardButton("Погода")

    markup.add(item1, item2)

    bot.send_message(message.chat.id, "Привет, {0.first_name}!\nЯ - <b>{1.first_name}</b>, твой Телеграм асистент, есть вопрос обратись ко мне, я с радостью помогу.".format(message.from_user, bot.get_me()),
    parse_mode = 'html', reply_markup = markup)

@bot.message_handler(content_types =['text'])
def lalala(message):
    if message.chat.type == 'private':
        if message.text == 'Случайное число':
            bot.send_message(message.chat.id, str(random.randint(0, 100)))
        elif message.text == 'Погода':
            bot.send_message(message.chat.id, "Введите название города")
        observation = owm.weather_at_place(message.text)
        w = observation.get_weather()
        temp = w.get_temperature('celsius')["temp"]

        answer = "В " + message.text + " сейчас " + w.get_detailed_status() + "\n"
        answer += "Температура в районе " + str(temp) + "\n\n"

        if temp < 10:
            answer += "Сейчас достаточно достаточно холодно, одень куртку"
        elif temp < 20:
            answer += "Сейчас прохладно, возьми что нибудь полегче чем куртка"
        else:
            answer += "Сейчас тепло, одень что нибудь легкое"

        #bot.reply_to(message, message.)
        bot.send_message(message.chat.id, answer)

# RUN
if __name__ == '__main__':
    bot.polling( none_stop = True )


Error from terminal:
Traceback (most recent call last):
File "telebot.py", line 10, in
bot = telebot.TeleBot(config.TOKEN)
AttributeError: module 'config' has no attribute 'TOKEN' Error

comment: file config.py I have in the same folder and the token too.

What you need with the weather:
When you click on the button, the weather asks for the city, but I don’t understand how to make it read the name of the city (which the user will write) and say weather data, and in case of an error it gives something like (city not found).

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Karbivnichy, 2020-02-23
@hleb_ets

More likelybot = telebot.TeleBot(config.token)

import telebot
import pyowm

owm = pyowm.OWM('key', language = "ru")
bot = telebot.TeleBot('token')

@bot.message_handler(content_types=['text'])
def send_echo(message):
  try:
    observation = owm.weather_at_place( message.text )
    w = observation.get_weather()
    temp = w.get_temperature('celsius')["temp"]
    hum = w.get_humidity()
    time = w.get_reference_time(timeformat='iso')
    wind = w.get_wind()["speed"]

    answer ="В городе " + message.text + " сейчас " + w.get_detailed_status() + "\n"
    answer += "Температура сейчас в районе " + str(temp) + "\n\n" + "\nСкорость ветра: " + str(wind) + "м/с" + "\n" + "\nВлажность: " + str(hum) + "%" + "\n" + "\nВремя: " + str(time) + "\n"

    if temp < 11:
      answer += "Сейчас очень холодно."
    elif temp < 20:
      answer += "Сейчас прохладно, лучше одеться потеплее."
    else:
      answer += "Температура в норме!"

    bot.send_message(message.chat.id, answer)
  except pyowm.exceptions.api_response_error.NotFoundError:
    bot.send_message(message.chat.id,'Ошибка! Город не найден.')
  except pyowm.exceptions.api_response_error.UnauthorizedError:
  	print('Не верный ключ pyowm!')

bot.polling( none_stop = True)
input()

5e51c6541e19e731240098.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question