Example #1
0
    def pollon(self, irc, msg, args, channel, pollid, interval):
        """<[channel]> <id> <interval in minutes>
        Schedules announcement of poll with the given <id> every <interval>.
        <channel> is only necessary if the message is not sent in the channel
        itself."""

        db = self.getDb(channel)
        cursor = db.cursor()

        # query to check poll exists, and if it is already on
        pollinfo = self._poll_info(db, pollid)
        if pollinfo is None:
            irc.error('That poll id does not exist')
            return
        if pollinfo[0] == 1:
            irc.error('Poll is already active')
            return

        # query to set poll off
        db.execute('UPDATE polls SET isAnnouncing=? WHERE id=?', (1, pollid))
        db.commit()

        if pollinfo[1] is not None:
            irc.reply('Note: you are turning on closed poll. I will not start announcing it')
            return

        # function called by schedule event. can not have args
        def runPoll():
            self._runPoll(irc, channel, pollid)

        # start schedule. will announce poll/choices to channel at interval
        schedule.addPeriodicEvent(runPoll, interval*60, name='%s_poll_%s' % (channel, pollid))
        self.poll_schedules.append('%s_poll_%s' % (channel, pollid))
Example #2
0
    def openpoll(self, irc, msg, args, channel, pollid, interval):
        """[<channel>] <id>
        Starts announcing poll with the given <id> if set to active.
        <channel> is only necessary if the message isn't sent in the channel
        itself."""

        db = self.getDb(channel)
        cursor = db.cursor()

        # query to check poll exists and if it is open
        pollinfo = self._poll_info(db, pollid)
        if pollinfo is None:
            irc.error('Poll id doesnt exist')
            return
        if pollinfo[1] is None:
            irc.error('Poll is still open')
            return

        # query to OPEN IT UP! unsets closed time
        self._execute_query(cursor, 'UPDATE polls SET closed=? WHERE id=?', None, pollid)
        db.commit()

        # if poll was set active then start schedule for it
        if pollinfo[0] == 1:
            if interval is None:
                irc.reply('Note: Poll set to active, but you didnt supply interval, using default of 10 minutes')
                interval = 10
            # function called by schedule event. can not have args
            def runPoll():
                self._runPoll(irc, channel, pollid)

            # start schedule. will announce poll/choices to channel at interval
            schedule.addPeriodicEvent(runPoll, interval*60, name='%s_poll_%s' % (channel, pollid))
            self.poll_schedules.append('%s_poll_%s' % (channel, pollid))
Example #3
0
    def __init__(self, irc):
        self.__parent = super(Mantis, self)
        self.__parent.__init__(irc)

        self.saidBugs = ircutils.IrcDict()
        sayTimeout = self.registryValue('bugSnarferTimeout')
        for k in irc.state.channels.keys():
            self.saidBugs[k] = TimeoutQueue(sayTimeout)

        self.urlbase = self.registryValue('urlbase')
        self.privateurlbase = self.registryValue('privateurlbase')

        if self.privateurlbase != "":
            serviceUrl = self.privateurlbase + '/api/soap/mantisconnect.php'
        else:
            serviceUrl = self.urlbase + '/api/soap/mantisconnect.php'

        self.server = SOAPProxy(serviceUrl)._ns(namespace)
        self.username = self.registryValue('username')
        self.password = self.registryValue('password')
        self.oldperiodic = self.registryValue('bugPeriodicCheck')
        self.irc = irc
        self.lastBug = 0

        bugPeriodicCheck = self.oldperiodic
        if bugPeriodicCheck > 0:
            schedule.addPeriodicEvent(self._bugPeriodicCheck, bugPeriodicCheck, name=self.name())

        reload(sys)
        sys.setdefaultencoding('utf-8')
Example #4
0
    def __init__(self, irc):
        self.__parent = super(DeedSystem, self)
        self.__parent.__init__(irc)
        
        # load deeds config
        config_path = self.registryValue('configPath')
	with open(config_path,'r') as f:
		deeds_config = json.loads(f.read())

        # prompt for password
        pwd = getpass('Enter wallet password:'******'wallet_pass'] = pwd

        # start the bundler
        self.deeds = Bundler(deeds_config)
        self.deeds.setup()

        # schedule events
        def make_bundle():
            self._make_bundle(irc)

        def confirm_bundle():
            self._confirm_bundle(irc)

        schedule.addPeriodicEvent(make_bundle, deeds_config['make_bundle_interval'], now=False, name='make_bundle')
        schedule.addPeriodicEvent(confirm_bundle, deeds_config['confirm_bundle_interval'], now=False, name='confirm_bundle')
Example #5
0
    def __init__(self, irc):
        self.__parent = super(Twitter, self)
        self.__parent.__init__(irc)
        self.irc = irc
        self.mentionSince = None
        try:
            schedule.removeEvent("Mentions")
        except KeyError:
            pass
        t_consumer_key = self.registryValue("consumer_key")
        t_consumer_secret = self.registryValue("consumer_secret")
        t_access_key = self.registryValue("access_key")
        t_access_secret = self.registryValue("access_secret")
        self.api = twitter.Api(
            consumer_key=t_consumer_key,
            consumer_secret=t_consumer_secret,
            access_token_key=t_access_key,
            access_token_secret=t_access_secret,
        )
        if self.registryValue("displayReplies"):
            statuses = self.api.GetMentions()
            self.mentionSince = statuses[0].id

            def mentionCaller():
                self._mention(irc)

            schedule.addPeriodicEvent(mentionCaller, 300, "Mentions")
Example #6
0
    def __init__(self, irc):
        self.__parent = super(SubredditAnnouncer, self)
        self.__parent.__init__(irc)
        self.savefile = conf.supybot.directories.data.dirize(
            "subredditAnnouncer.db")
        self.headers = {"User-Agent": "SubredditAnnouncer ([email protected])"}

        def checkForPosts():
            self.checkReddit(irc)

        try:
            schedule.addPeriodicEvent(checkForPosts,
                                      self.registryValue('checkinterval') * 60,
                                      'redditCheck', False)
        except AssertionError:
            schedule.removeEvent('redditCheck')
            schedule.addPeriodicEvent(checkForPosts,
                                      self.registryValue('checkinterval') * 60,
                                      'redditCheck', False)
        try:
            if self.registryValue('dsn') != "":
                if "raven" in dir():  # Check that raven was actually imported
                    self.raven = raven.Client(self.registryValue("dsn"))
                else:
                    self.log.error(
                        "dsn defined but raven not installed! Please pip install raven"
                    )
        except NonExistentRegistryEntry:
            pass
Example #7
0
    def __init__(self, irc):
        super().__init__(irc)

        # We have the flush disabled in the configuration, but this also stops
        # flushing of database-files. So every 2 minutes we still flush, which
        # ironically doesn't flush everything, but only the database-files.
        schedule.addPeriodicEvent(world.flush, 120, name="flush", now=False)
Example #8
0
    def __init__(self, irc):
        self.__parent = super(Bantracker, self)
        self.__parent.__init__(irc)
        self.default_irc = irc
        self.lastMsgs = {}
        self.lastStates = {}
        self.replies = {}
        self.logs = ircutils.IrcDict()
        self.nicks = {}
        self.hosts = {}
        self.bans = ircutils.IrcDict()

        self.thread_timer = threading.Timer(10.0, dequeue, args=(self,irc))
        self.thread_timer.start()

        db = self.registryValue('database')
        if db:
            self.db = sqlite3.connect(db)
        else:
            self.db = None
        self.get_bans(irc)
        self.get_nicks(irc)
        self.pendingReviews = PersistentCache('bt.reviews.db')
        self.pendingReviews.open()
        self._banreviewfix()
        # add scheduled event for check bans that need review, check every hour
        try:
            schedule.removeEvent(self.name())
        except:
            pass
        schedule.addPeriodicEvent(lambda : self.reviewBans(irc), 60*60,
                name=self.name())
Example #9
0
    def search(self, irc, msg, arg, search):
        """<terms>

        Start streaming a Twitter search."""
        name = 'twitterstream_search_' + search
        api = twitter.Api()

        def fetch(send=True):
            url = 'http://search.twitter.com/search.json?q=%s&since_id=%i' % \
                    (search, self._searches[name])
            timeline = requests.get(url).json['results']
            for tweet in timeline:
                self._searches[name] = max(self._searches[name], tweet['id'])
            format_ = '@%(user)s> %(msg)s'
            replies = [
                format_ % {
                    'longid': x['id'],
                    'user': x['from_user'],
                    'msg': x['text']
                } for x in timeline if not x['text'].startswith('RT ')
            ]
            replies = [
                x.replace("&lt;", "<").replace("&gt;",
                                               ">").replace("&amp;", "&")
                for x in replies
            ]
            if send:
                for reply in replies:
                    irc.reply(reply, prefixNick=False)

        self._searches[name] = 0
        fetch(False)
        schedule.addPeriodicEvent(fetch, 60, name)
        irc.replySuccess()
Example #10
0
    def __init__(self, irc):
        self.__parent = super(DebianDevelChanges, self)
        self.__parent.__init__(irc)
        self.irc = irc
        self.topic_lock = threading.Lock()

        fr = FifoReader()
        fifo_loc = '/var/run/debian-devel-changes/fifo'
        fr.start(self._email_callback, fifo_loc)

        self.queued_topics = {}
        self.last_n_messages = []

        # Schedule datasource updates
        for klass, interval, name in get_datasources():
            try:
                schedule.removePeriodicEvent(name)
            except KeyError:
                pass

            def wrapper(klass=klass):
                klass().update()
                self._topic_callback()

            schedule.addPeriodicEvent(wrapper, interval, name, now=False)
            schedule.addEvent(wrapper, time.time() + 1)
Example #11
0
 def __init__(self, irc):
     self.__parent = super(Hardball, self)
     self.__parent.__init__(irc)
     # initial states for channels.
     self.channels = {}  # dict for channels with values as teams/ids
     self._loadpickle()  # load saved data.
     # initial states for games.
     self.games = None
     self.nextcheck = None
     # dupedict.
     self.dupedict = {}
     # base url.
     self.baseurl = b64decode('aHR0cDovL2dkMi5tbGIuY29t')
     try:
         self.nohitterInning = self.registryValue('inningToAnnounceNoHitter')
     except:
         self.log.info('Registry value for no-hitter inning not set, defaulting to 7')
         self.nohitterInning = 7
     # fill in the blanks.
     if not self.games:
         self.games = self._fetchgames()
     # now schedule our events.
     def checkhardballcron():
         self.checkhardball(irc)
     try:  # check scores.
         schedule.addPeriodicEvent(checkhardballcron, self.registryValue('checkInterval'), now=False, name='checkhardball')
     except AssertionError:
         try:
             schedule.removeEvent('checkhardball')
         except KeyError:
             pass
         schedule.addPeriodicEvent(checkhardballcron, self.registryValue('checkInterval'), now=False, name='checkhardball')
Example #12
0
    def user(self, irc, msg, arg, username):
        """<username>

        Start usering a Twitter account."""
        name = 'twitterstream_user_'+username
        api = twitter.Api()
        def fetch(send=True):
            timeline = api.GetUserTimeline(username,
                    since_id=self._users[name])
            for tweet in timeline:
                self._users[name] = max(self._users[name], tweet.id)
            format_ = '@%(user)s> %(msg)s'
            replies = [format_ % {'longid': x.id,
                                  'user': x.user.screen_name,
                                  'msg': x.text
                                 } for x in timeline]
            replies = [x.replace("&lt;", "<").replace("&gt;", ">")
                    .replace("&amp;", "&") for x in replies]
            if send:
                for reply in replies:
                    irc.reply(reply, prefixNick=False)
        self._users[name] = 0
        fetch(False)
        schedule.addPeriodicEvent(fetch, 60, name)
        irc.replySuccess()
Example #13
0
 def starthello(self, irc, msg, args):
     """Nothing"""
     channel = msg.args[0]
     eventName = "%s_sayhello" % channel
     def sayHello():
         irc.queueMsg(ircmsgs.privmsg("DonVitoCorleone", "Function _sayHello is called"))
         eventNumber = self.read_timer_number()
         eventNumber = eventNumber["n"]
         irc.queueMsg(ircmsgs.privmsg("DonVitoCorleone", "eventN is %i" % eventNumber))
         if eventNumber <= 1:
             irc.queueMsg(ircmsgs.privmsg("DonVitoCorleone", "It's diferent"))
             self.write_timer_number()
         """if eventNumber <= 5:
             irc.sendMsg(ircmsgs.privmsg("DonVitoCorleone", "Current i before is %i" % eventNumber))
             eventNumber += 1
             irc.queueMsg(ircmsgs.privmsg("DonVitoCorleone", "I after is %i" % eventNumber))
             irc.queueMsg(ircmsgs.privmsg("DonVitoCorleone", "Hello World"))
         else:
             irc.queueMsg(ircmsgs.privmsg("DonVitoCorleone", schedule.schedule.events.keys()))
             schedule.removeEvent(eventName)
             irc.queueMsg(ircmsgs.privmsg("DonVitoCorleone", "Going to remove event %s" % eventName))"""
     schedule.addPeriodicEvent(sayHello, 60, eventName, now=False)
     def stopHello():
         print "Going to stop %s" % eventName
         try:
             schedule.removeEvent(eventName)
             print "Event %s stopped" % eventName
         except Exception as e:
             print e
     schedule.addEvent(stopHello, time.time() + 100)
