我们从Python开源项目中,提取了以下18个代码示例,用于说明如何使用telegram.ext.Job()。
def monitor_train(bot, job): """ Job to Send Train Message """ msg = train_alert.get_new_breakdowns_message() if msg is None: print('No new breakdowns') else: all_users = train_alert.get_all_users() to_send = chunks(all_users, 10) for group in to_send: for user in group: try: bot.sendMessage(int(user), text=emojize(msg, use_aliases=True), parse_mode='HTML') except: print("Error! Sending Message to " + str(user)) sleep(1.2)
def main(config): updater = Updater(config['token']) j = updater.job_queue def newAlert(bot, job): '''Polls the GitHub API every 2.5 minutes for new notifications.''' output = notifications(config) if output: bot.sendMessage(chat_id=config['chat_id'], text=output, parse_mode='markdown', \ disable_web_page_preview=True) job_minute = Job(newAlert, 150.0) #Time in seconds j.put(job_minute, next_t=0.0) updater.start_polling() updater.idle()
def monitor_promo(bot, job): """ Job to Send Promo Message """ msg = promo_alert.get_new_codes_message() if msg is None: print('No new promos') else: text_bot = ['Uber poked me privately and said this :wink:', 'I found this promo code while I was in my ActiveWear! :stuck_out_tongue:', 'Quick apply the code! Later run out dont cry :sunglasses:', 'Breaking News Brought to you by ShiokBot!', ] all_users = promo_alert.get_all_users() to_send = chunks(all_users, 10) for group in to_send: for user in group: try: bot.sendMessage(int(user), text=emojize(random.choice(text_bot), use_aliases=True), parse_mode='HTML') bot.sendMessage(int(user), text=msg, parse_mode='HTML') except: print("Error! Sending Message to " + str(user)) sleep(1.2)
def run_repeating(self, callback, interval, first=None, *args, **kwargs): job: Job = self.job_queue.run_repeating(callback=lambda bot, _job: callback(*args, **kwargs), first=first, interval=interval) self.jobs.append(job)
def run_once(self, callback, when, *args, **kwargs): job: Job = self.job_queue.run_once(callback=lambda bot, _job: callback(*args, **kwargs), when=when) self.jobs.append(job)
def automatic_message(bot, update, delay): delayed_message = Job(bot.sendMessage(update.message.chat_id, text=choice(automatic_phrases)), delay, repeat=False) job_queue.put(delayed_message, next_t=delay)
def test(bot, update): j.put(Job(broadcast_callback, 1.0)) bot.sendMessage(chat_id=update.message.chat_id, text="Started a job")
def change_setting(bot, update, setting, data, job_queue): user = get_user(bot, update) iden = id_from_update(update) if data not in settings[setting]['trans']: update.callback_query.answer(_('Unknown setting, try again.')) return setting try: old = settings[setting]['trans'][user[setting]] except KeyError: old = _('Corrupted data...') db.update({setting: data}, User.id == iden) new = settings[setting]['trans'][data] msg_type = _('User') if update.callback_query.message.chat.type == 'private' else _('Chat') text = _("<i>{type}</i>  {nice_name} changed from <code>{old}</code> to " "<code>{new}</code>. Please wait up to 5 minutes for all changes to take effect.") text = text.format(type=msg_type, nice_name=settings[setting]['nice_name'], old=old, new=new) message = bot.edit_message_text(chat_id=update.callback_query.message.chat.id, message_id=update.callback_query.message.message_id, text=text, parse_mode=ParseMode.HTML) def callback(b, j): update.message = update.callback_query.message update.message.chat, update.message.from_user = update.message.from_user, update.message.chat start(bot, update, edit=True, chat_id=message.chat_id, message_id=message.message_id) job = Job(callback=callback, interval=5, repeat=False) job_queue.put(job)
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 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 run(self): """ :return: None """ self.__updater = Updater(token=self.__config['KEYS']['bot_api']) self.__dispatcher = self.__updater.dispatcher executeHandler = MessageHandler([Filters.text], self.executer) self.__dispatcher.add_handler(executeHandler) self.__dispatcher.add_handler(InlineQueryHandler(self.getInlineQuery)) self.__dispatcher.add_error_handler(self.error) # Define Job Queue self.__job_queue = self.__updater.job_queue for key, hook in self.__hooks.items(): self.__job_queue.put(Job(hook.get('hook').job, hook.get('timer'), True), next_t=0.0) # Start the Motux Bot self.__updater.start_polling(poll_interval=0.1, timeout=10, network_delay=5, clean=False) # Run the Motux Bot until the you presses Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT. This should be used most of the time, since self.__updater.idle()
def set(bot, update, args, job_queue): """Adds a job to the queue""" chat_id = update.message.chat_id try: # args[0] should contain the time for the timer in seconds due = int(args[0]) if due < 0: bot.sendMessage(chat_id, text='Sorry we can not go back to future!') return # Add job to queue job = Job(alarm, due, repeat=False, context=chat_id) timers[chat_id] = job job_queue.put(job) bot.sendMessage(chat_id, text='Timer successfully set!') except (IndexError, ValueError): bot.sendMessage(chat_id, text='Usage: /set <seconds>')
def set(bot, update, args, job_queue): """Adds a job to the queue""" chat_id = update.message.chat_id try: # args[0] should contain the time for the timer in seconds due = int(args[0]) if due < 0: bot.sendMessage(chat_id, text='?? ???? ??? ?? ????? ?????? ? ???????!') return if due > 3600 * 24 * 31: bot.sendMessage(chat_id, text='??????? ??????? ?????!') return # Add job to queue job = Job(alarm, due, repeat=False, context=chat_id) timers[chat_id] = job job_queue.put(job) bot.sendMessage(chat_id, text='?????? ??????????!') except (IndexError, ValueError): bot.sendMessage(chat_id, text='????????? ??????: /set <seconds>')
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 start_vote_session(bot: Bot, update: Update, job_queue): """ Handles /new_vote command :param bot: :param update: :param job_queue: :return: """ chat_id = update.message.chat_id job = Job(start_vote, 0, repeat=False, context=(chat_id, job_queue)) job_queue.put(job)
def do_login(bot: Bot, chat_id: str, sender: str, token: str, job_queue: JobQueue): from bot_app.model import Conversation global data try: # Notify this is going to take some time # In groups if data.change_account_queries[sender] != sender: bot.sendChatAction(chat_id=chat_id, action=ChatAction.TYPING) # In private chat bot.sendChatAction(chat_id=chat_id, action=ChatAction.TYPING) # Create Tinder session session = Session(token) if session.do_connect(): message = "Switching to %s's account." % session.get_profile_name() messages.send_custom_message(bot=bot, message=message, chat_id=data.change_account_queries[sender]) if sender != data.change_account_queries[sender]: # group_name = bot.getChat(chat_id=data.change_account_queries[sender]).title bot.sendMessage(chat_id=sender, text=message, reply_markup=keyboards.switch_group_keyboard()) # Create conversation conversation = Conversation(data.change_account_queries[sender], session, sender) data.conversations[data.change_account_queries[sender]] = conversation del data.change_account_queries[sender] # Launch get matches background job cache_time = int(conversation.settings.get_setting("matches_cache_time")) job = Job(job_refresh_matches, cache_time + 1, repeat=True, context=conversation) job_queue.put(job, next_t=0.0) else: messages.send_error(bot=bot, chat_id=chat_id, name="auth_failed") except BaseException: messages.send_error(bot=bot, chat_id=chat_id, name="auth_failed")
def force_promo_check(bot, update): """ Job to Send Message """ msg = promo_alert.get_new_codes_message() if msg is None: bot.sendMessage(22959774, text="No new Promos", parse_mode='HTML') else: bot.sendMessage(22959774, text=msg, parse_mode='HTML') bot.sendMessage(22959774, text='Forced Promo Check!', parse_mode='HTML')
def alarm_vote(bot: Bot, chat_id: str, job_queue): """ Handles the end of a voting session :param bot: :param chat_id: :param job_queue: :return: """ global data conversation = data.conversations[chat_id] wait_for_vote_timeout(conversation) # Update the message to show that vote is ended msg = conversation.result_msg likes, dislikes = conversation.get_stats() message = "%d likes, %d dislikes " % (likes, dislikes) current_vote = len(conversation.get_votes()) max_vote = conversation.settings.get_setting("min_votes_before_timeout") caption = get_caption_match(conversation.current_user, current_vote, max_vote, bio=False) try: # todo wrap this up bot.editMessageCaption(chat_id=msg.chat_id, message_id=msg.message_id, caption=caption + "\n%s" % message, reply_markup=keyboards.get_vote_finished_keyboard(user=conversation.current_user, conversation=conversation)) except BaseException: traceback.print_exc() conversation.set_is_voting(False) conversation.is_alarm_set = False try: if likes > dislikes: # todo wrap this up conversation.current_user.like() else: # todo wrap this up conversation.current_user.dislike() except pynder.errors.RequestError as e: if session.is_timeout_error(e): session.do_reconnect(bot=bot, chat_id=chat_id, conversation=conversation) send_error(bot=bot, chat_id=chat_id, name="failed_to_vote") else: send_error(bot=bot, chat_id=chat_id, name="failed_to_vote") except BaseException: send_error(bot=bot, chat_id=chat_id, name="failed_to_vote") # Store vote for future prediction processing if conversation.settings.get_setting("store_votes"): data_retrieval.do_store_vote(user_id=conversation.current_user.id, chat_id=chat_id, is_like=likes > dislikes) # If the bot is set to auto -> launch another vote if conversation.auto: job = Job(start_vote, 0, repeat=False, context=(chat_id, job_queue)) job_queue.put(job)