删除电报机器人发送的传出消息(电报,python)
Posted
技术标签:
【中文标题】删除电报机器人发送的传出消息(电报,python)【英文标题】:Delete outgoing message sent by telegram bot (Telegram, python) 【发布时间】:2021-04-21 22:54:26 【问题描述】:我卡在我的代码中,因为我不知道如何输入/导出我的机器人转发的传出消息的 message_id。
背景:这只是我的代码的一部分,我随后会将其集成到主代码中。在这里,我正在测试转发消息+删除它们的功能。我能够成功地将它们转发出去,但我坚持删除它们。我能够提供chat_id 的输入,但无法为message_id 删除。有没有办法做到这一点,特别是当我要集成到可以管理几个组的主脚本时。请帮助我的菜鸟。谢谢!
我的脚本:
import logging
from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, Update
from telegram.ext import (
Updater,
CommandHandler,
MessageHandler,
Filters,
ConversationHandler,
CallbackContext,
)
TOKEN = "PUT TOKEN HERE" #INPUT HERE
# Enable logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
MSG, DELETE_MSG = range(2)
def start(update: Update, context: CallbackContext) -> int:
update.message.reply_text(
'Hi! Please post the message you would like to share:')
return MSG
def send(update: Update, context: CallbackContext) -> int:
user = update.message.from_user
logger.info("Message of %s: %s", user.first_name, update.message.text)
print(update.message.message_id)
send = update.message.forward(chat_id= 'PUT CHAT ID OF OUTGOING GROUP HERE') #INPUT HERE
update.message.reply_text("Please delete")
return DELETE_MSG
def delete_msg(update: Update, context: CallbackContext) -> int:
user = update.message.from_user
logger.info("edit of %s: %s", user.first_name, update.message.text)
update.message.delete(chat_id='PUT CHAT ID OF OUTGOING GROUP HERE',
message_id='IM STUCK HERE') #INPUT HERE
return ConversationHandler.END
def cancel(update: Update, context: CallbackContext) -> int:
user = update.message.from_user
logger.info("User %s canceled the conversation.", user.first_name)
update.message.reply_text('Bye! I hope we can talk again some day.', reply_markup=ReplyKeyboardRemove())
return ConversationHandler.END
def main() -> None:
updater = Updater(TOKEN, use_context=True)
dispatcher = updater.dispatcher
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start)],
states=
MSG: [MessageHandler(~Filters.command, send)],
DELETE_MSG: [MessageHandler(~Filters.command, delete_msg)]
,
fallbacks=[CommandHandler('cancel', cancel)],
)
dispatcher.add_handler(conv_handler)
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
【问题讨论】:
【参考方案1】:update.message.reply_text("Please delete")
必须是一个变量,然后,您将能够 context.bot.deleteMessage
和 message_id
。就像这样:
must_delete = update.message.reply_text("Please delete")
context.bot.deleteMessage (message_id = must_delete.message_id,
chat_id = update.message.chat_id)
试一试,如果这对你有用,请告诉我!!
【讨论】:
这就像魔术一样!这有助于我识别传出的 message_id 为询问!此外,我意识到我一直在尝试使用 update.message.delete,但它不起作用。我需要根据您的语法使用 context.bot.deleteMessage 。非常感谢! :) 很高兴能帮上忙!以上是关于删除电报机器人发送的传出消息(电报,python)的主要内容,如果未能解决你的问题,请参考以下文章