A
A
AlmaShooter2016-06-08 21:33:33
Python
AlmaShooter, 2016-06-08 21:33:33

How to embed JSON parsing into telegram bot in python?

There is a code that gets the temperature in the city from a JSON request, maybe not the best option, but everything works fine.

import requests

city = 'Сочи'

r = requests.get('http://api.openweathermap.org/data/2.5/weather?&units=metric&q=%s&appid=0c9f3c052f1d81b7062750ff0926f345' %(city))
data = r.json()
temp = data["main"]["temp"]
print('Температура в',city , ':', temp, '°C')

There is also a telegram bot code on pytelegramapi. When you try to embed the code above into it, it gives errors. As I understand it, it is trying to send a request to the telegram server and that they actually swear.
import telebot
import config
import requests


bot = telebot.TeleBot(config.token)

@bot.message_handler(commands=["start"]) # Обработка /start
def handle_start(message):
    bot.send_message(message.from_user.id, 'Hi! \nMy friend')

@bot.message_handler(content_types=["text"])
def handle_t(message):
    if message.text[:7] == "Погода " or message.text[:7] == "погода " :
            city = message.text[7:]
            r = requests.get('http://api.openweathermap.org/data/2.5/weather?&units=metric&q=%s&appid=0c9f3c052f1d81b7062750ff0926f345<img src="https://habrastorage.org/files/8fa/5f5/313/8fa5f5313b37438eb250b22cf041f2dd.png" alt="image"/>' % (city))
            data = r.json()
            temp = data["main"]["temp"]
            bot.send_message(message.chat.id, 'Температура в ', city, ': ',temp , '°C')

bot.polling(none_stop=True, interval=0)

56a3aa1a50c249d08ed94dfea29de599.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
AlmaShooter, 2016-06-10
@AlmaShooter

Solution:
Wrong use of bot.send_message function. In this case, you need to write like this

bot.send_message(message.chat.id, "Температура в {}: {} C".format(city, temp))

#
#algooptimize #bottize, 2016-06-08
@user004

bot.send_message(message.chat.id, 'Temperature in ', city, ': ',temp , '°C')
commas separate the arguments (parameters), and what are the parameters in this function?)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question