Search code examples
pythontelebot

How can I stop iterating once a certain number of SMS messages have been sent?


I'm making a telegram bot that will send SMS through a parser and I need to loop until about 20 SMS are sent. I am using the telebot library to create a bot and for the parser I have requests and BeautifulSoup.

import telebot
import requests
from bs4 import BeautifulSoup
from telebot import types

bot = telebot.TeleBot('my token')

@bot.message_handler(commands=['start'])
def start(message):
    mess = f'Привет, сегодня у меня для тебя 100 Анг слов! Удачи <b>{message.from_user.first_name}</b>'
    bot.send_message(message.chat.id, mess, parse_mode='html')

@bot.message_handler(commands=['words'])
def website(message):
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=1)
    word = types.KeyboardButton('100 Слов')
    markup.add(word)#создание самой кнопки.
    bot.send_message(message.chat.id, 'Подевиться слова', reply_markup=markup)

@bot.message_handler(content_types=['text'])
def get_user_commands(message):
    if message.text == '100 Слов':
        url = 'https://www.kreekly.com/lists/100-samyh-populyarnyh-angliyskih-slov/'
        response = requests.get(url)
        soup = BeautifulSoup(response.text, 'lxml')
        data = soup.find_all("div", class_="dict-word")
        for i in data:
            ENG = i.find("span", class_="eng").text
            rU = i.find("span", class_="rus").text
            bot.send_message(message.chat.id, ENG, parse_mode='html')
            bot.send_message(message.chat.id, rU, parse_mode='html')

bot.polling(none_stop=True)

I tried to do it this way:

if i >= 20:
   break

but this does not work. I also tried to do it like this:

if data.index(i) >= 20
   break

Solution

  • Don't bother with the stopping the loop or slicing the array, tell bs4 to limit the result:

    data = soup.find_all("div", class_="dict-word", limit=20)