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