Telegram bot not responding when mentionned - python

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.

Related

Exporting specific json data from api with python

First time here, I am making a small discord.py bot as a project to experiment with python/apis a little. My goal is to print in discord specific data from an api when asked. here is the code in question.
#client.command()
async def otherusers(ctx, player):
rs = requests.get(apiLink + "/checkban?name=" + str(player))
if rs.status_code == 200:
rs = rs.json()
embed = discord.Embed(title="Other users for" + str(player), description="""User is known as: """ + str(rs["usedNames"]))
await ctx.send(embed=embed)
here is an example of the API request
{"id":1536171865,"avatar":"https://secure.download.dm.origin.com/production/avatar/prod/userAvatar/41472001/208x208.PNG","name":"_7cV","vban":{"A1 Army of One":{"bannedUntil":null,"reason":"ping >1000"}},"ingame":[],"otherNames":{"updateTimestamp":"2022-07-08T10:10:50.939000","usedNames":["ABCDE123","ABCDE1234","ABCDE12345","ABCDE1234567"]}}
If I change the string to str(rs["otherNames"]) it does function but I would like to only include the usernames, if I put str(rs["usedNames"]) and request on discord it gives me an error on PyCharm.
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'usedNames'
Thanks in advance :)
Alright so as far as I can tell, the return from your API request where the "usedNames" key is located is nested. Try:
str(rs["otherNames"]["usedNames"])
I should note this will return ["ABCDE123","ABCDE1234","ABCDE12345","ABCDE1234567"] in the example which you gave. You might want to format the list of other usernames for your final product.
I hope that helped:)

An error is issued when opening the telebot keyboard

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.

Wait for user input before a send_message

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.

How to send bold text using Telegram Python bot

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

Telegram bot API: get message id to forward it

So, I need my bot to forward a message of a chat. But in order to do so, I need to get the id of the message I want to forward (it's an old message). How can I get the id of that message so I can send it?
This is the code I'm using
#bot.message_handler(func=lambda m: True)
def reply_ids(message):
cid = message.chat.id
bot.reply_to(message, "The message id is: " + str(message.message_id) + " This chat ID is: " + str(cid))
When receiving a message, the id will be in message.message_id, as documented here.
If it is a supergroup or a channel, you can get the message_id by clicking on the message (in telegram web ) then choosing copy message link. the link will be in this form "https://t.me/channel_name/message_id"
This solution is to find the message_id manually!!
Recently I've been working with callback queries from inline buttons. One things I noticed is that in order to reply to the exact message that had the buttons Telegram needs to know both message.chat_id and message.message_id. You can try with both. This is more a comment then an answer but I don't have enough reputation to comment.
UPDATE: Now, It's update.message.message_id
Using python, if you have a CommandHandler() you can read the chat_id and message_id like so:
https://stackoverflow.com/a/72433953/1000741

Categories