簡體   English   中英

在 python-telegram-bot 中忽略來自用戶的傳入消息

[英]Ignore incoming messages from user in python-telegram-bot

我在這里問你一種方法來忽略來自 python-telegram-bot 中用戶的傳入消息。 我只是指定我的情況,讓您了解我正在尋找的代碼的目的。

所以這是一個機器人的代碼,用戶發送命令/order並且機器人詢問用戶想要訂購哪種飲料。 此時,為了避免無用的溢出,我想阻止剛剛訂購的特定用戶(大約 5 分鍾),以便讓機器人對其他用戶“免費”。

幾年前,我查看了電報為群組提供的特定選項,例如計時器聊天,不是嗎? 但我認為在與機器人的私人聊天中根本不可能。

這是我正在處理的代碼的簡化版本。

from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, Update
from telegram.ext import (
    Updater,
    CommandHandler,
    MessageHandler,
    Filters,
    ConversationHandler,
    CallbackContext,
)


WORK = range(1)
def cancel(update: Update, context: CallbackContext) -> int:
    """Cancels and ends the conversation."""
    user = update.message.from_user
    update.message.reply_text(
        'Bye! I hope we can talk again some day.', reply_markup=ReplyKeyboardRemove()
    )

    return ConversationHandler.END

def order(update: Update, context: CallbackContext) -> int:
    update.message.reply_text("please choose a drink")
    update.message.reply_text("Sangria | Martini | Analcolico")
    return WORK

def work(update: Update, context: CallbackContext)-> int:
    ord_drink= update.message.text
    
    
    update.message.reply_text("Okay i've just received your drink, you can order your drink in 5 MINUTES")

    return ConversationHandler.END






def main() -> None:
    """Run the bot."""
    # Create the Updater and pass it your bot's token.
    updater = Updater("TOKEN")

    # Get the dispatcher to register handlers
    dispatcher = updater.dispatcher


    #blocks the user after the first order for n minutes
    conv_handler2 = ConversationHandler(
        entry_points=[CommandHandler('order', order)],
        states={
            WORK : [MessageHandler(Filters.text & ~Filters.command, work)],
        },
        fallbacks=[CommandHandler('cancel', cancel)],
    )

    dispatcher.add_handler(conv_handler2)

    # Start the Bot
    updater.start_polling()

    #updater.stop()
    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()


if __name__ == '__main__':
    main()

看它:顯然,用戶的阻塞 function 必須在他的訂單后調用,但機器人應該對其他用戶免費

如果此機器人在本地運行,您可以創建一個臨時數組,在其中存儲剛剛訂購的用戶的 ID。 同時,您啟動一個將在 5 分鍾后執行的作業,並在此作業中從數組中彈出 id。

# on top of the file
silented_user = []

# in the main function
j = updater.job_queue 


# before the order is sent
if update.effective_user.id not in silented_user:
    ...


# after the order is sent
silented_user.append(update.effective_user.id)
j.run_one(pop_user, 5*60, context={'cid_to_pop':update.effective_user.id})

def pop_user(context):
    silented_user.pop(context.job.context['cid_to_pop'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM