S
S
s1zen2021-06-08 14:00:01
Python
s1zen, 2021-06-08 14:00:01

Can't change Telebot Python message. What am I doing wrong?

import telebot
from telebot import types
from config import BOT_TOKEN 
import requests
import keyboard as kd
from pprint import pprint
import datetime

bot = telebot.TeleBot(BOT_TOKEN)
print("Запускаю...")

# API:
url = f"https://www.cbr-xml-daily.ru/daily_json.js"
r = requests.get(url)
data = r.json()


# commands:
@bot.message_handler(commands=['start'])
def starting(message):
    bot.send_message(message.chat.id, "Привет, я знаю курс валют.", reply_markup=kd.starting)
@bot.callback_query_handler(func=lambda call: True)
def choice_course(call):
    today = datetime.datetime.now()
    date_and_time = (today.strftime('%Y-%m-%d %H:%M:%S'))
    bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="Выберите валюту", reply_markup=kd.choice_cource)
    usd  = data['Valute']['USD']['Value']
    usd_name = data['Valute']['USD']['Name']
@bot.callback_query_handler(func=lambda call: True)
def course(call):
    if call.data == 'usd':
        bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=f"На {date_and_time}\n\nКурс {usd_name}: {usd}")














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

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Krostelev, 2021-06-08
@s1zen

you have two identical button handlers that process the same requests.

@bot.callback_query_handler(func=lambda call: True)

When you click on the button, the corresponding handler is searched from top to bottom. stumbles upon the first and never enters the second at all.
or do the processing of buttons in one handler
@bot.callback_query_handler(func=lambda call: True)
def choice_course(call):
    if call.data == 'usd':
            bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=f"На {date_and_time}\n\nКурс {usd_name}: {usd}")
    else:
        today = datetime.datetime.now()
        date_and_time = (today.strftime('%Y-%m-%d %H:%M:%S'))
        bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="Выберите валюту", reply_markup=kd.choice_cource)
        usd  = data['Valute']['USD']['Value']
        usd_name = data['Valute']['USD']['Name']

Or describe the correct function in the handlers themselves
@bot.callback_query_handler(func=lambda call: call.data=='usd')
def course(call):
    bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=f"На {date_and_time}\n\nКурс {usd_name}: {usd}")

But in this case, this handler must be placed higher in code than the previous one.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question