Example #14
0
    def spammer(self, irc, msg, args):
        """<none

        Spamming!!!"""
        #global lines
        #lines = []
        #irc.reply('asdsad')
        #with open('C:\\KAVIRC\\11-14-2013-SasaIka.txt', 'r') as k:
        #b = k.readlines()
        #reg = re.match('(.*)(Z|z)naci(.*)', b)
        #url = conf.supybot.plugins.ERep.url()
        #bata = json.load(utils.web.getUrlFd('%scitizen/search/Digital_Lemon/1.json' % (url)))
        #id = str(bata[0]['id'])
        #irc.reply(id)
        #if id == '3876733':
            #irc.reply('\x02 Link\x02: http://www.erepublik.com/en/citizen/profile/%s' % id)
        #else:
            #return
        #for line in b:
            #lines.append(line)
        #for l in lines:
            #time.sleep(5)
            #irc.reply(l)
        #t = time.time() + 7
        #schedule.addPeriodicEvent(self._checkTime, 7, 'MyFirstEvent')
        def _checkTime():
            url = conf.supybot.plugins.ERep.url()
            bata = json.load(utils.web.getUrlFd('%scitizen/search/Crazy_Hospy/1.json' % (url)))
            id = str(bata[0]['id'])
            irc.reply(id)
            if id == '3876733':
                irc.reply(id)
            if id == '4693953':
                irc.reply('ADsddad')
        schedule.addPeriodicEvent(_checkTime, 7, 'ms')
Example #15
0
 def __init__(self, irc):
     self.__parent = super(Twitter, self)
     self.__parent.__init__(irc)
     self.irc = irc
     self.mentionSince = None
     self.tweetsSince = None
     self.snarfdb = SNARFDB()
     try:
         schedule.removeEvent('Mentions')
     except KeyError:
         pass
     try:
         schedule.removeEvent('Tweets')
     except KeyError:
         pass
     t_consumer_key = self.registryValue('consumer_key')
     t_consumer_secret = self.registryValue('consumer_secret')
     t_access_key = self.registryValue('access_key')
     t_access_secret = self.registryValue('access_secret')
     self.api = twitter.Api(consumer_key=t_consumer_key, consumer_secret=t_consumer_secret, access_token_key=t_access_key, access_token_secret=t_access_secret)
     if self.registryValue('displayTweets'):
         statuses = self.api.GetUserTimeline(include_rts=True, count=1)
         if len(statuses) > 0:
             self.tweetsSince = statuses[0].id
         def tweetsCaller():
             self._tweets(irc)
         schedule.addPeriodicEvent(tweetsCaller, 300, 'Tweets')
     if self.registryValue('displayReplies'):
         statuses = self.api.GetMentions()
         if len(statuses) > 0:
             self.mentionSince = statuses[0].id
         def mentionCaller():
             self._mention(irc)
         schedule.addPeriodicEvent(mentionCaller, 300, 'Mentions')
Example #16
0
 def start_polling(self):
     logger.info("Starting GEA job %s" % self.job_name)
     self.fetch_updates(count=10)
     schedule.addPeriodicEvent(self.fetch_updates,
                               self.update_interval,
                               now=False,
                               name=self.job_name)
Example #17
0
    def user(self, irc, msg, arg, username):
        """<username>

        Start usering a Twitter account."""
        name = 'twitterstream_user_' + username
        api = twitter.Api()

        def fetch(send=True):
            timeline = api.GetUserTimeline(username,
                                           since_id=self._users[name])
            for tweet in timeline:
                self._users[name] = max(self._users[name], tweet.id)
            format_ = '@%(user)s> %(msg)s'
            replies = [
                format_ % {
                    'longid': x.id,
                    'user': x.user.screen_name,
                    'msg': x.text
                } for x in timeline
            ]
            replies = [
                x.replace("&lt;", "<").replace("&gt;",
                                               ">").replace("&amp;", "&")
                for x in replies
            ]
            if send:
                for reply in replies:
                    irc.reply(reply, prefixNick=False)

        self._users[name] = 0
        fetch(False)
        schedule.addPeriodicEvent(fetch, 60, name)
        irc.replySuccess()
Example #18
0
 def __init__(self, irc):
     self.__parent = super(Lunch, self)
     self.__parent.__init__(irc)
     self.irc = irc
     self.scheduled = None
     self._scheduleAnnouncement()
     schedule.addPeriodicEvent(self._checkTopic, self.registryValue('period'), 'lunch')
Example #19
0
    def search(self, irc, msg, arg, search):
        """<terms>

        Start streaming a Twitter search."""
        name = 'twitterstream_search_'+search
        api = twitter.Api()
        def fetch(send=True):
            url = 'http://search.twitter.com/search.json?q=%s&since_id=%i' % \
                    (search, self._searches[name])
            timeline = requests.get(url).json['results']
            for tweet in timeline:
                self._searches[name] = max(self._searches[name], tweet['id'])
            format_ = '@%(user)s> %(msg)s'
            replies = [format_ % {'longid': x['id'],
                                  'user': x['from_user'],
                                  'msg': x['text']
                                 } for x in timeline
                                 if not x['text'].startswith('RT ')]
            replies = [x.replace("&lt;", "<").replace("&gt;", ">")
                    .replace("&amp;", "&") for x in replies]
            if send:
                for reply in replies:
                    irc.reply(reply, prefixNick=False)
        self._searches[name] = 0
        fetch(False)
        schedule.addPeriodicEvent(fetch, 60, name)
        irc.replySuccess()
Example #20
0
    def newpoll(self, irc, msg, args, channel, interval, answers, question):
        """<number of minutes for announce interval> <"answer,answer,..."> question
        Creates a new poll with the given question and answers. <channel> is
        only necessary if the message isn't sent in the channel itself."""

        capability = ircdb.makeChannelCapability(channel, 'op')
        if not ircdb.checkCapability(msg.prefix, capability):
            irc.error('Need ops')
            return

        db = self.getDb(channel)
        cursor = db.cursor()
        self._execute_query(cursor, 'INSERT INTO polls VALUES (?,?,?,?,?)', None, datetime.datetime.now(), 1, None, question)
        pollid = cursor.lastrowid

        # used to add choices into db. each choice represented by character, starting at capital A (code 65)
        def genAnswers():
            for i, answer in enumerate(answers, start=65):
                yield pollid, chr(i), answer

        cursor.executemany('INSERT INTO choices VALUES (?,?,?)', genAnswers())

        db.commit()

        irc.reply('Started new poll #%s' % pollid)

        # function called by schedule event. can not have args
        def runPoll():
            self._runPoll(irc, channel, pollid)

        # start schedule. will announce poll/choices to channel at interval
        schedule.addPeriodicEvent(runPoll, interval*60, name='%s_poll_%s' % (channel, pollid))
        self.poll_schedules.append('%s_poll_%s' % (channel, pollid))
