timerbot.pyΒΆ

  1#!/usr/bin/env python
  2# pylint: disable=unused-argument
  3# This program is dedicated to the public domain under the CC0 license.
  4
  5"""
  6Simple Bot to send timed Telegram messages.
  7
  8This Bot uses the Application class to handle the bot and the JobQueue to send
  9timed messages.
 10
 11First, a few handler functions are defined. Then, those functions are passed to
 12the Application and registered at their respective places.
 13Then, the bot is started and runs until we press Ctrl-C on the command line.
 14
 15Usage:
 16Basic Alarm Bot example, sends a message after a set time.
 17Press Ctrl-C on the command line or send a signal to the process to stop the
 18bot.
 19
 20Note:
 21To use the JobQueue, you must install PTB via
 22`pip install "python-telegram-bot[job-queue]"`
 23"""
 24
 25import logging
 26
 27from telegram import Update
 28from telegram.ext import Application, CommandHandler, ContextTypes
 29
 30# Enable logging
 31logging.basicConfig(
 32    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
 33)
 34
 35
 36# Define a few command handlers. These usually take the two arguments update and
 37# context.
 38# Best practice would be to replace context with an underscore,
 39# since context is an unused local variable.
 40# This being an example and not having context present confusing beginners,
 41# we decided to have it present as context.
 42async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
 43    """Sends explanation on how to use the bot."""
 44    await update.message.reply_text("Hi! Use /set <seconds> to set a timer")
 45
 46
 47async def alarm(context: ContextTypes.DEFAULT_TYPE) -> None:
 48    """Send the alarm message."""
 49    job = context.job
 50    await context.bot.send_message(job.chat_id, text=f"Beep! {job.data} seconds are over!")
 51
 52
 53def remove_job_if_exists(name: str, context: ContextTypes.DEFAULT_TYPE) -> bool:
 54    """Remove job with given name. Returns whether job was removed."""
 55    current_jobs = context.job_queue.get_jobs_by_name(name)
 56    if not current_jobs:
 57        return False
 58    for job in current_jobs:
 59        job.schedule_removal()
 60    return True
 61
 62
 63async def set_timer(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
 64    """Add a job to the queue."""
 65    chat_id = update.effective_message.chat_id
 66    try:
 67        # args[0] should contain the time for the timer in seconds
 68        due = float(context.args[0])
 69        if due < 0:
 70            await update.effective_message.reply_text("Sorry we can not go back to future!")
 71            return
 72
 73        job_removed = remove_job_if_exists(str(chat_id), context)
 74        context.job_queue.run_once(alarm, due, chat_id=chat_id, name=str(chat_id), data=due)
 75
 76        text = "Timer successfully set!"
 77        if job_removed:
 78            text += " Old one was removed."
 79        await update.effective_message.reply_text(text)
 80
 81    except (IndexError, ValueError):
 82        await update.effective_message.reply_text("Usage: /set <seconds>")
 83
 84
 85async def unset(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
 86    """Remove the job if the user changed their mind."""
 87    chat_id = update.message.chat_id
 88    job_removed = remove_job_if_exists(str(chat_id), context)
 89    text = "Timer successfully cancelled!" if job_removed else "You have no active timer."
 90    await update.message.reply_text(text)
 91
 92
 93def main() -> None:
 94    """Run bot."""
 95    # Create the Application and pass it your bot's token.
 96    application = Application.builder().token("TOKEN").build()
 97
 98    # on different commands - answer in Telegram
 99    application.add_handler(CommandHandler(["start", "help"], start))
100    application.add_handler(CommandHandler("set", set_timer))
101    application.add_handler(CommandHandler("unset", unset))
102
103    # Run the bot until the user presses Ctrl-C
104    application.run_polling(allowed_updates=Update.ALL_TYPES)
105
106
107if __name__ == "__main__":
108    main()