Answer the question
In order to leave comments, you need to log in
How to execute 2 functions in python using telegram bot?
Hello. I made a parser bot in a cart that parses currency from Google. Question: How can I make 2 functions work in parallel? That is, the functions: currency_USD = Currency_USD() and currency_EUR.check_currency_EUR(). Because if the dollar function is the first one, then only the dollar is parsed into the cart and vice versa. If I send a request for the euro, then only the euro is parsed and the dollar is not seen, although both requests are displayed in the terminal using a print.
import requests
from bs4 import BeautifulSoup
import telebot
from telebot import types
from threading import Thread
from multiprocessing import Process
bot = telebot.TeleBot('1156880733:AAGNUiAiw79mbTVLoD4tOZtykU5JLTORgOI')
@bot.message_handler(commands=['start'])
def start(message):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1)
btn1 = types.KeyboardButton('Доллар $')
btn2 = types.KeyboardButton('Фунт Стерлингов £')
btn3 = types.KeyboardButton('Евро €')
markup.add(btn1, btn2, btn3)
send_mess = 'Воспользуйтесь клавиатурой'
sti = open('stic/fr.webp', 'rb')
bot.send_sticker(message.chat.id, sti)
bot.send_message(message.chat.id, send_mess, sti, reply_markup=markup)
class Currency_EUR:
EUR_LINK = 'https://www.google.com/search?client=firefox-b-d&q=%D0%B5%D0%B2%D1%80%D0%BE+%D0%BA+%D1%80%D1%83%D0%B1%D0%BB%D1%8E'
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0'}
def get_currency_price_EUR(self):
full_page = requests.get(self.EUR_LINK, headers=self.headers)
soup = BeautifulSoup(full_page.content, 'html.parser')
convert = soup.findAll("span", {"class": "DFlfde", "class": "SwHCTb", "data-precision": 2})
return convert[0].text
def check_currency_EUR(self):
print('Выполняется парсинг евро...')
currency_EUR = str(self.get_currency_price_EUR())
print("Сейчас курс: 1 евро = " + str(currency_EUR))
@bot.message_handler(content_types=['text'])
def EUR(message):
get_message_bot = message.text.strip().lower()
if get_message_bot == 'евро €':
bot.send_message(message.chat.id, 'Сейчас курс: 1 евро = ' + str(currency_EUR) + ' руб.')
# Основной класс
class Currency_USD:
# Ссылка на нужную страницу
DOLLAR_RUB = 'https://www.google.com/search?client=firefox-b-d&q=%D0%B4%D0%BE%D0%BB%D0%BB%D0%B0%D1%80+%D0%BA+%D1%80%D1%83%D0%B1%D0%BB%D1%8E'
# Заголовки для передачи вместе с URL
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36'}
# Метод для получения курса валюты
def get_currency_price_USD(self):
# Парсим всю страницу
full_page = requests.get(self.DOLLAR_RUB, headers=self.headers)
# Разбираем через BeautifulSoup
soup = BeautifulSoup(full_page.content, 'html.parser')
# Получаем нужное для нас значение и возвращаем его
convert = soup.findAll("span", {"class": "DFlfde", "class": "SwHCTb", "data-precision": 2})
return convert[0].text
# Проверка изменения валюты
def check_currency_USD(self):
print('Выполняется парсинг доллара...')
currency_USD = str(self.get_currency_price_USD())
print("Сейчас курс: 1 доллар = " + str(currency_USD))
@bot.message_handler(content_types=['text'])
def USD(message):
get_message_bot = message.text.strip().lower()
if get_message_bot == 'доллар $':
bot.send_message(message.chat.id, "Сейчас курс: 1 доллар = " + str(currency_USD) + " руб.")
# Создание объекта и вызов метода доллара
currency_USD = Currency_USD()
currency_USD.check_currency_USD()
#Создание объекта и вызов метода евро
currency_EUR = Currency_EUR()
currency_EUR.check_currency_EUR()
# Создание объекта и вызов бота
bot.polling(none_stop=True)
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