Example #21
0
    def __init__(self, irc):
        self.__parent = super(SubredditAnnouncer, self)
        self.__parent.__init__(irc)
        self.savefile = conf.supybot.directories.data.dirize("subredditAnnouncer.db")
        self.headers = {"User-Agent": "SubredditAnnouncer ([email protected])"}

        def checkForPosts():
            self.checkReddit(irc)
        try:
            schedule.addPeriodicEvent(checkForPosts,
                                      self.registryValue('checkinterval')*60,
                                      'redditCheck', False)
        except AssertionError:
            schedule.removeEvent('redditCheck')
            schedule.addPeriodicEvent(checkForPosts,
                                      self.registryValue('checkinterval')*60,
                                      'redditCheck', False)
        try:
            if self.registryValue('dsn') != "":
                if "raven" in dir():  # Check that raven was actually imported
                    self.raven = raven.Client(self.registryValue("dsn"))
                else:
                    self.log.error("dsn defined but raven not installed! Please pip install raven")
        except NonExistentRegistryEntry:
            pass
Example #22
0
 def __init__(self, irc):
     self.__parent = super(Tail, self)
     self.__parent.__init__(irc)
     self.files = {}
     period = self.registryValue('period')
     schedule.addPeriodicEvent(self._checkFiles, period, name=self.name())
     for filename in self.registryValue('files'):
         self._add(filename)
Example #23
0
 def __init__(self, irc):
     super(Darkfallonline, self).__init__(irc)
     self._state = {}
     for server, url in servers:
         self._state[server] = check_status(url)
     self._login = check_login_status(login)
     schedule.addPeriodicEvent(self._announcer, 10,
                               'Darkfallonline_checkstatus')
Example #24
0
 def __init__(self, irc):
     self.__parent = super(Tail, self)
     self.__parent.__init__(irc)
     self.files = {}
     period = self.registryValue('period')
     schedule.addPeriodicEvent(self._checkFiles, period, name=self.name())
     for filename in self.registryValue('files'):
         self._add(filename)
Example #25
0
 def __init__(self, irc):
     super(Darkfallonline, self).__init__(irc)
     self._state = {}
     for server, url in servers:
         self._state[server] = check_status(url)
     self._login = check_login_status(login)
     schedule.addPeriodicEvent(self._announcer, 10,
             'Darkfallonline_checkstatus')
Example #26
0
 def _start_polling(self):
     log.info('Start polling.')
     schedule.addPeriodicEvent(self._minutely_diff_poll,
                               60,
                               now=True,
                               name='minutely_poll')
     schedule.addPeriodicEvent(self._notes_rss_poll,
                               60,
                               now=True,
                               name='notes_rss_poll')
Example #27
0
    def __init__(self, irc):
        super().__init__(irc)
        self.irc = irc
        self.topic_lock = threading.Lock()

        self.dbus_service = BTSDBusService(self._email_callback)

        self.mainloop = None
        mainloop = GObject.MainLoop()
        if not mainloop.is_running():
            mainloop_thread = threading.Thread(target=mainloop.run)
            mainloop_thread.start()
            self.mainloop = mainloop

        self.dbus_bus = SystemBus()
        self.dbus_bus.publish(self.dbus_service.interface_name,
                              self.dbus_service)
        self.dbus_service.start()

        self.requests_session = requests.Session()
        self.requests_session.verify = True

        self.queued_topics = {}
        self.last_n_messages = []

        self.stable_rc_bugs = StableRCBugs(self.requests_session)
        self.testing_rc_bugs = TestingRCBugs(self.requests_session)
        self.new_queue = NewQueue(self.requests_session)
        self.dinstall = Dinstall(self.requests_session)
        self.rm_queue = RmQueue(self.requests_session)
        self.apt_archive = AptArchive(
            self.registryValue('apt_configuration_directory'),
            self.registryValue('apt_cache_directory'))
        self.data_sources = (self.stable_rc_bugs, self.testing_rc_bugs,
                             self.new_queue, self.dinstall, self.rm_queue,
                             self.apt_archive)

        # Schedule datasource updates
        def wrapper(source):
            def implementation():
                try:
                    source.update()
                except Exception as e:
                    log.exception('Failed to update {}: {}'.format(
                        source.NAME, e))
                self._topic_callback()

            return implementation

        for source in self.data_sources:
            schedule.addPeriodicEvent(wrapper(source),
                                      source.INTERVAL,
                                      source.NAME,
                                      now=False)
            schedule.addEvent(wrapper(source), time.time() + 1)
Example #28
0
 def __init__(self, irc):
     self.__parent = super(GNOMEOSTree, self)
     self.__parent.__init__(irc)
     schedule.addPeriodicEvent(self._query_new_build, 1, now=False)
     schedule.addPeriodicEvent(self._query_new_smoketest, 1, now=False)
     self._irc = irc
     self._last_build_version = None
     self._last_smoketest_version = None
     self._jsondb_re = re.compile(r'^(\d+\.\d+)-([0-9a-f]+)\.json$')
     self._workdir = os.path.expanduser('~/ostbuild/work/')
     self._workurl = "http://ostree.gnome.org/work/"
Example #29
0
    def __init__(self, irc):
        self.__parent = super(Tinderbox, self)
        self.__parent.__init__(irc)

        self.current_trees = {};
        for channel in irc.state.channels.keys():
            self.current_trees[channel] = \
                self._get_trees(self.registryValue('trees', channel))
        period = self.registryValue('pollTime')
        schedule.addPeriodicEvent(self._pollTrees, period, name=self.name(),
                                  now=False)
