timerbot.pyΒΆ

  1#!/usr/bin/env python
  2# pylint: disable=unused-argument, wrong-import-position
  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"""
 20
 21import logging
 22
 23from telegram import __version__ as TG_VER
 24
 25try:
 26    from telegram import __version_info__
 27except ImportError:
 28    __version_info__ = (0, 0, 0, 0, 0)  # type: ignore[assignment]
 29
 30if __version_info__ < (20, 0, 0, "alpha", 1):
 31    raise RuntimeError(
 32        f"This example is not compatible with your current PTB version {TG_VER}. To view the "
 33        f"{TG_VER} version of this example, "
 34        f"visit https://docs.python-telegram-bot.org/en/v{TG_VER}/examples.html"
 35    )
 36from telegram import Update
 37from telegram.ext import Application, CommandHandler, ContextTypes
 38
 39# Enable logging
 40logging.basicConfig(
 41    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
 42)
 43
 44
 45# Define a few command handlers. These usually take the two arguments update and
 46# context.
 47# Best practice would be to replace context with an underscore,
 48# since context is an unused local variable.
 49# This being an example and not having context present confusing beginners,
 50# we decided to have it present as context.
 51async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
 52    """Sends explanation on how to use the bot."""
 53    await update.message.reply_text("Hi! Use /set <seconds> to set a timer")
 54
 55
 56async def alarm(context: ContextTypes.DEFAULT_TYPE) -> None:
 57    """Send the alarm message."""
 58    job = context.job
 59    await context.bot.send_message(job.chat_id, text=f"Beep! {job.data} seconds are over!")
 60
 61
 62def remove_job_if_exists(name: str, context: ContextTypes.DEFAULT_TYPE) -> bool:
 63    """Remove job with given name. Returns whether job was removed."""
 64    current_jobs = context.job_queue.get_jobs_by_name(name)
 65    if not current_jobs:
 66        return False
 67    for job in current_jobs:
 68        job.schedule_removal()
 69    return True
 70
 71
 72async def set_timer(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
 73    """Add a job to the queue."""
 74    chat_id = update.effective_message.chat_id
 75    try:
 76        # args[0] should contain the time for the timer in seconds
 77        due = float(context.args[0])
 78        if due < 0:
 79            await update.effective_message.reply_text("Sorry we can not go back to future!")
 80            return
 81
 82        job_removed = remove_job_if_exists(str(chat_id), context)
 83        context.job_queue.run_once(alarm, due, chat_id=chat_id, name=str(chat_id), data=due)
 84
 85        text = "Timer successfully set!"
 86        if job_removed:
 87            text += " Old one was removed."
 88        await update.effective_message.reply_text(text)
 89
 90    except (IndexError, ValueError):
 91        await update.effective_message.reply_text("Usage: /set <seconds>")
 92
 93
 94async def unset(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
 95    """Remove the job if the user changed their mind."""
 96    chat_id = update.message.chat_id
 97    job_removed = remove_job_if_exists(str(chat_id), context)
 98    text = "Timer successfully cancelled!" if job_removed else "You have no active timer."
 99    await update.message.reply_text(text)
100
101
102def main() -> None:
103    """Run bot."""
104    # Create the Application and pass it your bot's token.
105    application = Application.builder().token("TOKEN").build()
106
107    # on different commands - answer in Telegram
108    application.add_handler(CommandHandler(["start", "help"], start))
109    application.add_handler(CommandHandler("set", set_timer))
110    application.add_handler(CommandHandler("unset", unset))
111
112    # Run the bot until the user presses Ctrl-C
113    application.run_polling()
114
115
116if __name__ == "__main__":
117    main()