1717bot.
1818"""
1919
20- from telegram .ext import Updater , CommandHandler
20+ from telegram .ext import Updater , CommandHandler , Job
2121import logging
2222
2323# Enable logging
2424logging .basicConfig (format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' ,
25- level = logging .INFO )
25+ level = logging .DEBUG )
2626
2727logger = logging .getLogger (__name__ )
28- job_queue = None
28+ timers = dict ()
2929
3030
3131# Define a few command handlers. These usually take the two arguments bot and
@@ -34,46 +34,58 @@ def start(bot, update):
3434 bot .sendMessage (update .message .chat_id , text = 'Hi! Use /set <seconds> to ' 'set a timer' )
3535
3636
37- def set (bot , update , args ):
38- """ Adds a job to the queue """
37+ def set (bot , update , args , job_queue ):
38+ """Adds a job to the queue"""
3939 chat_id = update .message .chat_id
4040 try :
4141 # args[0] should contain the time for the timer in seconds
4242 due = int (args [0 ])
4343 if due < 0 :
4444 bot .sendMessage (chat_id , text = 'Sorry we can not go back to future!' )
4545
46- def alarm (bot ):
47- """ Inner function to send the alarm message """
46+ def alarm (bot , job ):
47+ """Inner function to send the alarm message"""
4848 bot .sendMessage (chat_id , text = 'Beep!' )
4949
5050 # Add job to queue
51- job_queue .put (alarm , due , repeat = False )
51+ job = Job (alarm , due , repeat = False )
52+ timers [chat_id ] = job
53+ job_queue .put (job )
54+
5255 bot .sendMessage (chat_id , text = 'Timer successfully set!' )
5356
54- except IndexError :
55- bot .sendMessage (chat_id , text = 'Usage: /set <seconds>' )
56- except ValueError :
57+ except (IndexError , ValueError ):
5758 bot .sendMessage (chat_id , text = 'Usage: /set <seconds>' )
5859
5960
61+ def unset (bot , update ):
62+ """Removes the job if the user changed their mind"""
63+ chat_id = update .message .chat_id
64+
65+ if chat_id not in timers :
66+ bot .sendMessage (chat_id , text = 'You have no active timer' )
67+ return
68+
69+ job = timers [chat_id ]
70+ job .schedule_removal ()
71+ bot .sendMessage (chat_id , text = 'Timer successfully unset!' )
72+
73+
6074def error (bot , update , error ):
6175 logger .warn ('Update "%s" caused error "%s"' % (update , error ))
6276
6377
6478def main ():
65- global job_queue
66-
6779 updater = Updater ("TOKEN" )
68- job_queue = updater .job_queue
6980
7081 # Get the dispatcher to register handlers
7182 dp = updater .dispatcher
7283
7384 # on different commands - answer in Telegram
7485 dp .add_handler (CommandHandler ("start" , start ))
7586 dp .add_handler (CommandHandler ("help" , start ))
76- dp .add_handler (CommandHandler ("set" , set , pass_args = True ))
87+ dp .add_handler (CommandHandler ("set" , set , pass_args = True , pass_job_queue = True ))
88+ dp .add_handler (CommandHandler ("unset" , unset ))
7789
7890 # log all errors
7991 dp .add_error_handler (error )
0 commit comments