Back button in replykeyboard markup telegram bot - python

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

Related

checkbox inline button in aiogram python

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,
)

How can I make PySimpleGui read my input and update my window?

I am not sure if this has been answered before, sorry for a duplicate if it was, but I couldn't find it anywhere clearly.
I am making a GUI for my simple AIML chatbot (entertainment purposes mostly)
and I found PySimpleGui. I read the whole documents of it and been trying to use their code, implementing it into my own small code I got from a tutorial.
Originally:
kernel = aiml.Kernel()
kernel.learn("std-startup.xml")
kernel.respond("load aiml b")
while True:
input_text = input("You: ")
response = kernel.respond(input_text)
print("Csigusz Foxoup (bot): "+response)
I got this code working, all good (Thanks Misbah)
And I got my bot to say some words in the cmd accurately.
Next I wanted to add a simple gui.
I'd much rather it look more chatty but all I could come up with with my lacking coding experince is a simple window with 2 buttons and 2 texts.
The cood looks like this:
import aiml
import PySimpleGUI as sg
kernel = aiml.Kernel()
kernel.learn("std-startup.xml")
kernel.respond("load aiml b")
sg.theme('LightBlue 1')
layout = [[sg.Text('You: '), sg.Text(size=(12,1), key='-mytext-')],
[sg.Text('Csigusz Foxoup (bot): '), sg.Text(size=(12,1), key='-CSI-')],
[sg.Input(key='-myinput-')],
[sg.Button('Send message'), sg.Button('Bye!')]]
window = sg.Window('Csigusz Foxoup, your friend in a box (bot)', layout, [200,400])
while True:
event = window.read()
values = window.read()
if event == sg.WIN_CLOSED or event == 'Bye!':
break
if event == 'Send message':
# change the "output" element to be the value of "input" element
input_text = (values)
response = kernel.respond(input_text)
window['-mytext-'].update(values['-myinput-'])
print("Csigusz Foxoup(bot): "+response)
window.close()
And it produces a nice little window for me. looks like this
My problem is that when I type something, and click the buttons, nothing happens. When I press close window (X) I get an error message saying: "You have tried 100 times to read a closed window, you need to add a check for event == WIN_CLOSED, ERROR"
Now since i have a check, also a button, I have no idea why it doesnt work. Also don't know how I could get the button to send my bot the user text then retrieve the bot output.
What Am I doing wrong? Thank you for all replies in advance. All help greatly appreciated! 🙏
All your problem is that you use .read() in wrong way.
You have to use only one .read() which returns both values as tuple (event, values)
event, values = window.read()
print('event:', event)
print('values:', values)
Minimal working code (without aiml)
import PySimpleGUI as sg
sg.theme('LightBlue 1')
layout = [[sg.Text('You: '), sg.Text(size=(50,1), key='-mytext-')],
[sg.Text('Csigusz Foxoup (bot): '), sg.Text(size=(50,1), key='-CSI-')],
[sg.Input(key='-myinput-')],
[sg.Button('Send message'), sg.Button('Bye!')]]
window = sg.Window('Csigusz Foxoup, your friend in a box (bot)', layout, [200,400])
while True:
event, values = window.read()
print('event:', event)
print('values:', values)
if event == sg.WIN_CLOSED or event == 'Bye!':
break
if event == 'Send message':
input_text = values['-myinput-']
response = "some response for " + input_text
#response = kernel.respond(input_text)
window['-mytext-'].update(input_text)
window['-CSI-'].update(response)
window.close()

how to add submit button in streamlit (The button inside a button seems to reset the whole app.Why?)

