T
T
Timur2022-02-15 21:41:38
Python
Timur, 2022-02-15 21:41:38

Problems with launching a telegram bot in Python, what should I do?

Hello, I apologize in advance for the stupid question. I recently also started creating telegram bots on PytelegrambotAPI
, and now I ran into an error. I created a simple bot with functions, I write a script for it to start, and after the /start command, the bot sends nothing and does not react. Here is the code with comments

#_______________________________________________________________________________________________________________________
#imported libraries

from email import message
import telebot
from telebot import types as type
from random import randrange

#------------------------------------

#random_flowers = randrange(1 , 3)
#sport_random = randrange(1 , 3)
#cr = randrange(1 , 3)

#------------------------------------

#_____________________________________________________________________________________________________________________
#markup script
bot = telebot.TeleBot(*Токен скрыт , но он есть*)

bot.message_handler(commands=['Start'])
markup = type.ReplyKeyboardMarkup(resize_keyboard=True)
item1 = type.KeyboardButton("Любимый спорт")
item2 = type.KeyboardButton("любимые Цветы")
item3 = type.KeyboardButton("Мой создатель")
item4 = type.KeyboardButton("Любимая машина")
item5 = type.KeyboardButton("Выход")
markup.add(item1, item2, item3, item4)
#_______________________________________________________________________________________________________________________
#functions

def sport(sport_random):
    if sport_random == 1:
        bot.send_message(message.chat.id, "Мне нравится баскетбол . Особенно обувь в баскетболе)")

    elif sport_random == 2:
        bot.send_message(message.chat.id, "Футбол - моя жизнь . Обожаю его)")

    elif sport_random == 3:
        bot.send_message(message.chat.id, "Волейбольчик топчик)")





def flowers(random_flowers):
    if random_flowers == 1:
        bot.send_message(message.chat.id, "Ромашки такие красивые , жаль что я бот и не могу ощутить их запах(")

    elif random_flowers == 2:
        bot.send_message(message.chat.id, "Розы , красота , обожаю их)))")
    elif random_flowers == 3:
        bot.send_message(message.chat.id, "Тюльпанчики красавчики , ахах)")





def car(cr):
    if cr == 1:
        bot.send_message(message.chat.id, " Lamborghini , машина для богини)")
    elif cr == 2:
        bot.send_message(message.chat.id, "Ferrari обожаю больше всех")

    elif cr == 3:
        bot.send_message(message.chat.id, "Как бы странно не звучало , но мне нравится Лада приора)")



#______________________________________________________________________________________________
#main_script

bot.send_message(message.chat.id, f"Привет , я бот с интеллектом . У меня также есть свои интересы , которые ты можешь узнать , и после кнопки \"Выход\" я обновляю интересы . Пока что так , но скоро будет много интересного)))", reply_markup=markup)
if message.type == 'private':
    if message.text == "Любимый спорт":
        sport_random = randrange(1 , 3)
        sport(sport_random)
    elif message.text == "любимые Цветы":
        random_flowers = randrange(1 , 3)
        flowers(random_flowers)
    elif message.text == "Мой создатель":
        bot.send_message(message.chat.id, "Мой создатель Тимур - простой 12-летний школьник , пытающийся занятся программированием. Если что пишите @int3llect")
    elif message.text == "Любимая машина":
        cr = randrange(1 , 3)
        car(cr)
    elif message.text == "Выход":
        bot.send_message("Успешно выйдено.")

    else:
        bot.send_message(message.chat.id, "Извини , функция чат бота пока недоступна , но летом Тимур будет над ней работать , а пока наслаждайся тем что есть)")



#___________________________________________________________________________________________________
#polling

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

In advance, sorry for the stupid question :-/

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
shurshur, 2022-02-15
@shurshur

There's a lot wrong here, and it's not strange that it doesn't work.
At the first level of nesting, the main code, which should do 3 things:
1. Import modules.
2. Create an object of the TeleBot class.
3. Call polling from him.
What does polling do? This is a loop that pulls the getUpdates method from the Bot API and receives new updates from Telegram from time to time. For each, it calls handlers (handler). By default, there is not a single handler, and the simplest bot does nothing without them - it only downloads and immediately discards received messages.
Next, you need to make handlers. They are normal functions. For example, a message handler accepts an object of the Message class, in which all the data on the message: sender, text, time sent, chat id, etc.
In order for the bot to know that this particular function is a handler for such and such an event with such and such conditions, decorators must be used. For example:

@bot.message_handler(commands=['start','menu'])
def start_message(message):
  # в этом обработчике мы можем обработать команду /start или /menu,
  # при этом можно брать из message данные о сообщении:
  # message.text - текст
  # message.from_user - объект класса User с данными отправителя
  # message.chat - объект класса Chat с данными о чате (группа или приват)
  ... тут нужные действия ...

Using a decorator without @ and a subsequent function declaration is pointless - it simply won't do anything (because a decorator is a specially designed class, calling bot.message_handler creates an instance of this class, from which a special method is then called, but this does not happen here).
It is still possible to call bot.send_message at the first nesting level, but... but here, for example, message.chat.id is passed into it - what is message? This variable is not in the script. And where would it come from if the message is received inside the bot.polling call and needs to be passed to a handler that would need to be wrapped as a function with a decorator? There is none in the code. And the message variable will be relevant only inside this handler, it will not be available outside the function.
In general, it cannot work in any way.
It's a bad idea to start learning a language with bots, a field in which you already need to have a certain level of knowledge. It makes sense to start with the basics. Do the simplest tasks first (like "ask the user to enter two numbers and print their sum"), master loops and functions, work with files and strings, and all that. Then, returning to the topic of bots, you will already do everything not blindly, but at least somehow understanding what is happening.
Imagine if you bought a car and couldn't figure out how to start it. I would start poking around. For example, I found a nipple on a wheel - I pulled it. The janitor spins if you make an effort (oh, it’s broken, now it won’t ride?). There was a pipe sticking out at the back - should a water hose be connected to it? This is how you make a bot right now. Even if they tell you what to change, you still won’t learn how to program and you won’t understand what you did.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question