G
G
Glebych2021-06-10 22:24:37
Python
Glebych, 2021-06-10 22:24:37

Telegram bot. How to properly insert a 'while True' loop so that everything works correctly?

import telebot
import config
import random
from time import sleep
from os import system
 
from telebot import types
 
bot = telebot.TeleBot(config.TOKEN)

@bot.message_handler(commands=['start'])
def start(message):
    ground=types.ReplyKeyboardMarkup(resize_keyboard=True)
    button1=types.KeyboardButton('Играть')
    button2=types.KeyboardButton('Правила гри')
    button3=types.KeyboardButton('Відповісти')
    ground.add(button1, button2, button3)

    text1=('Вітаю, {0.first_name}!\nЯ <b>{1.first_name}</b>, бот створений щоб допомогти вам в грі.'.format(message.from_user, bot.get_me()))
    bot.send_message(message.chat.id, text1, parse_mode='html', reply_markup=ground)


@bot.message_handler(content_types=['text'])
def text2(message):
    if message.chat.type == 'private':
        if message.text == 'Агата':
            cities = ["Абаза", "Алатырь", "Азов","Астрахань","Алупка","Алагир","Аркадак","Асино","Абакан","Алдан","Андреаполь","Аткарск",
"Ардатов","АлейскАлександровск","АхтубинскАбдулино","Александров","Альметьевск","Ачинск","Абинск","Алексеевка","Арск",
"АргунАгидель","Алексин","Анжеро-Судженск","АрзамасАдыгейск","Амурск","Ардон","АрмавирАгрыз","Арамиль","Апрелевка","АрсеньевАзнакаево",
"Аша","Апатиты","АртемАлапаевск","Анапа","Апшеронск","АртемовскийАксай","Ангарск","Асбест","АрхангельскАлушта","Армянск",
"Алзамай","АртемовскАк-Довурак","Александровск-Сахалинский","Анива","АнадырьБабаево","Барабинск","Балашов","Батайск","Балабаново",
"Балахна","Балашиха","Брянск","Балтийск","Березники","Бологое","Бежецк","Белая","Калитва","Беслан","Благовещенск","Бердск",
"Белоярский","Братск","Бобров","Белгород","Березовский","Баксан","Боровичи","Белебей","Бирск","Барнаул","Большой","Камень",
"Белово","Благовещенск","Биробиджан","Бор","Белогорск","Благодарный","Богородицк","Борзя","Белорецк","Богданович","Борисоглебск",
"Бийск","Белореченск","Бугульма","Буденновск","Буй"]
    
            last_char = '' 
            while True:
                sleep (5)
                city = message.text 

                if last_char == '' or city[0] == last_char:
                    if city in cities:

                        if city[-1] == 'Ь' or city[-1] == 'Ъ':
                            last_char = city[-2].title()
                        else:
                            last_char = city[-1].title()
                        cities.remove(city)
                    else:
                        bot.send_message(message.chat.id,"Ошибка: Вы ввели несуществующий город (а может и существующий, но тут такого нет)"
                            "\nИЛИ! Этот город был уже использован ранее")
                else:
                    bot.send_message(message.chat.id,f"Ошибка: Город должен начинаться на букву '{last_char}'")
                        
                for i in range(len(cities)):
                    if cities[i].find(last_char) == 0:
                        bot.send_message(message.chat.id,f' {cities[i]}')
                        if cities[i][-1] == 'Ь' or cities[i][-1] == 'Ъ':
                            last_char = cities[i][-2].title()
                        else:
                            last_char = cities[i][-1].title()
                        cities.remove(cities[i])
                        break
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 question

Ask a Question

731 491 924 answers to any question