Answer the question
In order to leave comments, you need to log in
How to make a random response from a list in a Telegram bot in Python?
Sorry, I don't even know how to put it.
In general, I have 5 answers in the list: [apple', 'banana', 'pear', 'peach'].
How to make it so that when you press the keyboard, a random answer is given from the list.
For example:
I press the button for issuing a random fruit, and an apple is given to me.
Then I press the button again and a pear is issued
. Then I press again and, for example, a peach.
Here is the code itself:
import telebot
import random
from telebot import types
#Токен телеграм-бота
bot = telebot.TeleBot(')
#Приветственное сообщение при команде '/start'
@bot.message_handler(commands=['start'])
def zdarova(message):
bot.send_message(message.chat.id, 'Privet', reply_markup=markup )
#Клавиатура
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
item1 = types.KeyboardButton('Нажми на кнопку, и я отправлю тебе название фрукта')
markup.add(item1)
fruit = ['яблоко', 'банан', 'груша', 'персик']
@bot.message_handler(content_types=['text', 'photo'])
def messagelist(message):
if message.text == 'Нажми на кнопку, и я отправлю тебе название фрукта':
bot.send_message(message.chat.id, (fruit))
else:
bot.send_message(message.chat.id, 'ниче не понял')
#Запуск бота
bot.polling(none_stop=True, interval=0)
Answer the question
In order to leave comments, you need to log in
To do this, you just need to use random.choice ()
import telebot
import random
from telebot import types
from random import choice
#Токен телеграм-бота
bot = telebot.TeleBot('1802145216:AAHgiNmQvIpM9IdsWA3_Wpw1drPe3HKCBnE')
#Приветственное сообщение при команде '/start'
@bot.message_handler(commands=['start'])
def zdarova(message):
bot.send_message(message.chat.id, 'Privet', reply_markup=markup )
#Клавиатура
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
item1 = types.KeyboardButton('Нажми на кнопку, и я отправлю тебе название фрукта')
markup.add(item1)
fruit = ['яблоко', 'банан', 'груша', 'персик']
@bot.message_handler(content_types=['text', 'photo'])
def messagelist(message):
if message.text == 'Нажми на кнопку, и я отправлю тебе название фрукта':
bot.send_message(message.chat.id, random.choice(fruit))
else:
bot.send_message(message.chat.id, 'ниче не понял')
#Запуск бота
bot.polling(none_stop=True, interval=0)
You can also create a tekstovik for example fruit.txt with line-by-line writing:
# For example, the file will be written like this:
Apple
Banana
Pear
Peach
# Open it:
with open('fruit.txt', 'r', encoding="utf-8") as fruit:
fruit= fruit.readlines()
#And we will receive a random response in the message via random.choice(fruit)
bot.send_message(message.chat.id, random.choice(fruit))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question