How to edit an inline message in aiogram telegrambot - telegram-bot

An inline message is sent when the result is displayed inline and should change after 1 second!
Can Aiogram use edit_message()
#dp.inline_handler()
async def inline_echo(inline_query: types.InlineQuery):
print(inline_query)
text = inline_query.query or 'You'
input_content = types.InputTextMessageContent(text)
item = types.InlineQueryResultArticle(
id=inline_query.id,
thumb_url="https://t.me/iCoderNet",
title=f'I ❤️ {text!r}',
input_message_content=input_content,
)
#RESULT
await inline_query.answer(results=[item], cache_time=1)
#EDIT
sleep(2)
await bot.edit_message_text("❤️", inline_message_id=id)
Please explain how to Edit !!!

Related

the post sent by the bot telegram is not deleted for all users

I have a function which allows to send a message to all users who clicked the start button.
#dp.message_handler(commands=['Yes'], state=Post.send_post)
async def process_name(message: Message, state: FSMContext):
for admin in admins:
if message.from_user.id == admin:
async with state.proxy() as data:
data['send_post'] = message.text
conn = sqlite3.connect('data.db')
cur = conn.cursor()
cur.execute(f'SELECT * FROM users')
result = cur.fetchall()
await state.finish()
print(result)
try:
for z in range(len(result)):
print(result[z][0])
await dp.bot.send_photo(chat_id=result[z][0], photo=data['photo'], caption=data['CAPTHION'], reply_markup=kb)
print(z)
test = message.message_id + 1
await dp.bot.send_message(chat_id=result[z][0], text=f'id поста {test}')
except BotBlocked:
print('Пользователь заблокировал бота')
except ChatNotFound:
print('Пользователь не запускал бота')
Also, there is a function that allows you to delete messages by id. The administrator enters the deleted command, after which the bot asks to enter its id. When the Administrator enters an id, the bot deletes messages through a loop, iterating over the id. But for some reason, it only deletes a post from one user, then it throws an error
aiogram.utils.exceptions.MessageToDeleteNotFound: Message to delete not found
Please help me I can't figure out why
#dp.message_handler(commands=['deleted'], state=None)
async def send_id(message: Message):
for admin in admins:
if message.from_user.id == admin:
await Post.Sen_id.set()
await dp.bot.send_message(chat_id=admin, text='Введите ID поста, который нужно удалить.')
await Post.next()
#dp.message_handler(state=Post.del_mess)
async def deleted_post(message: Message, state: FSMContext):
for admin in admins:
if message.from_user.id == admin:
async with state.proxy() as data:
data['sen_id'] = message.text
try:
conn = sqlite3.connect('data.db')
cur = conn.cursor()
cur.execute(f'SELECT * FROM users')
result = cur.fetchall()
#message_ids = int(data['sen_id'])
for z in range(len(result)):
print('/////////////deleted/////////////')
print(result)
print(z)
await dp.bot.delete_message(chat_id=result[z][0], message_id=data['sen_id'])
print('Сообщение удалено')
#chat_id = message.chat.id
#await dp.bot.delete_message(message.chat.id, message_ids)
await dp.bot.send_message(chat_id=admin, text='пост удален')
except BotBlocked:
print('Пользователь заблокировал бота')
except ChatNotFound:
print('Пользователь не запускал бота')
This is a code that does what you wish for - deleting message with given message_id in every chat where that message exist. Later I'll explain why this is actually not a good solution.
The problem is with the placing of the try-except block. In your code, if deleting the message fails for a single user, for all users that are past him in the database the deletion will not be even attempted. Solution would be to place the try-except block in the for loop.
...
if message.from_user.id == admin:
async with state.proxy() as data:
data['sen_id'] = message.text
conn = sqlite3.connect('data.db')
cur = conn.cursor()
cur.execute(f'SELECT * FROM users')
result = cur.fetchall()
#message_ids = int(data['sen_id'])
for z in range(len(result)):
try:
print('/////////////deleted/////////////')
print(result)
print(z)
await dp.bot.delete_message(chat_id=result[z][0], message_id=data['sen_id'])
print('Сообщение удалено')
#chat_id = message.chat.id
#await dp.bot.delete_message(message.chat.id, message_ids)
await dp.bot.send_message(chat_id=admin, text='пост удален')
except BotBlocked:
print('Пользователь заблокировал бота')
except ChatNotFound:
print('Пользователь не запускал бота')
except Exception as e:
print(e)
...
However, after testing this approach, I believe you will realise that there is a problem: if you send a "post" to multiple users, it may have a different message_id for different users! So you would have to use a different approach.