Example #30
0
 def _channelState(self, irc, msg, nick, channel, adminPlugin):
     """Collects users from <channel> and determines if <nick> is owner or admin"""
     channels = irc.state.channels
     if channel in channels:
         users = irc.state.channels[channel].users
         # This checks number of valid users on channel
         validNicks = self._populateNicks(users)
         if validNicks == "Valid":
             owners = irc.state.channels[channel].owners
             # If owners are not empty that means ownermode is set and user must have +q
             # mode to request bot
             if len(owners) != 0:
                 if nick in owners:
                     eventName = "%s_RequestBot_dailyChecks" % channel
                     stopEventName = "%s_RequestBot_stopDailyChecks" % channel
                     # We must schedule it this way because we can't pass args in schedule...
                     def startDailyChecks():
                         # We are checking channel users for few days because one might try
                         # to bring a lot of users when he requests bot and later those users
                         # will part channel and never come back again
                         self._dailyCheckOfUsers(irc, msg, adminPlugin, channel, eventName)
                     # We're scheduling this to be run few times a day for few days and at the last
                     # time we're going to check if there where minimum users on the channel
                     # for most of the time
                     # TODO: Implement last check
                     schedule.addPeriodicEvent(startDailyChecks, self.dailyChecksInterval, eventName, now=False)
                     def stopDailyChecks():
                         # We must schedule it here because if we do it elswhere we won't be able to
                         # access new state of scheduler which holds reference to our scheduled event
                         schedule.removeEvent(eventName)
                     schedule.addEvent(stopDailyChecks, time.time() + self.stopDailyCheck, stopEventName)
                     greetMsg = "Hi, I've been assigned here thanks to %s. If you have any questions use +list or come to #KG-Bot and ask." % nick
                     irc.queueMsg(ircmsgs.privmsg(channel, greetMsg))
                 else:
                     partMsg = "You're not owner (with +q set) so you can't have me in here."
                     irc.queueMsg(ircmsgs.privmsg(channel, partMsg))
                     adminPlugin.part(irc, msg, [channel, partMsg])
             # If there are no owners with +q mode set we're not going to allow admins or ops
             # to request bot, we're forcing players to use ownermode and +q so only true channel owner
             # can request bot (you never know what admins can try to do)
             else:
                 partMsg = "There are no owners in here (with +q set)."
                 irc.queueMsg(ircmsgs.privmsg(channel, partMsg))
                 adminPlugin.part(irc, msg, [channel, partMsg])
         else:
             partMsg = "You don't have enough users in here."
             irc.queueMsg(ircmsgs.privmsg(channel, partMsg))
             adminPlugin.part(irc, msg, [channel, partMsg])
     # This should never happen, maybe only if bot is kicked from channel before
     # scheduled event for this command has been executed
     else:
         partMsg = "There was something strange internally. Please notify my owner about this."
         irc.queueMsg(ircmsgs.privmsg(channel, partMsg))
         adminPlugin.part(irc, msg, [channel, partMsg])
 def __init__(self, irc):
     self.__parent = super(SeattleIncidentResponse, self)
     self.__parent.__init__(irc)
     self.savefile = conf.supybot.directories.data.dirize("SeattleIncidentResponse.db")
             
     def checkForPosts():
         self.checkForIncidents(irc)
     try:
         schedule.addPeriodicEvent(checkForPosts, self.registryValue('checkinterval')*60, 'incidentresponsecheck', False)
     except AssertionError:
         schedule.removeEvent('incidentresponsecheck')
         schedule.addPeriodicEvent(checkForPosts, self.registryValue('checkinterval')*60, 'incidentresponsecheck', False)
Example #32
0
    def __init__(self, irc):
        self.__parent = super(Tinderbox, self)
        self.__parent.__init__(irc)

        self.current_trees = {}
        for channel in irc.state.channels.keys():
            self.current_trees[channel] = \
                self._get_trees(self.registryValue('trees', channel))
        period = self.registryValue('pollTime')
        schedule.addPeriodicEvent(self._pollTrees,
                                  period,
                                  name=self.name(),
                                  now=False)
Example #33
0
    def start(self, irc, msg, args):
        """takes no arguments

        A command to start the node checker."""
        # don't forget to redefine the event wrapper
        def checkForNodes():
            self.checkNodes(irc)
        try:
            schedule.addPeriodicEvent(checkForNodes, 5, 'hyperboriaNodeChecker', False)
        except AssertionError:
            irc.reply('Error: the node checker was already running!')
        else:
            irc.reply('Node checker started!')
Example #34
0
    def start(self, irc, msg, args):
        """takes no arguments

        A command to start the bamboo watcher."""
        # don't forget to redefine the event wrapper
        def myEventCaller():
            self.bambooEvent(irc)
        try:
            schedule.addPeriodicEvent(myEventCaller, self.bambooTime, 'myJiraStudioObserverEvent', False)
        except AssertionError:
            irc.reply('Error: JiraStudioObserver was already running!')
        else:
            irc.reply('JiraStudioObserver started!')
Example #35
0
 def __init__(self, irc):
     self.__parent = super(fearbot, self)
     self.__parent.__init__(irc)
     self.savefile = conf.supybot.directories.data.dirize("fearbot.db")
     self.headers = {"User-Agent":"fearbot ([email protected])"}
             
     def checkForPosts():
         self.checkReddit(irc)
     try:
         schedule.addPeriodicEvent(checkForPosts, self.registryValue('checkinterval')*60, 'redditCheck', False)
     except AssertionError:
         schedule.removeEvent('redditCheck')
         schedule.addPeriodicEvent(checkForPosts, self.registryValue('checkinterval')*60, 'redditCheck', False)
Example #36
0
 def __init__(self, irc):
     self.__parent = super(Tail, self)
     self.__parent.__init__(irc)
     try:
         self.config = json.load(open(conf.supybot.directories.data.dirize(
             self.registryValue('configfile')), 'r'))
     except FileNotFoundError as e:
         self.log.warning("Couldn't open file: %s" % e)
         raise
     self.files = {}
     period = self.registryValue('period')
     schedule.addPeriodicEvent(self._checkfiles, period, name=self.name())
     for filename in self.config.keys():
         self._add(filename)
Example #37
0
    def __init__(self, irc):
        self.__parent = super(SubredditAnnouncer, self)
        self.__parent.__init__(irc)
        self.savefile = conf.supybot.directories.data.dirize("subredditAnnouncer.db")
        self.headers = {"User-Agent": "SubredditAnnouncer ([email protected])"}

        def checkForPosts():
            self.checkReddit(irc)

        try:
            schedule.addPeriodicEvent(checkForPosts, self.registryValue("checkinterval") * 60, "redditCheck", False)
        except AssertionError:
            schedule.removeEvent("redditCheck")
            schedule.addPeriodicEvent(checkForPosts, self.registryValue("checkinterval") * 60, "redditCheck", False)
Example #38
0
 def __init__(self, irc):
     self.__parent = super(LogsToDB, self)
     self.__parent.__init__(irc)
     self.lastMsgs = {}
     self.lastStates = {}
     self.logs = {}
     self.flusher = self.flush
     world.flushers.append(self.flusher)
     self.logViewerDB = channellogger_model.LogviewerDB()
     self.logViewerFile = channellogger_model.LogviewerFile()
     self.currentUsers = 0
     def myEventCaller():
         self.addCount(irc)
     schedule.addPeriodicEvent(myEventCaller, 600, 'mySpamEvent')
Example #39
0
    def reset(self, irc, msg, args):
        """takes no arguments

        Resets the bamboo build watcher.  Can be useful if something changes and you want the
        updates to reflect that.  For example, if you defined the bambooChannel as a
        supybot config, and changed it while the bamboo build watcher was running, it would still
        keep going on the same channel until you reset it."""
        def myEventCaller():
            self.bambooEvent(irc)
        try:
            schedule.removeEvent('myJiraStudioObserverEvent')
        except KeyError:
            irc.reply('Build watcher wasn\'t running')
        schedule.addPeriodicEvent(myEventCaller, self.bambooTime, 'myJiraStudioObserverEvent', False)
        irc.reply('Build watcher reset sucessfully!')
Example #40
0
 def __init__(self, irc):
     super(GNOMEOSTree, self).__init__(irc)
     schedule.addPeriodicEvent(self._query_new_tasks, 1, now=False)
     self._irc = irc
     self._flood_channels = ['#testable']
     self._status_channels = ['#gnome-hackers']
     self._last_task_state = {}
     tracked_build = 'buildmaster'
     self._periodic_announce_seconds = 3*60*60
     self._periodic_announce_ticks = 0
     self._always_announce_tasks = ['build']
     self._announce_failed_tasks = ['resolve']
     self._announce_periodic_tasks = ['smoketest', 'integrationtest']
     self._workdir = os.path.expanduser('/srv/ostree/ostbuild/%s/' % (tracked_build, ))
     self._workurl = "http://build.gnome.org/ostree/%s" % (tracked_build, )
