def job_update_computers_status(bot: Bot, job: Job): user_data = job.context if Session.get_from(user_data).connected: update_computers_status(user_data) else: job.schedule_removal()
def main(): updater = Updater(config['telegtam']['TOKEN']) # Get the dispatcher to register handlers dp = updater.dispatcher job_queue = updater.job_queue # on different commands - answer in Telegram dp.add_handler(CommandHandler("start", start)) dp.add_handler(CommandHandler("help", help)) dp.add_handler(CommandHandler("info", info)) dp.add_handler(CommandHandler('Улица', Out)) dp.add_handler(CommandHandler('Комната', In)) dp.add_handler(CommandHandler('Балкон', Balc)) dp.add_handler(CommandHandler('auth', auth)) dp.add_handler(CommandHandler('Тест', openTestMenu)) dp.add_handler(CommandHandler('Основное_меню', openMainMenu)) dp.add_handler(CommandHandler('Тестовая_информация', testTemp)) # on noncommand i.e message - echo the message on Telegram dp.add_handler(MessageHandler(Filters.text, echo)) # Every 30 minutes job_queue.put(Job(check_temperature, 60 * 30), next_t=60 * 6) # Every 5 minutes job_queue.put(Job(narodmon_send, 60 * 6), next_t=60 * 6) dp.add_error_handler(error) updater.start_polling() updater.idle()
def enter_twitter_login(cls, bot, update): user_id = update.message.from_user.id login = update.message.text user = User.objects.filter(user_id=user_id).first() user.twitter_login = login user.save() logger.info('User {} add twitter login {}'.format( user.username, login)) res = twitter_score_info(login) user.twitter_month_score = res['avg_month_score'] user.twitter_week_score = res['avg_week_score'][-1] user.save() logger.info('Got twitter depression score of user {}: {}'.format( user.username, res)) update.message.reply_text(cls.end_message, reply_markup=ReplyKeyboardRemove()) if not user.activated: logger.info('Run monitorings for user with id=' + str(user_id)) Job(Controller.ask_for_photo, interval=timedelta(0, 40), context={ 'user_id': user_id }).run(bot) Job(Controller.grab_stat, interval=timedelta(1), context={ 'user_id': user_id }).run(bot) user.activated = True user.save() return ConversationHandler.END
def main(): token = init_bot.read_token() updater = Updater(token) global komsostav komsostav = init_bot.read_komsostav() global users users = users_store.restore('users') if users is None: users = {} global last_check_new_posts last_check_new_posts = datetime.now(tz=pytz.timezone('GMT')) for user_id in users: user_info = users[user_id] if user_info.last_forum_post_check < last_check_new_posts: last_check_new_posts = user_info.last_forum_post_check job_queue = updater.job_queue job = Job(check_new_posts_rss, UPDATE_FORUM_POSTS_TIMEOUT_SEC, repeat=True) check_new_posts_rss(updater.bot, job) job_queue.put(job) job_del_posts = Job(del_posts_from_list, DEL_FORUM_POSTS_TIMEOUT_SEC, repeat=True) job_queue.put(job_del_posts) for user_id in users: user_info = users[user_id] if user_info.job_check_posts: add_forum_job(user_info.user.id, job_queue) if user_info.check_meetings: meeting_subscribers.append(user_info.user.id) dp = updater.dispatcher dp.add_handler(CommandHandler("help", bot_help)) dp.add_handler(CommandHandler("start", start)) dp.add_handler(CommandHandler("get_game", get_games, pass_args=True)) dp.add_handler( CommandHandler("start_forum_subscription", start_forum_subscription, pass_job_queue=True)) dp.add_handler( CommandHandler("stop_forum_subscription", stop_forum_subscription)) dp.add_handler( CommandHandler("start_meeting_subscription", start_meeting_subscription)) dp.add_handler( CommandHandler("stop_meeting_subscription", stop_meeting_subscription)) dp.add_handler( CommandHandler("create_meeting", create_meeting, pass_args=True)) dp.add_handler( CommandHandler("change_update_delay", change_forum_delay, pass_args=True)) dp.add_handler(CallbackQueryHandler(callback_query)) updater.start_polling() updater.idle()
def startNotifier(bot, update, job_queue): #Check if user sending the command is allowed if (allowed_users_id.count(update.message.from_user.id) == 1): chat_id = update.message.chat_id #Start the Job to check new streamers jobCheckNewStreams = Job(checkNewStreams, checkTimeSeconds, context=chat_id) job_queue.put(jobCheckNewStreams, next_t=0.0) #Start the Job to check if streamers are still broadcasting jobCheckStreamsOnline = Job(checkStreamsOnline, checkTimeSecondsLive, context=chat_id) job_queue.put(jobCheckStreamsOnline, next_t=checkTimeSecondsLive) #Start the Job to check new videos jobCheckNewVideos = Job(checkNewYoutubeVideos, checkTimeSecondsYoutube, context=chat_id) job_queue.put(jobCheckNewVideos, next_t=0.0) bot.sendMessage( chat_id=update.message.chat_id, text= 'JobQueue started. You will receive notifications when new streamers start playing.' ) else: bot.sendMessage(chat_id=update.message.chat_id, text='You don\'t have permissions to do this.')
def load_jobs(jq): # w: open for writing, truncating the file first # b: binary mode # r: open for reading (default) with FILE.open(mode='rb') as fp: while True: try: # next_t, data, state = pickle.load(fp) next_t = pickle.load(fp) state = pickle.load(fp) data = pickle.load(fp) except EOFError: break # loaded all jobs # New object with the same data job = Job(**{var: val for var, val in zip(JOB_DATA, data)}) # Restore the state it had for var, val in zip(JOB_STATE, state): attribute = getattr(job, var) getattr(attribute, 'set' if val else 'clear')() job.job_queue = jq next_t -= time() # convert from absolute to relative time jq._put(job, next_t)
def add(bot, update, job_queue, args): """ add rss feed to DB.feeds """ chat_id = update.message.chat_id try: feed = str(args[0]) d = Database(chat_id) custom_feed = 0 if len(args) == 2: custom_feed = int(args[1]) # try to add feed add_feed = d.add_feed(feed, custom_feed) if add_feed == 'Invalid rss feed. Please try again': bot.sendMessage(chat_id, text=add_feed) else: # if feed was added then try to subscribe to this feed subscribe = d.subscribe_feed(chat_id, feed, custom_feed) # update feeds job_updater = Job(upd, 1.0, repeat=False, context=update.message.chat_id) job_clear_new_posts = Job(pub, 1.0, repeat=False, context=[update.message.chat_id, feed]) job_queue.put(job_updater) job_queue.put(job_clear_new_posts) bot.sendMessage(chat_id, text=subscribe) except (IndexError, ValueError): bot.sendMessage(chat_id, text='Usage: /add <rss feed string>')
def run(bot, update,args, job_queue, chat_data): global fav_limit chat_id = '@nahaangard' print 'running' # chat_id = update.message.chat_id print len(args) if args: if 2 < len(args): print 'please set your values agains.' pass if len(args) == 1: print 'args' + args try: Timer_set = int(args[0]) if Timer_set < 31: Timer_set = 30 if Timer_set > 3601: Timer_set = 3600 fav_limit = default_fav job = Job(twitel, Timer_set, repeat=True, context=chat_id) chat_data['job'] = job job_queue.put(job) except (IndexError, ValueError): pass if len(args) == 2: print 'args' + ' ' + args[0] + ' ' +args[1] try: Timer_set = int(args[0]) if Timer_set < 31: Timer_set = 30 if Timer_set > 3601: Timer_set = 3600 fav_limit = int(args[1]) if fav_limit < 51: fav_limit = 50 if fav_limit > 2001: fav_limit = 2000 job = Job(twitel, Timer_set, repeat=True, context=chat_id) chat_data['job'] = job job_queue.put(job) except (IndexError, ValueError): pass if not args: print 'no args' try: fav_limit = default_fav job = Job(twitel, default_time, repeat=True, context=chat_id) chat_data['job'] = job job_queue.put(job) except (IndexError, ValueError): pass
def callback_timer(bot, update, job_queue): bot.sendMessage(chat_id=update.message.chat_id, text='updater started!') job_updater = Job(upd, 200.0, repeat=True, context=update.message.chat_id) job_publisher = Job(pub, 150.0, repeat=True, context=[update.message.chat_id]) job_queue.put(job_updater, next_t=0.0) job_queue.put(job_publisher, next_t=0.0)
def garage(self, bot, update): return_message = """""" sender_id = update.message.chat_id # Gives menu to select which garage to open if not self.sender_is_admin(sender_id): self.logger.warning("Unauthorized user", sender_id=sender_id) bot.sendMessage(chat_id=sender_id, text='Not authorized') return ConversationHandler.END options = [] # Stores the keys for the keyboard reply self.logger.info("Got request to open garage.", sender_id=sender_id) garage_statuses = self._get_garage_position() if not garage_statuses: bot.sendMessage( chat_id=sender_id, text='An exception occured while getting garage status', reply_keyboard=None) return ConversationHandler.END # Handle the reponse and creation of the keyboard return_message += "Pick a garage \n" for one_garage_dict in garage_statuses: garage_name = one_garage_dict['garage_name'] current_status = one_garage_dict['status'] return_message += ': '.join([ garage_name, current_status, one_garage_dict['status_time'] ]) + '\n' # Determine whether this can be opened or closed if not one_garage_dict['error']: action = 'CLOSE' if current_status == 'OPEN' else 'OPEN' key_string = ' '.join(['confirm', action, str(garage_name)]) options.append([key_string]) # Store the key for the keyboard options.append(["CANCEL GARAGE"]) # Store the key for the keyboard # Send the message with the keyboard reply_keyboard = ReplyKeyboardMarkup(options, one_time_keyboard=True) bot.sendMessage(chat_id=sender_id, text=return_message, reply_markup=reply_keyboard) # Expires request so that the conversation is not open forever def expire_request(bot, job): bot.sendMessage(chat_id=sender_id, text='Timeout reached. Please start again', reply_keyboard=None) return ConversationHandler.END # Add job to expire request self.garage_expire_request = Job(expire_request, 15.0, repeat=False) self.job_queue.put(self.garage_expire_request) # Set the conversation to go to the next state return GarageConversationState.CONFIRM
def reminder_message(self, bot: Bot, job: Job): event = self.repository.find_by_id(job.context['event_id']) if not event: job.schedule_removal() return bot.sendMessage(job.context['chat_id'], text=EventInline.create_event_message(event), reply_markup=InlineKeyboardMarkup( inline_keyboard=EventInline.create_reply_keyboard(event)), parse_mode=ParseMode.HTML)
def test_disabled(self): j0 = Job(self.job1, 0.1) j1 = Job(self.job1, 0.2) self.jq.put(j0) self.jq.put(Job(self.job1, 0.4)) self.jq.put(j1) j0.enabled = False j1.enabled = False sleep(1) self.assertEqual(2, self.result)
def job_notify_subscriber(bot: Bot, job: Job): chat_id = job.context['chat_id'] city = job.context['city'] subscriber = subscribers[chat_id] try: interesting_ads = list(filter(lambda ad: subscriber.is_interested_in(ad), current_ads[city])) new_ads = subscriber.review_ads(interesting_ads, city) for new_ad in new_ads: bot.sendMessage(chat_id=chat_id, text=new_ad.to_chat_message()) except Unauthorized: logging.warning('unauthorized in job notify. removing job') subscribers.pop(chat_id) job.schedule_removal()
def load_jobs_from_bytes(jq, pickle_buffer: bytes): next_t, data, state = pickle.loads(pickle_buffer) # New object with the same data job = Job(**{var: val for var, val in zip(JOB_DATA, data)}) # Restore the state it had for var, val in zip(JOB_STATE, state): attribute = getattr(job, var) getattr(attribute, 'set' if val else 'clear')() job.job_queue = jq next_t -= time() # convert from absolute to relative time jq._put(job, next_t)
def __init__(self): # Enable logging logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) self.logger = logging.getLogger(__name__) self.__c__ = SQLiter() self.subscribe_job = Job(self._subscription_job_callback, __config__.subscr_time_delta.total_seconds()) # Create the EventHandler and pass it your bot's token. self.updater = Updater(__config__.TG_TOKEN) self.updater.job_queue.put(self.subscribe_job) # Get the dispatcher to register handlers self.dp = self.updater.dispatcher # on different commands - answer in Telegram # self.dp.add_handler(CommandHandler("start", self.start)) # self.dp.add_handler(CommandHandler("help", self.help, pass_args=True)) # self.dp.add_handler(CommandHandler("language_ru", self.subscribe)) self.dp.add_handler(MessageHandler(Filters.text, self._handle_text_message)) # self.dp.add_handler(MessageHandler(Filters.location, self.location)) # log all errors self.dp.add_error_handler(self.error) # Start the Bot self.updater.start_polling() # 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. self.updater.idle()
def _reply(c_id, bot, txt, buttons=None, photo=None, repeat=True): if c_id == 0: return if buttons: custom_keyboard = [ ] for b in buttons: if isinstance(b, list): custom_keyboard.append(b) else: custom_keyboard.append([b]) reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard, one_time_keyboard=True) try: bot.sendMessage(c_id, text=txt, reply_markup=reply_markup, parse_mode=telegram.ParseMode.MARKDOWN) except Exception as e: if not repeat: raise e if '429' in str(e): send_job = Job(reply_job, 1, repeat=False, context=(c_id, bot, txt, buttons, photo)) updater.job_queue.put(send_job) else: raise e elif len(txt) > 0: bot.sendMessage(c_id, text=txt, parse_mode=telegram.ParseMode.MARKDOWN) if photo: bot.sendSticker(c_id, sticker=photo)
def monitor_open_orders(): if config["check_trade"].lower() == "true": # Send request for open orders to Kraken res_data = kraken.query_private("OpenOrders") # If Kraken replied with an error, show it if res_data["error"]: updater.bot.send_message(chat_id=config["user_id"], text=res_data["error"][0]) return # Get time in seconds from config check_trade_time = config["check_trade_time"] if res_data["result"]["open"]: for order in res_data["result"]["open"]: order_txid = str(order) # Create context object with chat ID and order TXID context_data = dict(chat_id=config["user_id"], order_txid=order_txid) # Create job to check status of order job_check_order = Job(monitor_order, check_trade_time, context=context_data) job_queue.put(job_check_order, next_t=0.0)
def find_existing_alerts(job_queue): """Summary reads in any alerts from the existing alerts file deletes the file rewrites any alerts that can still happen back to the file Args: job_queue (TYPE): Description """ try: my_jobs = fileIO.readJobs("alerts") t = datetime.now() if my_jobs != 0: for job in my_jobs: due = int(job.due) - \ int((t - datetime(1970, 1, 1)).total_seconds()) if due > 0: my_context = '' + str(job.chatId) + \ ':' + str(job.messageId) my_job = Job(alarm, due, repeat=False, context=my_context) USERS[my_context] = job.user MESSAGES[my_context] = job.message TIMERS[my_context] = my_job job_queue.put(my_job) fileIO.writeAlertJob("alerts", job.chatId, job.messageId, job.user, job.due, job.message) except: print("Unexpected error:", sys.exc_info())
def start(bot, update, chat_data, job_queue): command = update.message.text checkPasswordList = command.split() if (len(checkPasswordList) < 2): bot.sendMessage(chat_id=update.message.chat_id, text="second argument is password") return ConversationHandler.END if crypt.crypt(checkPasswordList[1], PASSWORDHASH) != PASSWORDHASH: bot.sendMessage(chat_id=update.message.chat_id, text="Wrong password") return ConversationHandler.END bot.sendChatAction(chat_id=update.message.chat_id, action=ChatAction.TYPING) bot.sendMessage(chat_id=update.message.chat_id, text="Admin mode enable") update.message.reply_text("Set Job") job = Job(alarm, 5, context=update.message.chat_id) chat_data['job'] = job job_queue.put(job) keyboard = [[ InlineKeyboardButton(STARTSERVICE), InlineKeyboardButton(STOPSERVICE) ], [InlineKeyboardButton(SHOWSTATUS)], [InlineKeyboardButton(ADMINMODEDISABLE)]] reply_markup = ReplyKeyboardMarkup(keyboard) return EXECUTE
def main(): global mClient, mDatabase mClient = MongoClient(mongoURI) mDatabase = mClient[mDatabase] try: serverInfo = mClient.server_info() logger.info("Mongo Connection Achieved") logger.debug("Connected to Mongo Server: %s" % serverInfo) except: logger.error("Could not connect to Mongo Server at %s" % mongoURI) raise updater = Updater(authToken) dp = updater.dispatcher dp.add_handler(CommandHandler('motd', MOTD)) dp.add_handler(CommandHandler('set_motd', setMOTD)) dp.add_handler(CommandHandler('register_me', registerMe)) dp.add_handler(CallbackQueryHandler(callbackHandler, pattern='RegisterMe')) calendar = calendarEventHandler(mDatabase.groups, updater.job_queue, dp) #polls = pollEventHandler(mDatabase.groups, mDatabase.pollData) #dp.add_handler(polls.pollCreateHandler) dp.add_handler(CallbackQueryHandler(empty_callback, pattern=' ')) updateAdmins = Job(updateChatList, 60 * 5) updater.job_queue.put(updateAdmins, next_t=0) updater.start_polling() updater.idle()
def main(): try: serverInfo = MCLIENT.server_info() logger.info("Connected to Mongo Server: %s." % serverInfo) except: logger.error("Could not connect to the Mongo Server.") raise updater = Updater(AUTHTOKEN) dp = updater.dispatcher dp.add_handler(CommandHandler('start', start, pass_user_data=True)) dp.add_handler(CommandHandler('cancel', start, pass_user_data=True)) dp.add_handler(CommandHandler('resolve', resolve, pass_user_data=True)) dp.add_handler( CommandHandler('help', help, pass_user_data=True, pass_chat_data=True)) dp.add_handler(CommandHandler('info', info)) dp.add_handler( CallbackQueryHandler(callbackResponseHandler, pass_user_data=True)) dp.add_handler(MessageHandler(Filters.status_update, statusReceived)) dp.add_handler( MessageHandler(Filters.all, messageReceived, pass_user_data=True)) dp.add_error_handler(error) updater.start_polling() updateAdmins = Job(updateChatList, 60 * 15) updater.job_queue.put(updateAdmins, next_t=0) updater.idle()
def push_message(self, args): if 'chat_id' not in args: self.send_response(400) self.send_header("Content-type", "text") self.end_headers() self.wfile.write(bytes("'chat_id' not provided in arguments.", 'utf-8')) return if 'message' not in args: self.send_response(400) self.send_header("Content-type", "text") self.end_headers() self.wfile.write(bytes("'message' not provided in arguments.", 'utf-8')) return try: chat_id = self._get_arg(args['chat_id']) # 333551684 message = self._get_arg(args['message']) delay = 0 if 'delay' in args: delay = int(self._get_arg(args['delay'])) job = Job(self._alarm, delay, repeat=False, context=(chat_id, message)) self.job_queue.put(job) self.send_response(200) self.send_header("Content-type", "text") self.end_headers() self.wfile.write(bytes("OK.", 'utf-8')) except Exception as e: self.logger.error('[%s] %s' % (chat_id, repr(e))) self.send_response(500) self.send_header("Content-type", "text") self.end_headers() self.wfile.write(bytes("500 Internal server error.", 'utf-8'))
def __init__(self, mCollection, job_queue, dp): ''' mCollection : The mongo collection that we will be adding events too. ''' self.mCollection = mCollection self.logger = logging.getLogger(__name__) self.EVENT_SELECT, self.EVENT_TYPING = range(100, 102) self.reply_keyboard = [['Name', 'Time', 'Date'], ['Group', 'Place', 'Description']] self.usedKeys = [ 'Name', 'Time', 'Date', 'Description', 'Place', 'Group' ] self.conversationHandler = ConversationHandler( entry_points=[ CommandHandler('create_event', self.eventStartEditing, pass_user_data=True) ], states={ self.EVENT_SELECT: [ RegexHandler('^(Name|Time|Date|Description|Place|Group)$', self.eventPromptTyping, pass_user_data=True), RegexHandler('^Done$', self.eventCreate, pass_user_data=True), RegexHandler('^Cancel$', self.eventCancel, pass_user_data=True) ], self.EVENT_TYPING: [ MessageHandler(Filters.text, self.eventSelectEditing, pass_user_data=True), CallbackQueryHandler(self.dateHandler, pass_user_data=True, pattern='^cal-.*'), CallbackQueryHandler(self.clockHandler, pass_user_data=True, pattern='^clk-.*') ] }, fallbacks=[ MessageHandler(Filters.text, self.editPreviousMessage, edited_updates=True, pass_user_data=True) ], allow_reentry=True) purgeOld = Job(self.removeOldEvents, 60 * 60 * 24) job_queue.put(purgeOld, next_t=0) dp.add_handler(CommandHandler('list_events', self.getEventList)) dp.add_handler(self.conversationHandler)
def init(*, bot: Bot, job_queue: JobQueue, callback: callable): _load_all() _configure_logging(bot) for chat in auto_spins: job = Job(callback, 86400.0, context=auto_spins[chat]) job_queue.put(job, next_t=time_diff(auto_spins[chat])) auto_spin_jobs.update({chat: job})
def enable_h(bot, update, job_queue, chat_data): chat_id = update.message.chat.id fromemail, mailinglist, enabled = db.getaddresses(chat_id) if not fromemail: bot.sendMessage(chat_id=update.message.chat_id, text="Can not enable the bot, missing 'From' email") return if not mailinglist: bot.sendMessage(chat_id=update.message.chat_id, text="Can not enable the bot, missing 'mailinglist'" " email") return if not enabled: if db.enable(chat_id): bot.sendMessage(chat_id=update.message.chat_id, text="Ok, will send digest once every %s minutes" " to %s from %s" % (str(sendinterval), mailinglist, fromemail)) job = Job(senddigest, sendinterval * 60, repeat=True) chat_data['job'] = job job_queue.put(job) else: bot.sendMessage(chat_id=update.message.chat_id, text="Group already enabled")
def addJob(bot, update, job_queue): chat_id = update.message.chat_id logger.info('[%s] Adding job.' % (chat_id)) try: if chat_id not in jobs: job = Job(alarm, 30, repeat=True, context=(chat_id, "Other")) # Add to jobs jobs[chat_id] = job job_queue.put(job) # User dependant - Save/Load if chat_id not in search_ids: search_ids[chat_id] = [] if chat_id not in language: language[chat_id] = config.get('DEFAULT_LANG', None) # User dependant if chat_id not in sent: sent[chat_id] = dict() if chat_id not in locks: locks[chat_id] = threading.Lock() text = "Scanner started." bot.sendMessage(chat_id, text) except Exception as e: logger.error('[%s] %s' % (chat_id, repr(e)))
def main(): if os.path.isfile(question_filename): with open(question_filename, 'r') as f: question_yes, question_no = map(int, f.readline().split()) asked = f.readline().split() if not os.path.isdir(config.USERS_PATH): logger.info('Creating users directory') os.makedirs(config.USERS_PATH) logger.info('Creating Updater...') updater.dispatcher.add_handler(CommandHandler('leaderboard', leaderboard)) updater.dispatcher.add_handler(CommandHandler('setname', setname)) updater.dispatcher.add_handler(CommandHandler('notify', notify)) updater.dispatcher.add_handler(CommandHandler('debug', debug_print)) updater.dispatcher.add_handler(CommandHandler('cesar', cesar)) updater.dispatcher.add_handler(CommandHandler('start', start)) updater.dispatcher.add_handler(CommandHandler('bot', bot)) updater.dispatcher.add_handler(CommandHandler('rate', rate)) updater.dispatcher.add_handler(CommandHandler('stop', stop)) updater.dispatcher.add_handler(CommandHandler('room', room)) updater.dispatcher.add_handler(CommandHandler('give', give)) updater.dispatcher.add_handler(CommandHandler('gold', gold)) updater.dispatcher.add_handler(CommandHandler('pet', pet)) updater.dispatcher.add_handler(CommandHandler('question_status', question_status)) updater.dispatcher.add_handler(CommandHandler('zero', zero)) updater.dispatcher.add_handler(CommandHandler('yes', yes)) updater.dispatcher.add_handler(CommandHandler('no', no)) updater.dispatcher.add_handler(MessageHandler(False, msg)) updater.dispatcher.add_error_handler(error_callback) intervention_job = Job(divine_intervention, 3 * 60 * 60.0) update_tornament_job = Job(update_tornament, 10.0) updater.job_queue.put(intervention_job) updater.job_queue.put(update_tornament_job) queue_job = Job(queue_reply, 0.035) updater.job_queue.put(queue_job) logger.info('Starting polling...') updater.start_polling() logger.info('Bot now officially started!') updater.idle()
def test_schedule_removal(self): j0 = Job(self.job1, 0.1) j1 = Job(self.job1, 0.2) self.jq.put(j0) self.jq.put(Job(self.job1, 0.4)) self.jq.put(j1) j0.schedule_removal() j1.schedule_removal() sleep(1) self.assertEqual(2, self.result)
def add_forum_job(user_id, job_queue): user_info = users[user_id] job = Job(check_new_posts_from_list, user_info.job_posts_timeout, repeat=True, context=user_id) forum_subscribers[user_id] = job job_queue.put(job)
def test_jobs_tuple(self): self.jq.stop() jobs = tuple(Job(self.job1, t) for t in range(5, 25)) for job in jobs: self.jq.put(job) self.assertTupleEqual(jobs, self.jq.jobs())
def stay(bot, update, job_queue, chat_data): global is_listening is_listening = True update.message.reply_text('Listening is on now') job = Job(stay_socket, 0, context=update.message.chat_id) chat_data['job'] = job job_queue.put(job, next_t=0.0) update.message.reply_text('OK')
def test_warnings(self, job_queue): j = Job(self.job_run_once, repeat=False) with pytest.raises(ValueError, match='can not be set to'): j.repeat = True j.interval = 15 assert j.interval_seconds == 15 j.repeat = True with pytest.raises(ValueError, match='can not be'): j.interval = None j.repeat = False with pytest.raises(ValueError, match='must be of type'): j.interval = 'every 3 minutes' j.interval = 15 assert j.interval_seconds == 15 with pytest.raises(ValueError, match='argument should be of type'): j.days = 'every day' with pytest.raises(ValueError, match='The elements of the'): j.days = ('mon', 'wed') with pytest.raises(ValueError, match='from 0 up to and'): j.days = (0, 6, 12, 14)