Aiogram fails to create sticker pack

I ran into a problem with stickers, the code is below
async def sticker_set(msg:types.Message):
await bot.create_new_sticker_set(
user_id=msg.from_user.id,
name = "what_den_things",
title = "What Denis thinks",
png_sticker = "boring.png",
emojis = "👍"
)

Flask - How can I use my functions on the URL

I'm starting to learn Flask and maybe I'm just using the wrong words to search, but here's the problem.
I have this class:
class Video(Resource):
#marshal_with(resource_fields)
def get(self, video_id):
result = VideoModel.query.filter_by(id=video_id).first()
if not result:
abort(404, message="Could not find video with that id")
return result
#marshal_with(resource_fields)
def put(self, video_id):
args = video_put_args.parse_args()
result = VideoModel.query.filter_by(id=video_id).first()
if result:
abort(409, message="Video id taken...")
video = VideoModel(id=video_id, name=args['name'], views=args['views'], likes=args['likes'])
db.session.add(video)
db.session.commit()
return video, 201
#marshal_with(resource_fields)
def patch(self, video_id):
args = video_update_args.parse_args()
result = VideoModel.query.filter_by(id=video_id).first()
if not result:
abort(404, message="Video doesn't exist, cannot update")
if args['name']:
result.name = args['name']
if args['views']:
result.views = args['views']
if args['likes']:
result.likes = args['likes']
db.session.commit()
return result
And I'm trying to make so when I have an URL like http://127.0.0.1/5000/video/put/1/Test/80/2, I can use the funtion from the URL by typing it. Is there any way to do this? Thanks in advance!

Telegram bot: How to get chosen inline result

I'm sending InlineQueryResultArticle to clients and i'm wondering how to get chosen result and it's data (like result_id,...).
here is the code to send results:
token = 'Bot token'
bot = telegram.Bot(token)
updater = Updater(token)
dispatcher = updater.dispatcher
def get_inline_results(bot, update):
query = update.inline_query.query
results = list()
results.append(InlineQueryResultArticle(id='1000',
title="Book 1",
description='Description of this book, author ...',
thumb_url='https://fakeimg.pl/100/?text=book%201',
input_message_content=InputTextMessageContent(
'chosen book:')))
results.append(InlineQueryResultArticle(id='1001',
title="Book 2",
description='Description of the book, author...',
thumb_url='https://fakeimg.pl/300/?text=book%202',
input_message_content=InputTextMessageContent(
'chosen book:')
))
update.inline_query.answer(results)
inline_query_handler = InlineQueryHandler(get_inline_results)
dispatcher.add_handler(inline_query_handler)
I'm looking for a method like on_inline_chosen(data) to get id of the chosen item. (1000 or 1001 for snippet above) and then send the appropriate response to user.
You should set /setinlinefeedback in #BotFather, then you will get this update
OK, i got my answer from here
Handling user chosen result:
from telegram.ext import ChosenInlineResultHandler
def on_result_chosen(bot, update):
print(update.to_dict())
result = update.chosen_inline_result
result_id = result.result_id
query = result.query
user = result.from_user.id
print(result_id)
print(user)
print(query)
print(result.inline_message_id)
bot.send_message(user, text='fetching book data with id:' + result_id)
result_chosen_handler = ChosenInlineResultHandler(on_result_chosen)
dispatcher.add_handler(result_chosen_handler)

how to handle multiple return values in scrapy from splash

i'm using scrapy with splash, in my splash i can send multiple values but in my scrapy code i could not handle all.for example,
this my splash script
splash_script = """
function main(splash)
local url = splash.args.url
return {
html = splash:html(),
number = 1
}
end
"""
The method trigger splash from scrapy
yield scrapy.Request(
url= response.urljoin(url),
callback = self.product_details,
errback=self.error,
dont_filter=True,
meta = {
'splash':{
'endpoint': 'render.html',
'cache_args': ['lua_source'],
'args' :{
'index': index,
'http_method':'GET',
'lua_source': self.splash_script,
}
}
},
)
The call back method
def product_details(self,response):
print response.body
This method receives only html content, i cant see the number
Your are printing response.body . This only includes the html.
You have to use response.data to see the 1.
You can also access the elements individually:
response.data['html']
or
response.data['number']
And when you return stuff, make sure you are assigning it in the return statement:
NOT-
html = splash:html()
number = 1
return {number,html}
BUT
return {number = 1, html = splash:html()}
Basically, you have to assign the JSON keys in the return statement even if you might have done so outside.
Extra info but that really screwed me up and you might run into the same problem.