There is such a code, it opens the keyboard after changing the message, but an error is issued when executing.
elif (merchant_id == 2):
bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text='Your request was accepted', parse_mode="Markdown", reply_markup=keyboard.main_keyboard())
Error:
A request to the Telegram API was unsuccessful. Error code: 400. Description: Bad Request: inline keyboard expected
But when executing another part of the code, the keyboard opens immediately. Here is the keyboard code:
def main_keyboard():
markup = types.ReplyKeyboardMarkup(one_time_keyboard = False, resize_keyboard = True)
btn1 = types.KeyboardButton('Hello')
btn2 = types.KeyboardButton('Start')
btn3 = types.KeyboardButton('Add')
btn4 = types.KeyboardButton('Stop')
markup.add(btn1, btn3)
markup.add(btn2)
markup.add(btn4)
return markup
How to solve the problem so that the keyboard opens correctly in both parts of the code ?
Maybe it is necessary to replace or add some functionality.
main_keyboard returns a ReplyKeyboardMarkup, but the reply_markup parameter edit_message_text only accepts InlineKeyboardMarkup objects as explained in the official API docs. In the header of the "updating messages" paragraph it says:
Please note, that it is currently only possible to edit messages without reply_markup or with inline keyboards.
Related
I'm having a problem with handling incoming messages. I have a main menu in my bot with one InlineKeyboardMarkup. When the button is pressed, the bot should wait for user input and then send a message. But in my case, it sends the message, then it waits for user input and then it sends again the message. And that's a big problem, because after the message it sends, it should go back to main menu.
I'm using pythonTelegramBotAPI (telebot)
That's the code:
#bot.callback_query_handler(func = lambda call: True)
def query_handler(call):
bot.answer_callback_query(callback_query_id = call.id, text = '')
cid = call.message.chat.id
mid = call.message.message_id
msg = call.message
if call.data == 'request':
bot.edit_message_text('Test - Answer to request', cid, mid, reply_markup = markup)
request_handler(msg)
################# Keyboard sections #################
#bot.message_handler()
def request_handler(msg):
if msg.content_type == 'text':
bot.send_message(msg.chat.id, 'Request accepted')
# and here the code to go back, that I didn't do yet
Perhaps this conversational bot example will help you to understand how to build dialog with user.
Correct answer
The decorator #bot.messge_handler() is used to tell to the function that it must be handle incoming messages. So, when there's a new message, the function will do the code inside it automatically. This means that the function must not be called manually as is not required. Calling the function will, in fact, run the code inside it, instead of initializing it and waiting for an input.
And here's a tip: if the user send a message, the function is automatically called. But what happens when the bot send a message? The function is also called, because it doesn't make difference about who sent the message. So, to avoid using the function also for bot messages, just put an if in like this:
if msg.from_user.is_bot == False:
# Here put what the function should do
The if, as you can see, check if the message is coming from the bot.
I am developing a little bot in python with the library python-telegram-bot, and I am stucked with a little problem :
I have an InlineKeyboardButton with the parameter switch_inline_query_current_chat, so when the user click on it, a command is automatically written in its chat.
But, that command is preceded with the mention of the bot (with an #).
The problem is my bot isn't answering in that case, and I have no idea why..
Is there a solution to make the button do not preced the command with the mention of the bot ?
From #BotFather the groups are allowed and the privacy group is turned off.
Thank you a lot
Edit : This is the code for the CommandHandler :
def getEntry(update, context):
if not (is_allowed_user(update.message.from_user.username, 'getEntry')):
context.bot.send_message(chat_id=update.effective_chat.id,
text='Who the hell are you #' + update.message.from_user.username + ' ?')
return
search = ' '.join(context.args)
infos, err = get_infos_people(search)
if err is not None:
context.bot.send_message(chat_id=update.effective_chat.id, text=err)
return
context.bot.send_message(chat_id=update.effective_chat.id, text=beautify_infos(infos),
parse_mode=ParseMode.MARKDOWN, reply_markup=getMainKeyboard(infos))
get_handler = CommandHandler('get', getEntry, filters=~Filters.update.edited_message)
And this is the code for the buttons :
def getMainKeyboard(infos):
keyboard = [InlineKeyboardButton("modify",
switch_inline_query_current_chat="/get " + infos[0] + "<write here>")]]
return InlineKeyboardMarkup(keyboard)
Note: I'm no python-telegram-bot expert, but the issue/fix should be non-lib related
Your commandHandler() is defined as so:
get_handler = CommandHandler('get', getEntry, filters=~Filters.update.edited_message)
This links the /get command to the getEntry handler.
Issue
Since the command is only fired at /get, you'll need to add a second command with the name of the bot so it will register that command as-well;
get_handler = CommandHandler([ 'get', 'get#myBot' ], getEntry, filters=~Filters.update.edited_message)
The first argument (command) accepts both a str or a list as the docs shows
Had the same issue in some other library, don't think there is a 'cleaner' way of handeling this.
I am writing a telegram bot in Python. I want to send messages with bold letters. I tried to inclose message inside both * and **, but it does not solve the problem.
Is there a function for mark up or HTML formatting or a way to do it?
You should use:
bot.send_message(chat_id=chat_id, text="*bold* Example message",
parse_mode=telegram.ParseMode.MARKDOWN)
Or:
bot.send_message(chat_id=chat_id, text='<b>Example message</b>',
parse_mode=telegram.ParseMode.HTML)
More info at:
https://github.com/python-telegram-bot/python-telegram-bot/wiki/Code-snippets#message-formatting-bold-italic-code-
This is a little bit late. But i hope to be helpful for others:
import telepot
token = 'xxxxxxxxxxxxxxx' # Your telegram token .
receiver_id = yyyyyyyy # Bot id, you can get this by using the next link :
https://api.telegram.org/bot<TOKEN>/getUpdates. Note that you should
replace <TOKEN> with your token.
bot = telepot.Bot(token)
message = "*YOUR MESSAGE YOU WENT TO SEND.*" #Any characters between ** will be
send in bold format.
bot.sendMessage(receiver_id, message , parse_mode= 'Markdown' )
I try use python-telegram-bot
I do not understand how to handle InlineKeyboardButton correctly.
def start(bot, update):
currencies = [currency for currency in API().get_currencies()]
keyboard = [[InlineKeyboardButton("{}".format(c), callback_data='{}'.format(c))] for c in currencies]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text('Select the currency you want to exchange:', reply_markup=reply_markup)
updater.dispatcher.add_handler(CommandHandler('start', start))
Now, I need to process the selection by passing it to another function with the help of ChosenInlineResultHandler, but I do not understand how to do this.
You are using Inline Buttons and the query coming back is simply CallbackQuery but not InlineQuery, yes the names are a bit confusing by the Telegram Bot API.
You can use telegram.ext.CallbackQueryHandler to catch the queries upon buttons pressed.
def button_callback(bot, update):
# data is the callback_data where you declared in the buttons
query = update.callback_query.data
if query == "something":
# do something here
updater.dispatcher.add_handler(CallbackQueryHandler(button_callback))
This is a minimal example of how to catch the buttons' data. You can check here for a complete example.
I'm writing a python telegram bot and I want to work with inline keyboard bottom.
I write this code below:
from telegram import *
from telegram.ext import *
mbti_message = 'This is a test massage that should sent in MBTI part'
def startx(bot, update):
keyboard = [[InlineKeyboardButton("Option 1", callback_data='1'),
InlineKeyboardButton("Option 2", callback_data='2')],
[InlineKeyboardButton("Option 3", callback_data='3')]]
reply_markup = InlineKeyboardMarkup(keyboard)
chat_id = update.message.chat_id
bot.sendMessage(chat_id, "Message Sent From Function STARTX", reply_markup=reply_markup)
def buttomx(bot, update):
query = update.callback_query
bot.edit_message_text(text="Selected option: %s" % query.data,
chat_id=query.message.chat_id,
message_id=query.message.message_id)
def start (bot,update):
keyboard_list = [[InlineKeyboardButton("ABOUT US", callback_data='1')],
[InlineKeyboardButton("MBTI Test Start", callback_data='2')]]
reply_markup = InlineKeyboardMarkup(keyboard_list)
chat_id = update.message.chat_id
start_message_sent = "Welcome To My Bot Please Chose Your Options"
bot.sendMessage(chat_id,start_message_sent, reply_markup=reply_markup)
bot.sendMessage(chat_id,start_message_sent_global,reply_markup=reply_markup)
def bottom(bot, update):
counter = 0
query = update.callback_query
chat_id = query.message.chat_id
selected_option = int(query.data)
if selected_option==1 :
bot.sendMessage(chat_id,"You Chose About Us Section Thanks For Choosing Us")
elif selected_option==2:
bot.sendMessage(chat_id,"You Are Ready To Start Test ...")
command = 'mbti'
updater.dispatcher.add_handler(CommandHandler(command=command, callback=startx))
updater.dispatcher.add_handler(CallbackQueryHandler(buttomx))
updater.start_polling()
When user press bottom MBTI set command to mbti and pass it to command handler and when command handler get mbti command start to run starx function.
but when i use this code below in the if condition it send it before checking if condition
updater.dispatcher.add_handler (CommandHandler (command = command , startx)
What should i do in this condition?
Use a ConversationHandler for deep interactive menu. other way you can storing userState, and call function with State.
for more information see docs example it also supported user_data and RegExp for powerful handling message from users.
don't forget: data stores in memory and you may have lost or incorrect in some case. good think cleaned user_data in entry point,
each function can have many returns to other entry and with other side - each of entry has many different function in different matching case.