Example #41
0
class Football(callbacks.Plugin):
    """Add the help for "@plugin help Football" here
    This should describe *how* to use this plugin."""
    threaded = True

    def __init__(self, irc):
        self.__parent = super(Football, self)
        self.__parent.__init__(irc)
        # initial states for games.
        self.games = None
        self.nextcheck = None
        self.scoredict = {}  # for scoring events.
        # dict for big plays and dupedict.
        self.bps = {}
        self.bpsdupe = set([])
        # now setup the empty channels dict.
        self.channels = {}
        self._loadpickle()  # load saved data into channels.
        # Odds XML cache.
        self.CACHEFILE = conf.supybot.directories.data.dirize(self.name() +
                                                              ".xml")
        # now do our initial run.
        if not self.games:
            self.games = self._fetchgames()
        # now setup the regular cron.
        def checkfootballcron():
            try:
                self.checkfootball(irc)
            except Exception, e:  # something broke. The plugin will stop itself from reporting.
                self.log.error("cron: ERROR :: {0}".format(e))
                self.nextcheck = self._utcnow(
                ) + 72000  # add some major delay so the plugin does not spam.

        # now setup the schedule part of the cron.
        try:
            schedule.addPeriodicEvent(checkfootballcron,
                                      30,
                                      now=False,
                                      name='checkfootball')
        except AssertionError:
            try:
                schedule.removeEvent('checkfootball')
            except KeyError:
                pass
            schedule.addPeriodicEvent(checkfootballcron,
                                      30,
                                      now=False,
                                      name='checkfootball')
Example #42
0
 def __init__(self, irc):
     self.__parent = super(Bugzilla, self)
     self.__parent.__init__(irc)
     self.saidBugs = ircutils.IrcDict()
     self.saidAttachments = ircutils.IrcDict()
     sayTimeout = self.registryValue('bugSnarferTimeout')
     for k in irc.state.channels.keys():
         self.saidBugs[k] = TimeoutQueue(sayTimeout)
         self.saidAttachments[k] = TimeoutQueue(sayTimeout)
     period = self.registryValue('mboxPollTimeout')
     schedule.addPeriodicEvent(self._pollMbox, period, name=self.name(),
                               now=False)
     for name in self.registryValue('bugzillas'):
         registerBugzilla(name)
     reload(sys)
     sys.setdefaultencoding('utf-8')
Example #43
0
 def _repeat(self, irc, msg, name, seconds, command, now=True):
     f = self._makeCommandFunction(irc, msg, command, remove=False)
     id = schedule.addPeriodicEvent(f, seconds, name, now)
     assert id == name
     self.events[name] = {'command':command,
                          'msg':msg,
                          'time':seconds,
                          'type':'repeat'}
Example #44
0
    def set_auto_announce_interval(self):
        interval = self.registryValue("pollingIntervalInSeconds")

        self.remove_announce_interval()

        if not self.auto_announce_interval:
            self.auto_announce_interval = schedule.addPeriodicEvent(
                self.announce_to_channels, interval, "SpiffyRadioAutoAnnounce")
Example #45
0
    def __init__(self, irc):
        self.__parent = super(Jira, self)
        self.__parent.__init__(irc)
        self.server = self.registryValue('server')

        self.checkTime = 30  # move to config

        try:
            schedule.removeEvent('recent')
        except KeyError:
            pass

        def myEventCaller():
            self.recentOnly(irc)

        schedule.addPeriodicEvent(myEventCaller, self.checkTime, 'recent')
        self.irc = irc
Example #46
0
    def __init__(self, irc):
        super(DebianDevelChanges, self).__init__(irc)
        self.irc = irc
        self.topic_lock = threading.Lock()

        fr = FifoReader()
        fifo_loc = '/var/run/debian-devel-changes-bot/fifo'
        fr.start(self._email_callback, fifo_loc)

        self.requests_session = requests.Session()
        self.requests_session.verify = True

        self.queued_topics = {}
        self.last_n_messages = []

        self.stable_rc_bugs = StableRCBugs(self.requests_session)
        self.testing_rc_bugs = TestingRCBugs(self.requests_session)
        self.new_queue = NewQueue(self.requests_session)
        self.data_sources = (self.stable_rc_bugs, self.testing_rc_bugs,
                             self.new_queue)

        # Schedule datasource updates
        for klass, interval, name in get_datasources():
            try:
                schedule.removePeriodicEvent(name)
            except KeyError:
                pass

            def wrapper(klass=klass):
                klass().update()
                self._topic_callback()

            schedule.addPeriodicEvent(wrapper, interval, name, now=False)
            schedule.addEvent(wrapper, time.time() + 1)

        def wrapper(source):
            def implementation():
                source.update()
                self._topic_callback()
            return implementation

        for source in self.data_sources:
            schedule.addPeriodicEvent(wrapper(source), source.INTERVAL,
                                      source.NAME, now=False)
            schedule.addEvent(wrapper(source), time.time() + 1)
Example #47
0
    def start(self, irc, msg, args):
        """takes no arguments

        A command to start the node checker."""
        # don't forget to redefine the event wrapper
        if ircdb.checkCapability(msg.prefix, "owner"):

            def checkForPosts():
                self.checkReddit(irc)

            try:
                schedule.addPeriodicEvent(
                    checkForPosts,
                    self.registryValue('checkinterval') * 60, 'redditCheck',
                    False)
            except AssertionError:
                irc.reply('The reddit checker was already running!')
            else:
                irc.reply('Reddit checker started!')
        else:
            irc.reply("F**k off you unauthorized piece of shit")
Example #48
0
    def __init__(self, irc):
        self.__parent = super(Racebot, self)
        self.__parent.__init__(irc)

        db = RacebotDB(self.DATABASE_FILENAME)

        username = self.registryValue('iRacingUsername')
        password = self.registryValue('iRacingPassword')

        connection = IRacingConnection(username, password)
        self.iRacingData = IRacingData(connection, db)

        # Check for newly registered racers every x time, (initially five minutes.)
        # This should perhaps ramp down in frequency during non-registration times and ramp up a few minutes
        #  before race start times (four times per hour.)  For now, we fire every five minutes.
        def scheduleTick():
            self.doBroadcastTick(irc)

        schedule.addPeriodicEvent(scheduleTick,
                                  self.SCHEDULER_INTERVAL_SECONDS,
                                  self.SCHEDULER_TASK_NAME)
