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 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
Exemplo n.º 3
0
    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'))
Exemplo n.º 4
0
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()
Exemplo n.º 5
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 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)
Exemplo n.º 7
0
    def test_time_unit_int(self):
        # Testing seconds in int
        seconds_interval = 5
        expected_time = self.getSeconds() + seconds_interval

        self.jq.put(Job(self.job5, seconds_interval, repeat=False))
        sleep(6)
        self.assertEqual(self.job_time, expected_time)
Exemplo n.º 8
0
def button(bot, update, job_queue, chat_data):
    '''Button response'''
    query = update.callback_query
    data = query.data
    data_type = data["type"]
    if data_type == "snooze_1":
        snooze = data["snooze"]
        if snooze:
            keyboard = [[
                InlineKeyboardButton("5 minutes",
                                     callback_data={
                                         "type": "snooze_2",
                                         "job": data['job'],
                                         'length': 300
                                     }),
                InlineKeyboardButton("15 minutes",
                                     callback_data={
                                         "type": "snooze_2",
                                         "job": data['job'],
                                         'length': 900
                                     }),
                InlineKeyboardButton("1 hour",
                                     callback_data={
                                         "type": "snooze_2",
                                         "job": data['job'],
                                         'length': 3600
                                     }),
                InlineKeyboardButton("6 hours",
                                     callback_data={
                                         "type": "snooze_2",
                                         "job": data['job'],
                                         'length': 21600
                                     }),
                InlineKeyboardButton("1 day",
                                     callback_data={
                                         "type": "snooze_2",
                                         "job": data['job'],
                                         'length': 86400
                                     })
            ]]
            snooze_inline = InlineKeyboardMarkup(keyboard)
            bot.sendMessage(update.messagechat_id,
                            text="How long would you like to snooze?",
                            reply_markup=snooze_inline)
        else:
            update.message.reply_text("Dismissed.")
    elif data_type == "snooze_2":
        due = data["length"]
        job = Job(alarm, due, repeat=False, context=chat_data)
        chat_data["job"] = job
        job_queue.put(job)
        update.message.reply_text("Snoozed")
    elif data_type == "plugin_selection":
        event_data = data['event']
        plugin_function = data["function"]
        log.info("Calling plugin {0}".format(data["plugin_name"]))
        #Call the plugin
        plugin_handler.subscriptions().call_plugin(plugin_function, event_data)