ANTICHAT

ANTICHAT (https://forum.antichat.xyz/index.php)
-   Общие вопросы программирования (https://forum.antichat.xyz/forumdisplay.php?f=206)
-   -   [Telegram] Кнопки в боте на Python (https://forum.antichat.xyz/showthread.php?t=1435149)

Koro Kuro 02.06.2022 22:05

Как сделать кнопки в кнопке? Допустим человек в боте нажимает обычную (Reply) кнопку "Анекдот". И ему бот выдаёт текст "Выберите анекдот" и две обычные кнопки "Смешной" и "Грустный". И исходя из выбранной кнопки, бот отправит анекдот.

laiser 03.06.2022 05:35

Кнопки в кнопке? Это как так?

Также, ты не сказал, какую библиотеку ты используешь. aiogram, telebot, requests...

Написал код на aiogram, так как использую ее сам:

Python:





Код:

from
aiogram
import
executor
from
aiogram
import
Bot
,
Dispatcher
,
types
from
aiogram
.
contrib
.
fsm_storage
.
memory
import
MemoryStorage
from
aiogram
.
types
import
ReplyKeyboardMarkup

bot
=
Bot
(
token
=
BOT_TOKEN
,
parse_mode
=
types
.
ParseMode
.
HTML
)
dp
=
Dispatcher
(
bot
,
storage
=
MemoryStorage
(
)
)
@dp.message_handler
(
commands
=
[
'start'
]
)
async
def
bot_start
(
message
:
types
.
Message
)
:
menu_default
=
ReplyKeyboardMarkup
(
resize_keyboard
=
True
)
menu_default
.
row
(
"Анекдот"
)
await
message
.
answer
(
'(Reply) кнопку'
,
reply_markup
=
menu_default
)
@dp.message_handler
(
text
=
'Анекдот'
)
async
def
bot_start
(
message
:
types
.
Message
)
:
menu_default
=
ReplyKeyboardMarkup
(
resize_keyboard
=
True
)
menu_default
.
row
(
"Смешной"
,
"Грустный"
)
await
message
.
answer
(
'Выберите анекдот'
,
reply_markup
=
menu_default
)
@dp.message_handler
(
text
=
[
'Смешной'
,
'Грустный'
]
)
async
def
bot_start
(
message
:
types
.
Message
)
:
if
message
.
text
==
'Смешной'
:
await
message
.
answer
(
'Колобок повесился'
)
else
:
await
message
.
answer
(
'Он остался жив('
)
if
__name__
==
"__main__"
:
executor
.
start_polling
(
dp
)



Весь текст желательно вынести в файлик, например json или БД

Код с кнопками желательно вынести в другой скрипт, где будут все кнопки, чтобы можно было обращаться к ним из любого места.


Время: 10:10