How to change the message sent by the inline bot? - python

There is this code:
#bot.inline_handler(lambda query: query.query == 'text')
def query_text(inline_query):
try:
r = types.InlineQueryResultArticle('1', 'text', types.InputTextMessageContent('2'))
bot.answer_inline_query(inline_query.id, [r])
except Exception as e:
print(e)
I do not understand how to make the message "2" be changed, for example, after 2 seconds to "3".
I wanted to do it through bot.edit_message_text () but I didn’t understand where to get all the id from.

You get the inline_message_id parameter of editMessageText by listening for ChosenInlineResult updates.
Also notice that you should do the following things to be able to receive updates like that:
Contact #BotFather and use the /setinlinefeedback command to enable receiving those updates.
Add chosen_inline_result to the allowed_updates parameter when you getUpdates.

Related

Can't catch an exception, system just closes

I've implemented an orchestrator in python that makes some requisitions to an API. My problem is that sometimes it gets stucked in a request. To solve that I used the timeout parameter. Now I want to implement something so I can retry doing the requisition, but first I need to take care of the exception. For that I tried this:
uri = MS_MONITOR + "/api/monitor/advise/lawsuit/total/withProgressDaily"
try:
response = requests.get(uri, headers={"Correlation-Id": CORRELATION_ID}, timeout = 10)
except requests.exceptions.RequestException as e:
logging.info("[{}] [{}] {}".format("ERROR de Timeout", response.status_code, uri))
print("Deu timeout")
I put the timeout as 10 just to force it to happen, the problem is that it doesn't go into the exception part below, the cmd just closes. I've tried using this one too but it didn't work either:
except requests.exceptions.Timeout
If there's lack of information in my post please let me know so I'll provide it. Thank you!

Detect failed edit of channel in discord.py

I am making a discord bot which lets users edit a voicechannel name. My code is something like this:
channel = client.get_channel(id)
try:
await channel.edit(name="new name")
except:
raise
And it raises fine if the name is invalid but not if the name is valid and the change was not successful due to Discords rate limit of I guess 2 edits every 10 minutes.
I think the problem is that there is no error on my end, Discord is just waiting with the response. Is there a way to give my request a timeout of about 5 seconds and raise if it takes too long?
I would check for both an error and a None response. Better yet, why not just check that the name after the change is what it should be?
I don't think you can add in a timeout directly into the function call but this is the type of thing you might want to loop and add a asyncio.sleep into. Ignoring the first part, you might have something like this:
NEW_NAME = "new name"
while True:
e = None
try:
await channel.edit(name=NEW_NAME)
except Exception as e: pass
# "channel.name" is pseudo-code.
# Use whatever method to check the name.
if <channel.name> != NEW_NAME:
print ("Exception: %s ...(whatever else you want to print)" % e)
await asyncio.sleep(60) # or whatever you think reasonable
else:
break

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 take multiple inputs on Twilio-Whatsapp?

I'm using Twilio with Whatsapp, I want to take multiple inputs from users on Whatsapp but I am only able to get the first input.
My first input is usually "hello" from user
then my query
and the second input I want
```
#app.route("/allr", methods=['POST'])
def start():
phonestring = request.form["From"]
phonenumber = int(re.search(r'\d+', phonestring).group(0))
print(phonenumber)
resp = MessagingResponse()
msg1 = request.form.get('Body') #usually hello or something to initialize
l1 = (db.search(User.Phone == phonenumber))
if len(l1)!=0:
aj=l1[0]
print(aj['Preference'])
pref=aj['Preference']
print("Done")
resp.message("{} News".format(pref))
else:
resp.message("Which updates would you like?\n1.National\n2.Regional")
pref = request.form.get('Body') # I need input but I get it as hello(the input above)
print(pref)
resp.message("You selected: {}".format(pref))
Item3 = {'Phone': phonenumber, 'Preference': pref}
db.insert(Item3)
return str(resp)
```
Expected: Regional/National
What I get: Hello
Twilio developer evangelist here.
It appears that when you receive the user's first message that you are not storing anything in the database. So, when you receive their second message, you look up the user by phone number but still don't find anything.
Also, it sounds like you are expecting to receive more than one message within this piece of code. Each webhook request from Twilio corresponds to one incoming message. If you are looking for the response to the second message, it will be in a second webhook.

How to forward every channels updates using Telethon

I would like to forward every updates from channels to my bot.
Is it Possible with ForwardMessagesRequest ?
I tried to use this Telethon example to build my personal code:
https://github.com/LonamiWebs/Telethon/wiki/Forwarding-messages
But i wasn't able to do it. And i don't know if it's possible to use that part of code inside a callback function. Someone can help me? Thank you
Ok, i'm really confused so let's go back.
In this code I just try to retrieve last messages from an user chat and forward them to my bot:
def callback(update):
source_chat_id = "here i put the user id"
source_hash = "here i put his access_hash"
source_chat = InputPeerUser(source_chat_id, source_hash)
total_count, messages, senders = client.get_message_history(
source_chat, limit=10)
for msg in reversed(messages):
print ("msg:", msg.id, msg)
msg = messages[0]
print ("msg id:", msg.id)
dest_chat = "here i tried to put the number of my bot ID"
result = client.invoke(ForwardMessagesRequest(from_peer=source_chat, id=[msg.id], random_id=[generate_random_long()], to_peer=dest_chat))
client.add_update_handler(callback)
The print was correct but i didn't receive anything to my bot chat.
I know that there will be a lot of errors so please be patient and sorry.

Categories