when i click answer button it refreshing whole app. please see this link for what i am exactly expecting https://youtu.be/WO2mK1VnlZU. just download SessionState.py file from this link(adapted from https://gist.github.com/tvst/036da038ab3e999a64497f42de966a92 93) to import SessionState Thanks in advance
import streamlit as st
import SessionState
import random
import operator
def random_problem():
st.markdown("<h1 style = 'text-align:center; color:green;'>Simple Math</h1>", unsafe_allow_html=True)
session_state = SessionState.get(name = "", button_start = False)
session_state.name = st.text_input("Enter Your Name")
button_start = st.button('Start Game')
if button_start:
session_state.button_start = True
if session_state.button_start:
st.write("Welcome ", session_state.name)
session_state.operators = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv,
}
session_state.num1 = random.randint(1,10)
session_state.num2 = random.randint(1,10)
session_state.operation = random.choice(list(session_state.operators.keys()))
session_state.answer = session_state.operators.get(session_state.operation)(session_state.num1,session_state.num2)
st.write('What is:', session_state.num1, session_state.operation, session_state.num2,'?')
session_state.ans = st.text_input('Answer: ')
session_state.button_submit = st.button('Answer')
if session_state.button_submit:
if session_state.answer == session_state.ans:
st.write('Correct')
else:
st.write('Incorrect')
random_problem()
```[![when i click answer button it keep on refreshing whole app][1]][1]
[1]: https://i.stack.imgur.com/IowEQ.png
That`s how streamlit works - every time you change your choice (for example click on a button) it runs the whole script again.
But - you can use caching in order to cache things that you have to calculate again and again.
Please read here about caching in streamlit - https://docs.streamlit.io/en/stable/caching.html
For future references, Streamlit now have forms which will wait to run the codes until form submit button is pressed.
with st.form("key1"):
# ask for input
button_check = st.form_submit_button("Button to Click")
# do something to calculate. Will not run until button is clicked.
See the blog post by Streamlit. https://blog.streamlit.io/introducing-submit-button-and-forms/

How to create a single widget in the same GUI with tkinter in python

I'm trying to create a GUI that has two buttons: One checks whether the user has provided all the required inputs while the other runs a backend script. My problem is that this GUI will run for as long as the user wants to perform the backend task. The problem is: every time the user clicks on the 'check' button, another 'run' button is created right bellow the one last created. I need the 'run' button to be created at the same position every time the check button is clicked. I'm a newbie in python, btw. I'll appreciate if anyone can tell me if I got it all wrong. Thanks!
def verifica():
fluxo=vfluxo.get()
permissoes=vpermissoes.get()
results = vresults.get()
if fluxo==2:
label4 = Label(setup_window, text='Quantas tentativas (1-20)?')
label4.pack()
tentativas = Entry(setup_window)
tentativas.pack()
else:
label5 = Label(setup_window, text='Ready!')
label5.pack()
def bot_setup():
if fluxo==2:
num_tentativas = tentativas.get()
if num_tentativas == '' or int(num_tentativas) > 20:
num_tentativas=0
messagebox.showerror('ERRO!','Digite um tamanho de lote válido (1 a 20)')
else:
num_tentativas=1
setup = {
'tipo_operacao':fluxo,
'permissoes':permissoes,
'mostrarnofim':results,
'tamanho_lote':int(num_tentativas)
}
return setup
comecar = Button(text='Run', command = bot_setup)
comecar.pack()
verificar = Button(text='Check', command = verifica)
verificar.pack()

PyQt send parameters with button click

I have a GUI that has 4 widgets which are user inputs (file in/out and directory in/out). I am trying to make a button that will do two things.
I want to button when clicked to send the four user set parameters to another imported function.
self.btn.clicked.connect(lambda: self.sendData(self.rawName, self.outName, self.directoryIn, self.directoryOut))
I was using something like this. Where send data looks like this:
def sendData(self, rawName, outName, directoryIn, directoryOut):
try:
foo.main(rawName, outName, directoryIn, directoryOut)
except TypeError:
pass
In this case foo.main is the imported function. The user input method looks like this:
def setInputDirectory(self):
options = QtGui.QFileDialog.DontResolveSymlinks | QtGui.QFileDialog.ShowDirsOnly
directoryIn = QtGui.QFileDialog.getExistingDirectory(self,
"Some Directory",
self.directoryLabelIn.text(), options)
if directoryIn:
self.directoryLabelIn.setText(directoryIn)
Finally, I want to have the button (btn) be clickable only when all four values are entered in the gui.
self.rawName = ""
self.outName = ""
self.directoryIn = ""
self.directoryOut = ""
...
self.btn.clicked.connect(self.sendData)
self.btn.setEnabled(False) # disable button here, enable it later
so you can simply send those parameters directly:
def sendData(self):
try:
foo.main(self.rawName, self.outName, self.directoryIn, self.directoryOut)
except TypeError:
pass
also after every input, check if all four values are entered and if so enable button:
def areAllFourValuesEntered(self):
if (self.rawName!="" and self.outName!="" and self.directoryIn!="" and self.directoryOut!=""):
self.btn.setEnabled(True)

Categories