Image

(Last change: 04.05.2024)

To test the performance of the bot - a random number generator in Python, we used preconfigured telegram bot server. This bot can generate a random number from a range you specify.

Let's proceed with the installation:

source my-tel-bot/bin/activate

Let's replace our demo bot with the existing one:

/root/my-tel-bot/bot.py

import telebot
import random

# to create buttons
from telebot import types

bot = telebot.TeleBot('Key received from @BotFather')

# Creating a button after the /start command
@bot.message_handler(commands=['start'])
def welcome(message):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
random_sender = types.KeyboardButton("Came a random number")
markup.add(random_sender)
bot.send_message(message.chat.id, 'Number generator started', parse_mode='html',
reply_markup=markup)

# Button click tracking
@bot.message_handler(content_types=['text'])

def first_number_step(message):
if message.text == 'Пришли случайное число':
msg = bot.send_message(message.chat.id, 'Enter start of range')

# jump to function second_number_step
bot.register_next_step_handler(msg, second_number_step)
else:
bot.send_message(message.chat.id, 'There is no such command')

# Getting the first number of a range
def second_number_step(message):
global NUM_first
NUM_first = int(message.text)
msg = bot.send_message(message.chat.id, 'Enter the end of the range')

# jump to function result_number_step
bot.register_next_step_handler(msg, result_number_step)

# Getting the second number of a range
def result_number_step(message):
global NUM_second
NUM_second = int(message.text)

# Function call result(message)
result(message)

# Result output (random)
def result(message):
bot.send_message(message.chat.id, 'Random number: ' + str(random.randint(NUM_first, NUM_second)))

# To keep the bot running all the time
bot.polling(none_stop=True)

Done, don't forget to specify your key token in the script and restart the service:

service my-tel-bot restart



No Comments Yet