Example #49
0
def main():
    import supybot.conf as conf
    import supybot.world as world
    import supybot.drivers as drivers
    import supybot.schedule as schedule
    # We schedule this event rather than have it actually run because if there
    # is a failure between now and the time it takes the Owner plugin to load
    # all the various plugins, our registry file might be wiped.  That's bad.
    interrupted = False
    when = conf.supybot.upkeepInterval()
    schedule.addPeriodicEvent(world.upkeep, when, name='upkeep', now=False)
    world.startedAt = started
    while world.ircs:
        try:
            drivers.run()
        except KeyboardInterrupt:
            if interrupted:
                # Interrupted while waiting for queues to clear.  Let's clear
                # them ourselves.
                for irc in world.ircs:
                    irc._reallyDie()
                    continue
            else:
                interrupted = True
                log.info('Exiting due to Ctrl-C.  '
                         'If the bot doesn\'t exit within a few seconds, '
                         'feel free to press Ctrl-C again to make it exit '
                         'without flushing its message queues.')
                world.upkeep()
                for irc in world.ircs:
                    quitmsg = conf.supybot.plugins.Owner.quitMsg() or \
                              'Ctrl-C at console.'
                    irc.queueMsg(ircmsgs.quit(quitmsg))
                    irc.die()
        except SystemExit, e:
            s = str(e)
            if s:
                log.info('Exiting due to %s', s)
            break
        except:
Example #50
0
    def openpoll(self, irc, msg, args, channel, pollid, interval):
        """[<channel>] <id>
        Starts announcing poll with the given <id> if set to active.
        <channel> is only necessary if the message isn't sent in the channel
        itself."""

        db = self.getDb(channel)
        cursor = db.cursor()

        # query to check poll exists and if it is open
        pollinfo = self._poll_info(db, pollid)
        if pollinfo is None:
            irc.error('Poll id doesnt exist')
            return
        if pollinfo[1] is None:
            irc.error('Poll is still open')
            return

        # query to OPEN IT UP! unsets closed time
        self._execute_query(cursor, 'UPDATE polls SET closed=? WHERE id=?',
                            None, pollid)
        db.commit()

        # if poll was set active then start schedule for it
        if pollinfo[0] == 1:
            if interval is None:
                irc.reply(
                    'Note: Poll set to active, but you didnt supply interval, using default of 10 minutes'
                )
                interval = 10
            # function called by schedule event. can not have args
            def runPoll():
                self._runPoll(irc, channel, pollid)

            # start schedule. will announce poll/choices to channel at interval
            schedule.addPeriodicEvent(runPoll,
                                      interval * 60,
                                      name='%s_poll_%s' % (channel, pollid))
            self.poll_schedules.append('%s_poll_%s' % (channel, pollid))
Example #51
0
    def pollon(self, irc, msg, args, channel, pollid, interval):
        """<[channel]> <id> <interval in minutes>
        Schedules announcement of poll with the given <id> every <interval>.
        <channel> is only necessary if the message is not sent in the channel
        itself."""

        db = self.getDb(channel)
        cursor = db.cursor()

        # query to check poll exists, and if it is already on
        pollinfo = self._poll_info(db, pollid)
        if pollinfo is None:
            irc.error('That poll id does not exist')
            return
        if pollinfo[0] == 1:
            irc.error('Poll is already active')
            return

        # query to set poll off
        db.execute('UPDATE polls SET isAnnouncing=? WHERE id=?', (1, pollid))
        db.commit()

        if pollinfo[1] is not None:
            irc.reply(
                'Note: you are turning on closed poll. I will not start announcing it'
            )
            return

        # function called by schedule event. can not have args
        def runPoll():
            self._runPoll(irc, channel, pollid)

        # start schedule. will announce poll/choices to channel at interval
        schedule.addPeriodicEvent(runPoll,
                                  interval * 60,
                                  name='%s_poll_%s' % (channel, pollid))
        self.poll_schedules.append('%s_poll_%s' % (channel, pollid))
Example #52
0
    def __init__(self, irc):
        self.__parent = super(Odds, self)
        self.__parent.__init__(irc)
        self.displaytz = self.registryValue('displayTZ')
        self.XMLURL = 'http://lines.bookmaker.eu/'
        self.CACHEFILE = conf.supybot.directories.data.dirize("Odds.xml")

        def oddscachexmlcron():
            self.oddscachexml()

        try:  # every 1hours make sure the schedule is fresh.
            schedule.addPeriodicEvent(oddscachexmlcron,
                                      3600,
                                      now=True,
                                      name='oddscachexml')
        except AssertionError:
            try:
                schedule.removeEvent('oddscachexml')
            except KeyError:
                pass
            schedule.addPeriodicEvent(oddscachexmlcron,
                                      3600,
                                      now=True,
                                      name='oddscachexml')
Example #53
0
    def newpoll(self, irc, msg, args, channel, interval, answers, question):
        """<number of minutes for announce interval> <"answer,answer,..."> question
        Creates a new poll with the given question and answers. <channel> is
        only necessary if the message isn't sent in the channel itself."""

        capability = ircdb.makeChannelCapability(channel, 'op')
        if not ircdb.checkCapability(msg.prefix, capability):
            irc.error('Need ops')
            return

        db = self.getDb(channel)
        cursor = db.cursor()
        self._execute_query(cursor, 'INSERT INTO polls VALUES (?,?,?,?,?)',
                            None, datetime.datetime.now(), 1, None, question)
        pollid = cursor.lastrowid

        # used to add choices into db. each choice represented by character, starting at capital A (code 65)
        def genAnswers():
            for i, answer in enumerate(answers, start=65):
                yield pollid, chr(i), answer

        cursor.executemany('INSERT INTO choices VALUES (?,?,?)', genAnswers())

        db.commit()

        irc.reply('Started new poll #%s' % pollid)

        # function called by schedule event. can not have args
        def runPoll():
            self._runPoll(irc, channel, pollid)

        # start schedule. will announce poll/choices to channel at interval
        schedule.addPeriodicEvent(runPoll,
                                  interval * 60,
                                  name='%s_poll_%s' % (channel, pollid))
        self.poll_schedules.append('%s_poll_%s' % (channel, pollid))
Example #54
0
    def repeat(self, irc, msg, args, name, seconds, command):
        """<name> <seconds> <command>

        Schedules the command <command> to run every <seconds> seconds,
        starting now (i.e., the command runs now, and every <seconds> seconds
        thereafter).  <name> is a name by which the command can be
        unscheduled.
        """
        name = name.lower()
        if name in self.events:
            irc.error(
                'There is already an event with that name, please '
                'choose another name.',
                Raise=True)
        self.events[name] = command
        f = self._makeCommandFunction(irc, msg, command, remove=False)
        id = schedule.addPeriodicEvent(f, seconds, name)
        assert id == name
