i have this aiogram inline buttons
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from middlewares.internationlization import _
choise_sign_select_company = InlineKeyboardMarkup(row_width=1,
inline_keyboard=[
[
InlineKeyboardButton(
text=_('Капитализация ❌'),
callback_data='market_cap_of_company'
),
InlineKeyboardButton(
text=_('Кол-во акций ❌'),
callback_data='count_shares_ofustanding_of_company'
)
],
[
InlineKeyboardButton(
text=_('Цена акции ❌'),
callback_data='current_prise_share_now_of_company'
)
]
])
how to turn these buttons into a check of a button? For example, so that when you click on the "Capitalization ❌" button, the button changes to "Capitalization ✅" (when you click it again, it goes back)
and also the value was stored in the call.data from callback_data
Here comes the keyboard
#dp.message_handler(text='Подобрать компании 🤑')
async def select_sign(message: types.Message):
await message.answer(_('Выберите признаки на которых будет основываться подбор'),
reply_markup=choise_sign_select_company)
await SelectCompanies.enter_the_sign.set()
click on the button is processed here
#dp.callback_query_handler(state=SelectCompanies.enter_the_sign)
async def select_interval(call: types.CallbackQuery):
text = call.data
await call.answer(text)
You can manually implement this feature using callbacks.
For example, store current button`s state in callback and change it after click.
Also, there is aiogram-dialog library. You can find special "checkbox" button there
You can try it:
from aiogram_dialog import DialogManager, ChatEvent
from aiogram_dialog.widgets.kbd import Checkbox, ManagedCheckboxAdapter
from aiogram_dialog.widgets.text import Const
async def check_changed(event: ChatEvent, checkbox: ManagedCheckboxAdapter, manager: DialogManager):
print("Check status changed:", checkbox.is_checked())
check = Checkbox(
Const("✓ Checked"),
Const("Unchecked"),
id="check",
default=True, # so it will be checked by default,
on_state_changed=check_changed,
)
Related
I made replykeboard markup bot by telebot , i need way when click the back button it’s return me to previous menu , I tried to do this but i found should every (back button) have unique name ,any way to make same “back give me many return menu ”
import telebot
token=""
bot=telebot.TeleBot(token)
main=types.ReplyKeyboardMarkup(row_width=2)
a=types.KeyboardButton('sara')
b=types.KeyboardButton('jack')
c=types.KeyboardButton('mohmmed')
d=types.KeyboardButton('ali')
main.add(a)
main.add(b)
main.add(c)
main.add(d)
sara=types.ReplyKeyboardMarkup()
a1=types.KeyboardButton('age')
b1=types.KeyboardButton('from')
c1=types.KeyboardButton('user name')
d1=types.KeyboardButton('back')
sara.row(a1,b1)
sara.row(c1,d1)
fromm=types.ReplyKeyboardMarkup()
p0=types.KeyboardButton('mousle')
p1=types.KeyboardButton('dohuk')
p2=types.KeyboardButton('arbile')
p3=types.KeyboardButton('back')
fromm.row(p0)
fromm.row(p1)
fromm.row(p2)
fromm.row(p3)
#bot.message_handler(func=lambda m:True)
def message(m):
if m.text=="sara":
bot.send_message(m.chat.id,"sara",reply_markup=sara)
elif m.text == "from":
bot.send_message(m.chat.id,"sara",reply_markup=fromm)
elif m.text=="back":
bot.send_message(m.chat.id,"sara",reply_markup=main)
elif m.text=="back":
bot.send_message(m.chat.id,"sara",reply_markup=sara)
I need the same back button return me to different menu
I'm trying to write a Telegram bot to help a friend with his online buisness.
I'm trying to make an interactive menu, but if I try to use an emoji as a prefix the #bot.message_handler doesn't read the user input, resulting in the menu not updating.
Working code (with "/" as command prefix):
#bot.message_handler(commands=["Menu"])
def startMenu(msg):
#########-START MENU-#########
markup = keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True, one_time_keyboard=True)
btnHelp = types.KeyboardButton("/Help")
##############################
markup.add(btnHelp)
bot.send_message(msg.chat.id, text="Need help?"
, reply_markup=markup)
#bot.message_handler(commands=["Help"])
def helpMenu(msg):
markup = keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True, one_time_keyboard=True)
btnBack = types.KeyboardButton("/Menu")
markup.add(btnBack)
bot.send_message(msg.chat.id, text="Test Help"
, reply_markup=markup)
Faulty code (with UNICODE emoji as prefix):
#bot.message_handler(commands=["Menu"])
def startMenu(msg):
#########-START MENU-#########
markup = keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True, one_time_keyboard=True)
btnHelp = types.KeyboardButton("\U0001F60Help")
##############################
markup.add(btnHelp)
bot.send_message(msg.chat.id, text="Need help?"
, reply_markup=markup)
#bot.message_handler(commands=["\U0001F60Help"])
def helpMenu(msg):
markup = keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True, one_time_keyboard=True)
btnBack = types.KeyboardButton("/Menu")
markup.add(btnBack)
bot.send_message(msg.chat.id, text="Test Help"
, reply_markup=markup)
You can use regular expression as there is no native way to change the prefixes:
#bot.message_handler(regexp="^\U0001F60H(your_command)")
So im using this code and i have from discord_components import * and DiscordComponents(bot) in on_ready. I did pip install --update discord-components. This is the code im using.
#bot.command()
async def button(ctx):
await ctx.channel.send(
"This is a button test :smile:",
components =[
Button(style=ButtonStyle.blue, label ="Button 1"),
Button(style=ButtonStyle.red, label ="Button 2"),
Button(style=ButtonStyle.URL, label ="this is a picture", url="https://www.planetware.com/wpimages/2020/02/france-in-pictures-beautiful-places-to-photograph-eiffel-tower.jpg" ),
],
)
component = discord.Component
interaction1 = await client.wait_for("button_click", check = lambda i: i.component.label.startswith("Button 1"))
await interaction1.respond(content = "Button 1 Seems like it working")
interaction2 = await client.wait_for("button_click", check = lambda i: i.component.label.startswith("Button 2"))
await interaction2.respond(content = "Button 2 Seems like it working")
There is no error message and when I do $button it prints but if I click on a button it says interaction failed(still no error message) I'm new to button so if you could help me that would be great
Hello I recently made a help command using discord_components buttons (I know they arent fully supported by Discord.py) but I still went ahead. The problem is that whenever I run the command and receive the Buttons to click on, they alway say "This Interaction Failed". I can't seem to find what's wrong. Please help.
Thanking You,
NightMX.
import discord
from discord.ext import commands
from discord_components.component import ButtonStyle
from discord_components import DiscordComponents, Button, Select, SelectOption
from discord_components.interaction import InteractionType
class BotCommands(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
async def helpv2(self, ctx):
funbutton = Button(style=ButtonStyle.grey, label="Fun Commands", id="funcmds")
monkedevbutton = Button(style=ButtonStyle.grey, label="Attachment Commands", id="monkecmds")
# utilitybutton = Button(style = ButtonStyle.grey, label = "3", id = "embed3")
funembed = discord.Embed(title="Fun Commands", colour=discord.Colour.orange())
funembed.add_field(name="k.joke", value="Sends a Random joke from PyJokes")
monkedevembed = discord.Embed(title="Fun Commands", colour=discord.Colour.blurple())
monkedevembed.add_field(name="k.dog", value="Sends a Random Dog Fact")
monkedevembed.add_field(name="k.monkey", value="Sends a Monkey's Picture")
monkedevembed.add_field(name="k.bird", value="Sends a Bird's Picture")
await ctx.send(
"Kola's Beta Help Command!",
components=[[funbutton, monkedevbutton]]
)
buttons = {
"funcmds": funembed,
"monkedcmds": monkedevembed
}
while True:
event = await self.bot.wait_for('button_click')
if event.channel is not ctx.channel:
return
if event.channel == ctx.channel:
response = buttons.get(event.component.id)
if response is None:
await event.channel.send(
"Something went Wrong"
)
if event.channel == ctx.channel:
await event.respond(
type=InteractionType.ChannelMessageWithSource, embed=response
)
def setup(client):
client.add_cog(BotCommands(client))
should be content="something" instead of embed = response
Can somebody help, I cant understand how can I do my bot with two menus.
first - is "short menu" where you press the button and its open "long menu" with all functions
second - in "long menu" menu where I have all functions and the button "Back to Menu".
I cant understnand how to make the button "Back to Menu" that go back me to the "short menu"
help me please. And the Main -- the clicking on buttons should not send a message to the user
def telegram():
with open("madata") as f3:
info = yaml.safe_load(f3)
token = mytoken
bot = Bot(token=token)
dp = Dispatcher(bot)
#greeting message, pin this message in private chat
#dp.message_handler(commands=['start'])
async def greeting(message: types.Message):
chat_id = message.chat.id
msg = '''hello friend'''
# body of keyboard
small_function = ReplyKeyboardMarkup(
keyboard = [
[
KeyboardButton(text="show functions", callback_data='open menu all functions')
]
],
resize_keyboard=True
)
all_functions = ReplyKeyboardMarkup(
keyboard = [
[
KeyboardButton(text="function 1", callback_data='do function1')
],
[
KeyboardButton(text="function 2", callback_data='do function2')
],
[
KeyboardButton(text="back to menu", callback_data=' open menu small_function')
],
],
resize_keyboard=True
)
#insert my keyboard
sent_message = await bot.send_message(chat_id=chat_id, text=msg,parse_mode = "Markdown", reply_markup=small_function)
print(sent_message.message_id)
#bot.callback_query_handler(func=lambda call: True)
async def answer(call):