Example #55
0
    def __init__(self, irc):
        self.__parent = super(DropboxWatch, self)
        self.__parent.__init__(irc)
        callback = DropboxWatchServerCallback()
        self._abbrev = DropboxWatchServerCallback.name.lower()

        for server in httpserver.http_servers:
            if self._abbrev in server.callbacks:
                httpserver.unhook(self._abbrev)
                break

        httpserver.hook(self._abbrev, callback)
        interval = conf.supybot.plugins.DropboxWatch.interval()

        def f():
            if events.empty():
                return

            path_dict = dict()

            for channel in irc.state.channels:
                paths = conf.supybot.plugins.DropboxWatch.paths.get(channel)()

                if len(paths) == 0:
                    continue

                for path in paths:
                    if path in path_dict:
                        continue

                    path_dict[path] = (set(), set())

            try:
                while not events.empty():
                    event = events.get_nowait()

                    for path in path_dict.keys():
                        if event[1].startswith('/' + path):
                            updates, deletes = path_dict[path]

                            if event[0] == EventType.delete:
                                deletes.add(event[1])
                            else:
                                updates.add(event[1])

                            path_dict[path] = (updates, deletes)
            except Queue.Empty:
                log.warning('Queue empty')

            for k in path_dict.keys():
                updates, deletes = path_dict[k]
                output = ''

                if len(deletes) > 0:
                    output = 'Deleted: %s' % (', '.join(deletes))

                if len(updates) > 0:
                    if len(output) > 0:
                        output += ' | '

                    output += 'Updated: %s' % (', '.join(updates))

                if len(output) == 0:
                    continue

                output = '[Dropbox] %s' % output

                for chan in irc.state.channels:
                    paths = conf.supybot.plugins.DropboxWatch.paths.get(chan)()

                    if len(paths) == 0 or k not in paths:
                        continue

                    log.info('%s >> %s' % (chan, output))
                    irc.queueMsg(ircmsgs.privmsg(chan, output))

        if self._abbrev in schedule.schedule.events:
            schedule.removeEvent(self._abbrev)

        schedule.addPeriodicEvent(f, interval, name=self._abbrev, now=False)
Example #56
0
 def startPoll(self):
   self.conn = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
   schedule.addPeriodicEvent(lambda: self.poll(), self.checkTime, 'utPoll:' + str(self), False)
   self.polling = True
Example #57
0
 def __init__(self, irc):
     self.__parent = super(UbuntuUnreg, self)
     self.__parent.__init__(irc)
     self.event = 'UbuntuUnreg'
     schedule.addPeriodicEvent(self.check, self.registryValue('interval'), self.event)
Example #58
0
    def start(self, irc, msg, args):
        """
        Starts the hunt
        """

        currentChannel = msg.args[0]
        if irc.isChannel(currentChannel):

            if (self.started.get(currentChannel) == True):
                irc.reply("There is already a hunt right now!")
            else:

                # First of all, let's read the score if needed
                self._read_scores(currentChannel)

                self._initthrottle(irc, msg, args, currentChannel)

                # Init saved scores
                try:
                    self.channelscores[currentChannel]
                except:
                    self.channelscores[currentChannel] = {}

                # Init saved times
                try:
                    self.channeltimes[currentChannel]
                except:
                    self.channeltimes[currentChannel] = {}

                # Init saved times
                try:
                    self.channelworsttimes[currentChannel]
                except:
                    self.channelworsttimes[currentChannel] = {}

                # Init times
                self.toptimes[currentChannel] = {}
                self.worsttimes[currentChannel] = {}

                # Init bangdelay
                self.times[currentChannel] = False

                # Init lastSpoke
                self.lastSpoke[currentChannel] = time.time()

                # Reinit current hunt scores
                if self.scores.get(currentChannel):
                    self.scores[currentChannel] = {}

                # Reinit reloading
                self.reloading[currentChannel] = {}

                # No duck launched
                self.duck[currentChannel] = False

                # Hunt started
                self.started[currentChannel] = True

                # Init shoots
                self.shoots[currentChannel] = 0

                # Init averagetime
                self.averagetime[currentChannel] = 0

                # Init schedule

                # First of all, stop the scheduler if it was still running
                try:
                    schedule.removeEvent('DuckHunt_' + currentChannel)
                except KeyError:
                    pass

                # Then restart it
                def myEventCaller():
                    self._launchEvent(irc, msg)

                try:
                    schedule.addPeriodicEvent(myEventCaller, 5,
                                              'DuckHunt_' + currentChannel,
                                              False)
                except AssertionError:
                    pass

                irc.reply("The hunt starts now!")
        else:
            irc.error('You have to be on a channel')
Example #59
0
    def start(self, irc, msg, args, channel):
        """[channel]

        Starts SupySnap for [channel]. If [channel] is not specified the
        current one is used."""

        seconds = self.registryValue('interval', channel)
        username = self.registryValue('username', channel)
        password = self.registryValue('password', channel)
        address = self.registryValue('address', channel)
        localpath = self.registryValue('localpath', channel)
        markasread = self.registryValue('markasread', channel)

        if not username or username == '':
            irc.error('No username entered.')
            return
        if not password or password == '':
            irc.error('No password entered.')
            return
        if not address or address == '':
            irc.error('No address entered.')
            return
        if not localpath or localpath == '':
            irc.error('No local path entered.')
            return
        if not os.path.isdir(localpath):
            os.makedirs(localpath)

        name = self._name(channel)

        def fetch():
            try:
                s = pysnap.Snapchat()
                if not s.login(username,
                               password)['updates_response'].get('logged'):
                    irc.reply('Invalid username or password.')
                    return
                for snap in s.get_snaps():
                    # media_type 3 is friend requests. status 2 means it is read
                    if snap['media_type'] == 3 or snap['status'] == 2:
                        continue
                    #boop = 'ID: {0}\tMedia id: {1}\tMedia type: {2}\tTime: {3}\tSender: {4}\tRecipient: {5}\tStatus: {6}\tScreenshot count: {7}\tSent: {8}\tOpened: {9}'.format(snap['id'], snap['media_id'], snap['media_type'], snap['time'], snap['sender'], snap['recipient'], snap['status'], snap['screenshot_count'], snap['sent'], snap['opened'])
                    #self.log.info(str(boop))
                    sent = time.strftime(
                        '%Y-%m-%dT%H:%M',
                        time.gmtime(int(str(snap['sent'])[:-3])))
                    filename = '{2}_{0}.{1}'.format(
                        snap['sender'],
                        pysnap.get_file_extension(snap['media_type']), sent)
                    abspath = os.path.abspath(os.path.join(
                        localpath, filename))
                    if os.path.isfile(abspath):
                        continue
                    data = s.get_blob(snap['id'])
                    if data is None:
                        continue
                    with open(abspath, 'wb') as f:
                        f.write(data)
                        irc.reply('[{0}] New snap from: {1}! - {2}{3}'.format(
                            username, snap['sender'], address, filename))
                    if markasread:
                        s.mark_viewed(snap['id'])
            except Exception as e:
                self.log.error('SupySnap: ' + str(e))

        self._names.append(name)
        try:
            schedule.addPeriodicEvent(fetch, seconds, name)
        except AssertionError:
            irc.error('SupySnap is already running in this channel.')
            return
        irc.replySuccess()