def __init__(self, irc, victim, detonateTime, channel, sender, debug): self.victim = victim self.startTime = time.time() self.detonateTime = detonateTime self.active = True self.channel = channel self.sender = sender self.irc = irc self.debug = debug self.thrown = False self.responded = False self.rng = random.Random() self.rng.seed() if self.debug: self.irc.reply('I just created a lazor in %s' % channel) def detonate(): self.detonate(irc) schedule.addEvent(detonate, self.startTime + self.detonateTime, '%s_lazor' % self.channel) formattedTime = "%02d:%02d:%02d" % ( detonateTime / 3600, detonateTime / 60, detonateTime % 60) irc.reply("IMMA CHARGIN MAH LAZOR") s = 'charges his lazor' self.irc.queueMsg(ircmsgs.action(self.channel, s))
def newquestion(self): if self.num == 0: self.active = False elif ( self.unanswered > self.registryValue("inactiveShutoff", self.channel) and self.registryValue("inactiveShutoff", self.channel) >= 0 ): self.reply("Seems like no one's playing any more.") self.active = False elif len(self.questions) == 0: self.reply("Oops! I ran out of questions!") self.active = False if not self.active: self.stop() return self.hints = 0 self.num -= 1 self.numAsked += 1 which = self.rng.randint(0, len(self.questions) - 1) q = self.questions.pop(which) sep = self.registryValue("questionFileSeparator") self.q = q[: q.find(sep)] self.a = q[q.find(sep) + len(sep) :].split(sep) self.reply( "\x03%s#%d of %d: %s" % (self.registryValue("color", self.channel), self.numAsked, self.total, self.q) ) def event(): self.timedEvent() eventTime = time.time() + self.registryValue("timeout", self.channel) / ( self.registryValue("numHints", self.channel) + 1 ) if self.active: schedule.addEvent(event, eventTime, "next_%s" % self.channel)
def detonate(self, irc): self.active = False #if self.showCorrectWire: # self.irc.reply('Should\'ve gone for the %s wire!' % self.goodWire) self.irc.sendMsg( ircmsgs.privmsg(self.channel, ' .___ ')) self.irc.sendMsg( ircmsgs.privmsg(self.channel, ' (,) O/```````````````````````````````````')) self.irc.sendMsg( ircmsgs.privmsg(self.channel, 'c [| >->o ')) self.irc.sendMsg( ircmsgs.privmsg(self.channel, ' \___________________________________')) self.active = False self.thrown = False self.irc.queueMsg( ircmsgs.kick(self.channel, self.victim, 'shoop da woop')) def reinvite(): if not self.victim in irc.state.channels[self.channel].users: self.irc.queueMsg(ircmsgs.invite(self.victim, self.channel)) if not self.responded: schedule.addEvent(reinvite, time.time() + 5)
def version(self, irc, msg, args, channel, optlist): """[<channel>] [--nicks] Sends a CTCP VERSION to <channel>, returning the various version strings returned. It waits for 10 seconds before returning the versions received at that point. If --nicks is given, nicks are associated with the version strings; otherwise, only the version strings are given. """ self.versions = ircutils.IrcDict() nicks = False for (option, arg) in optlist: if option == 'nicks': nicks = True irc.queueMsg(ircmsgs.privmsg(channel, '\x01VERSION\x01')) def doReply(): if self.versions: L = [] for (reply, nickslist) in self.versions.iteritems(): if nicks: L.append( format('%L responded with %q', nickslist, reply)) else: L.append(reply) irc.reply(format('%L', L)) else: irc.reply('I received no version responses.') wait = self.registryValue('versionWait') schedule.addEvent(doReply, time.time() + wait)
def perform_standup(self): """Perform the daily standup""" # based on what time it is, guess which standup we are having # Which team is it? irc = self.irc now = datetime.datetime.now() stand_up = None for st in self.__standups: # What time is it? hour, min, sec = st["time"] if hour == now.hour and min == now.minute: stand_up = st break else: # did not find one print "Did not find a matching standup" return irc.queueMsg( ircmsgs.privmsg( stand_up["channel"], "%s - %s - Yesterday, Today, Blocked?" % (" ".join(stand_up["members"]), stand_up["name"]), ) ) # schedule the next event next_time = self._nextStandup(stand_up["name"]) schedule.addEvent(self.perform_standup, next_time, stand_up["name"]) print "[Perform Standup] Scheduling standup at %s for %s" % (str(next_time), stand_up["name"])
def hint(self): self.hints += 1 ans = self.a[0] self.show.setdefault(self.id, None) self.revealed.setdefault(self.id, None) hintPercentage = self.registryValue('hintPercentage', self.channel) divider = round(len(re.sub('[^a-zA-Z0-9]+', '', ans)) * hintPercentage) blankChar = self.registryValue('blankChar', self.channel) blank = re.sub('\w', blankChar, ans) if not self.show[self.id]: self.show[self.id] = list(blank) if not self.revealed[self.id]: self.revealed[self.id] = list(range(len(self.show[self.id]))) i = 0 while i < divider and len(self.revealed[self.id]) > 1: try: rand = self.revealed[self.id].pop(random.randint(0,len(self.revealed[self.id])) - 1) if self.show[self.id][rand] == blankChar: self.show[self.id][rand] = list(ans)[rand] i += 1 except: break self.reply(_('HINT: %s') % (''.join(self.show[self.id]))) self.p = self.p // 2 def event(): self.timedEvent() timeout = self.registryValue('timeout', self.channel) numHints = self.registryValue('numHints', self.channel) eventTime = time.time() + timeout / (numHints + 1) if self.active: schedule.addEvent(event, eventTime, 'next_%s' % self.channel)
def _topic_callback(self): self.topic_lock.acquire() sections = { lambda: len(TestingRCBugs().get_bugs()): 'RC bug count:', NewQueue().get_size: 'NEW queue:', RmQueue().get_size: 'RM queue:', } try: values = {} for callback, prefix in sections.iteritems(): values[callback] = callback() for channel in self.irc.state.channels: new_topic = topic = self.irc.state.getTopic(channel) for callback, prefix in sections.iteritems(): if values[callback]: new_topic = rewrite_topic(new_topic, prefix, values[callback]) if topic != new_topic: log.info("Queueing change of topic in #%s to '%s'" % (channel, new_topic)) self.queued_topics[channel] = new_topic event_name = '%s_topic' % channel try: schedule.removeEvent(event_name) except KeyError: pass schedule.addEvent(lambda channel=channel: self._update_topic(channel), time.time() + 60, event_name) finally: self.topic_lock.release()
def version(self, irc, msg, args, channel, optlist): """[<channel>] [--nicks] Sends a CTCP VERSION to <channel>, returning the various version strings returned. It waits for 10 seconds before returning the versions received at that point. If --nicks is given, nicks are associated with the version strings; otherwise, only the version strings are given. """ self.versions = ircutils.IrcDict() nicks = False for (option, arg) in optlist: if option == 'nicks': nicks = True irc.queueMsg(ircmsgs.privmsg(channel, '\x01VERSION\x01')) def doReply(): if self.versions: L = [] for (reply, nicks) in self.versions.iteritems(): if nicks: L.append(format('%L responded with %q', nicks, reply)) else: L.append(reply) irc.reply(format('%L', L)) else: irc.reply('I received no version responses.') wait = self.registryValue('versionWait') schedule.addEvent(doReply, time.time()+wait)
def next_question(self): self.clear() self.correct = False if self.registryValue("keepHistory", self.channel): self.history[self.channel].append(int(self.id)) self.reply(self.question) if self.timeout > 0: def endEvent(): self.end() self.endTime = time.time() + self.timeout schedule.addEvent(endEvent, self.endTime, "end_%s" % self.channel) if self.showBlank: self.hint() elif self.showHints or self.showTime: def timedEvent(): self.timedEvent() eventTime = time.time() + self.waitTime if eventTime < self.endTime: schedule.addEvent(timedEvent, eventTime, "event_%s" % self.channel) elif self.showBlank: self.hint()
def doPrivmsg(self, irc, msg): channel = msg.args[0] nick = msg.prefix.split('!')[0] if channel not in self.states: return reply = None state = self.states[channel] for mode, answer in state.answers: if mode == 'r': if msg.args[1].lower() == answer.lower(): state.adjust(nick, state.question[0]) reply = _('Congratulations %s! The answer was %r.') reply %= (nick, answer) elif mode == 'm': if answer.match(msg.args[1]): state.adjust(nick, state.question[0]) reply = _('Congratulations %s! The answer was %r.') reply %= (nick, msg.args[1]) if reply is not None: schedule.removeEvent('Eureka-nextClue-%s' % channel) otherAnswers = [y for x,y in state.answers if x == 'r' and y.lower() != msg.args[1].lower()] if len(otherAnswers) == 1: reply += ' ' + _('Another valid answer is: \'%s\'.') reply %= otherAnswers[0] elif len(otherAnswers) >= 2: reply += ' ' + _('Other valid answers are: \'%s\'.') reply %= '\', \''.join([x for x in otherAnswers]) irc.reply(reply, prefixNick=False) schedule.addEvent(self._ask, time.time() + 6, args=(irc, channel, True)) # Delay in seconds for next question after answered question (just change 6 to seconds you want to use).
def doPrivmsg(self, irc, msg): if irc.isChannel(msg.args[0]): speakChan = msg.args[0] dbChan = plugins.getChannel(speakChan) canSpeak = False now = time.time() throttle = self.registryValue('randomSpeaking.throttleTime', speakChan) prob = self.registryValue('randomSpeaking.probability', speakChan) delay = self.registryValue('randomSpeaking.maxDelay', speakChan) if now > self.lastSpoke + throttle: canSpeak = True if canSpeak and random.random() < prob: f = self._markov(speakChan, irc, prefixNick=False, to=speakChan, Random=True) schedule.addEvent(lambda: self.q.enqueue(f), now + delay) self.lastSpoke = now + delay words = self.tokenize(msg) # This shouldn't happen often (CTCP messages being the possible # exception) if not words: return if self.registryValue('ignoreBotCommands', speakChan) and \ callbacks.addressed(irc.nick, msg): return words.insert(0, None) words.insert(0, None) words.append(None) def doPrivmsg(db): for (first, second, follower) in utils.seq.window(words, 3): db.addPair(dbChan, first, second, follower, isFirst=(first is None and second is None), isLast=(follower is None)) self.q.enqueue(doPrivmsg)
def shoa(self, irc, msg, args): """ Shoa ist anberaumt """ if(self._checkCPO(irc, msg)): nicks = [] nick4 = [] def unlimit(): irc.queueMsg(ircmsgs.unlimit(msg.args[0], 0)) irc.queueMsg(ircmsgs.limit(msg.args[0], 1)) schedule.addEvent(unlimit, time.time() + 3*60) for nick in irc.state.channels[msg.args[0]].users: if nick not in irc.state.channels[msg.args[0]].ops: nicks.append(nick) i = 0 for nick in nicks: i = i+1 nick4.append(nick) if (len(nick4) >= 4): irc.queueMsg(ircmsgs.kicks(msg.args[0], nicks, 'Reichskristallnacht')) nick4 = [] elif ((len(nicks) - i) < 4): irc.queueMsg(ircmsgs.kicks(msg.args[0], nicks, 'Reichskristallnacht')) irc.noReply()
def _reply(self, irc, msg, channel, text): """Send a response to text""" cobeBrain = Brain(self._getBrainDirectoryForChannel(channel)) response = cobeBrain.reply(text).encode('utf-8') response = self._strip_nick(irc, msg, response) for i in range(response.lower().count(self.magicnick.lower())): # If first word is nick, switch with the callers nick. if self.magicnick in response: response = response.replace( self.magicnick, random.choice(list(irc.state.channels[msg.args[0]].users))) if self.magicnick.lower() in response: response = response.replace( self.magicnick.lower(), random.choice(list(irc.state.channels[msg.args[0]].users))) cobeBrain.learn( response) # Let's have the bot learn the wacky things it says self.log.info("Attempting to respond in {0} with message: {1}".format( channel, response)) # delay the response here so we look real? if self.registryValue('responseDelay', channel): self.log.info("Delayed the response in %s." % channel) delayseconds = time.time() + random.randint(2, 5) schedule.addEvent(irc.queueMsg(ircmsgs.privmsg(channel, response)), delayseconds) else: irc.queueMsg(ircmsgs.privmsg(channel, response))
def social(self, irc, msg, args, channel, user, junk): """[#powder] <user> Sets a redirection ban from #powder to #powder-social, kicks the user (exploiting a users auto-rejoin to force them to #powder-social) then lifts the ban. Also sends the user a notice informing them of what happened.""" if channel not in '#powder': channel = '#powder' hostmask = irc.state.nickToHostmask(user) irc.queueMsg( ircmsgs.IrcMsg( 'MODE #powder +b {0}$#powder-social'.format(hostmask))) irc.queueMsg( ircmsgs.IrcMsg( 'KICK #powder {0} :Take it to #powder-social'.format(user))) irc.queueMsg(ircmsgs.invite(user, '#powder-social')) irc.queueMsg( ircmsgs.IrcMsg(( 'NOTICE {0} :{1} has requested you take your current conversation', 'to #powder-social.').format(user, msg.nick))) expires = time.time() + 300 def f(): irc.queueMsg( ircmsgs.IrcMsg( 'MODE #powder -b {0}$#powder-social'.format(hostmask))) schedule.addEvent(f, expires)
def k(self, irc, msg, args, nicks): """[user] ... [user] Kick mit Timeban """ if(self._checkCPO(irc, msg)): hostmasks = [] for nick in nicks: prefix = irc.state.nickToHostmask(nick) user = ircutils.userFromHostmask(prefix) host = ircutils.hostFromHostmask(prefix) hostmask = '*!*@%s' % host if(host.find('mibbit.com') != -1): hostmask = '*!%s@*.mibbit.com' % user hostmasks.append(hostmask) hostmask = '*!*@%s' % self._numToDottedQuad(user) hostmasks.append(hostmask) irc.queueMsg(ircmsgs.bans(msg.args[0], hostmasks)) irc.queueMsg(ircmsgs.kicks(msg.args[0], nicks, 'Your behavior is not conducive to the desired environment.')) def unban(): irc.queueMsg(ircmsgs.unbans(msg.args[0], hostmasks)) schedule.addEvent(unban, time.time() + 900) irc.noReply()
def _giveClue(self, irc, channel, now=False): state = self.states[channel] (delay, clue, valid) = state.getClue() def event(): try: schedule.removeEvent('Eureka-nextClue-%s' % channel) except KeyError: pass if clue is None: assert valid is None irc.reply(_('Nobody replied with (one of this) ' 'answer(s): %r.') % ', '.join([y for x, y in state.answers if x == 'r']), prefixNick=False) self._ask(irc, channel) else: irc.reply(_('Another clue: %s') % clue, prefixNick=False) self._giveClue(irc, channel) eventName = 'Eureka-nextClue-%s' % channel if now and eventName in schedule.schedule.events: schedule.schedule.events[eventName]() schedule.removeEvent(eventName) schedule.addEvent(event, time.time() + delay, eventName)
def saveLast(self,irc,msg,match): r".+" channel = msg.args[0] try: self.buffer[channel] except: self.buffer[channel]=[] # Stuff for multikick if channel in self.kickuser: for each in self.kickuser[channel]: if each in msg.nick.lower() and not self.kickuser[channel][each]['num'] <= 0: irc.queueMsg(ircmsgs.ban(msg.args[0], msg.nick)) irc.queueMsg(ircmsgs.kick(msg.args[0], msg.nick, "{}".format(self.kickuser[channel][each]['msg'].replace('#n',str(self.kickuser[channel][each]['num']))))) self.kickuser[channel][each]['num']-=1 def un(): irc.queueMsg(ircmsgs.unban(msg.args[0],msg.nick)) schedule.addEvent(un,time.time()+random.randint(10,60)) # 30,120 # END line = match.group(0).replace('\x01ACTION','*').strip('\x01') if msg.nick.lower() in self.annoyUser: def fu(): irc.queueMsg(ircmsgs.IrcMsg('NOTICE {} :\x02\x03{},{}{}'.format(msg.nick,random.randint(0,15),random.randint(0,15),line))) schedule.addEvent(fu,time.time()+random.randint(2,60)) if re.match(r"^u[/].*[/].*[/].*$", match.group(0)) or re.match(r"^s[/].*[/].*$", match.group(0)): return 1 self.buffer[channel].insert(0,[msg.nick,line]) if len(self.buffer[channel]) > self.buffsize: self.buffer[channel].pop(self.buffsize) return 1
def newquestion(self): inactiveShutoff = self.registryValue('inactiveShutoff', self.channel) if self.num == 0: self.active = False elif self.unanswered > inactiveShutoff and inactiveShutoff >= 0: self.reply(_('Seems like no one\'s playing any more.')) self.active = False elif len(self.questions) == 0: self.reply(_('Oops! I ran out of questions!')) self.active = False if not self.active: self.stop() return self.hints = 0 self.num -= 1 self.numAsked += 1 which = self.rng.randint(0, len(self.questions)-1) q = self.questions.pop(which) sep = self.registryValue('questionFileSeparator') self.q = q[:q.find(sep)] self.a = q[q.find(sep)+len(sep):].split(sep) color = self.registryValue('color', self.channel) self.reply(_('\x03%s#%d of %d: %s') % (color, self.numAsked, self.total, self.q)) def event(): self.timedEvent() timeout = self.registryValue('timeout', self.channel) numHints = self.registryValue('numHints', self.channel) eventTime = time.time() + timeout / (numHints + 1) if self.active: schedule.addEvent(event, eventTime, 'next_%s' % self.channel)
def __init__(self, irc, victim, wires, detonateTime, goodWire, channel, sender, showArt, showCorrectWire, debug): self.victim = victim self.detonateTime = detonateTime self.wires = wires self.goodWire = goodWire self.active = True self.channel = channel self.sender = sender self.irc = irc self.showArt = showArt self.showCorrectWire = showCorrectWire self.debug = debug self.thrown = False self.responded = False self.rng = random.Random() self.rng.seed() if self.debug: self.irc.reply('I just created a bomb in %s' % channel) def detonate(): self.detonate(irc) schedule.addEvent(detonate, time.time() + self.detonateTime, '%s_bomb' % self.channel) s = 'stuffs a bomb down %s\'s pants. The timer is set for %s seconds! There are %s wires. Use !cut <wire> to defuse the bomb. The wires are: %s.' % (self.victim, self.detonateTime, len(wires), utils.str.commaAndify(wires)) self.irc.queueMsg(ircmsgs.action(self.channel, s)) if self.victim == irc.nick: time.sleep(1) cutWire = self.rng.choice(self.wires) self.irc.queueMsg(ircmsgs.privmsg(self.channel, '@cutwire %s' % cutWire)) time.sleep(1) self.cutwire(self.irc, cutWire)
def doPrivmsg(self, irc, msg): if irc.isChannel(msg.args[0]): channel = plugins.getChannel(msg.args[0]) canSpeak = False now = time.time() throttle = self.registryValue('randomSpeaking.throttleTime', channel) prob = self.registryValue('randomSpeaking.probability', channel) delay = self.registryValue('randomSpeaking.maxDelay', channel) irc = callbacks.SimpleProxy(irc, msg) if now > self.lastSpoke + throttle: canSpeak = True if canSpeak and random.random() < prob: f = self._markov(channel, irc, prefixNick=False, to=channel, Random=True) schedule.addEvent(lambda: self.q.enqueue(f), now + delay) self.lastSpoke = now + delay words = self.tokenize(msg) words.insert(0, '\n') words.insert(0, '\n') words.append('\n') # This shouldn't happen often (CTCP messages being the possible exception) if not words or len(words) == 3: return if self.registryValue('ignoreBotCommands', channel) and \ callbacks.addressed(irc.nick, msg): return def doPrivmsg(db): for (first, second, follower) in utils.seq.window(words, 3): db.addPair(channel, first, second, follower) self.q.enqueue(doPrivmsg)
def quiet(self, irc, msg, args, channel, nick, expiry): """[<channel>] <nick> [<expiry>] Quietens <nick> from <channel> for <expiry>. If <expiry> isn't given, the duration is permanent. <channel> is only necessary if the message isn't sent in the channel itself. """ if irc.isNick(nick): bannedNick = nick try: bannedHostmask = irc.state.nickToHostmask(nick) except KeyError: irc.error(format(_('I haven\'t seen %s.'), bannedNick), Raise=True) else: bannedNick = ircutils.nickFromHostmask(nick) bannedHostmask = nick if not irc.isNick(bannedNick): self.log.warning('%q tried to quiet a non nick: %q', msg.prefix, bannedNick) raise callbacks.ArgumentError banmaskstyle = conf.supybot.protocols.irc.banmask banmask = banmaskstyle.makeBanmask(bannedHostmask) if ircutils.strEqual(nick, irc.nick): irc.error('I cowardly refuse to quiet myself.', Raise=True) thismsg=self.registryValue('message') self._sendMsg(irc, ircmsgs.mode(channel, ("+q", banmask))) if self.registryValue('SendMsgPvt'): self._sendMsg(irc, ircmsgs.privmsg(nick,nick+", "+thismsg )) else: self._sendMsg(irc, ircmsgs.privmsg(channel,nick+", "+thismsg )) def f(): irc.queueMsg(ircmsgs.mode(channel, ("-q", banmask))) if expiry: schedule.addEvent(f, expiry)
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)
def _playqueue(self, irc): def _playline(): irc.reply(self.playQueue.pop(), prefixNick=False) start = time.time() for i, v in enumerate(self.playQueue): schedule.addEvent(_playline, start + i * PP)
def detonate(self, irc): self.active = False self.thrown = False if self.showCorrectWire: self.irc.sendMsg(ircmsgs.privmsg(self.channel, 'Should\'ve gone for the {} wire!'.format(self.goodWire))) if self.showArt: self.irc.sendMsg(ircmsgs.privmsg(self.channel, '\x031,1.....\x0315,1_.\x0314,1-^^---....,\x0315,1,-_\x031,1.......')) self.irc.sendMsg(ircmsgs.privmsg(self.channel, '\x031,1.\x0315,1_--\x0314,1,.\';,`.,\';,.;;`;,.\x0315,1--_\x031,1...')) self.irc.sendMsg(ircmsgs.privmsg(self.channel, '\x0315,1<,.\x0314,1;\'`".,;`..,;`*.,\';`.\x0315,1;\'>)\x031,1.')) self.irc.sendMsg(ircmsgs.privmsg(self.channel, '\x0315,1I.:;\x0314,1.,`;~,`.;\'`,.;\'`,..\x0315,1\';`I\x031,1.')) self.irc.sendMsg(ircmsgs.privmsg(self.channel, '\x031,1.\x0315,1\\_.\x0314,1`\'`..`\';.,`\';,`\';,\x0315,1_../\x031,1..')) self.irc.sendMsg(ircmsgs.privmsg(self.channel, '\x031,1....\x0315,1```\x0314,1--. . , ; .--\x0315,1\'\'\'\x031,1.....')) self.irc.sendMsg(ircmsgs.privmsg(self.channel, '\x031,1..........\x034,1I\x031,1.\x038,1I\x037,1I\x031,1.\x038,1I\x034,1I\x031,1...........')) self.irc.sendMsg(ircmsgs.privmsg(self.channel, '\x031,1..........\x034,1I\x031,1.\x037,1I\x038,1I\x031,1.\x037,1I\x034,1I\x031,1...........')) self.irc.sendMsg(ircmsgs.privmsg(self.channel, '\x031,1.......,\x034,1-=\x034,1II\x037,1..I\x034,1.I=-,\x031,1........')) self.irc.sendMsg(ircmsgs.privmsg(self.channel, '\x031,1.......\x034,1`-=\x037,1#$\x038,1%&\x037,1%$#\x034,1=-\'\x031,1........')) else: self.irc.sendMsg(ircmsgs.privmsg(self.channel, 'KABOOM!')) self.irc.queueMsg(ircmsgs.kick(self.channel, self.victim, 'BOOM!')) def reinvite(): if self.victim not in irc.state.channels[self.channel].users: self.irc.queueMsg(ircmsgs.invite(self.victim, self.channel)) if not self.responded: schedule.addEvent(reinvite, time.time() + 5)
def __init__(self, irc, victim, wires, detonateTime, goodWire, channel, sender, showArt, showCorrectWire, debug): self.victim = victim self.detonateTime = detonateTime self.wires = wires self.goodWire = goodWire self.active = True self.channel = channel self.sender = sender self.irc = irc self.showArt = showArt self.showCorrectWire = showCorrectWire self.debug = debug self.thrown = False self.responded = False self.rng = random.Random() self.rng.seed() if self.debug: self.irc.reply('I just created a bomb in {}'.format(channel)) def detonate(): self.detonate(irc) schedule.addEvent(detonate, time.time() + self.detonateTime, '{}_bomb'.format(self.channel)) s = 'stuffs a bomb down {}\'s pants. The timer is set for {} seconds! There are {} wires. They are: {}.'.format(self.victim, self.detonateTime, len(wires), utils.str.commaAndify(wires)) self.irc.queueMsg(ircmsgs.action(self.channel, s)) if self.victim == irc.nick: time.sleep(1) cutWire = self.rng.choice(self.wires) self.irc.queueMsg(ircmsgs.privmsg(self.channel, '$cutwire {}'.format(cutWire))) time.sleep(1) self.cutwire(self.irc, cutWire)
def _giveClue(self, irc, channel, now=False): state = self.states[channel] (delay, clue, valid) = state.getClue() def event(): try: schedule.removeEvent("Eureka-nextClue-%s" % channel) except KeyError: pass if clue is None: assert valid is None irc.reply( _("Nobody replied with (one of this) " "answer(s): %s.") % ", ".join([y for x, y in state.answers if x == "r"]), prefixNick=False, ) self._ask(irc, channel) else: irc.reply(_("Another clue: %s") % clue, prefixNick=False) self._giveClue(irc, channel) eventName = "Eureka-nextClue-%s" % channel if now and eventName in schedule.schedule.events: schedule.schedule.events[eventName]() schedule.removeEvent(eventName) schedule.addEvent(event, time.time() + delay, eventName)
def _topic_callback(self): sections = { self.testing_rc_bugs.get_number_bugs: 'RC bug count', self.stable_rc_bugs.get_number_bugs: 'Stable RC bug count', self.new_queue.get_size: 'NEW queue', RmQueue().get_size: 'RM queue', } with self.topic_lock: values = {} for callback, prefix in sections.iteritems(): values[callback] = callback() for channel in self.irc.state.channels: new_topic = topic = self.irc.state.getTopic(channel) for callback, prefix in sections.iteritems(): if values[callback]: new_topic = rewrite_topic(new_topic, prefix, values[callback]) if topic != new_topic: log.info("Queueing change of topic in #%s to '%s'" % (channel, new_topic)) self.queued_topics[channel] = new_topic event_name = '%s_topic' % channel try: schedule.removeEvent(event_name) except KeyError: pass schedule.addEvent(lambda channel=channel: self._update_topic(channel), time.time() + 60, event_name)
def schedule(self, irc, msg, args, timestamp, name): """[name] [timestamp] Schedule an event with [name] at [timestamp] """ schedule.addEvent(self.perform_standup, int(timestamp), name) irc.replySuccess()
def stab(self, irc, msg, args, channel, user, timer): """<user> [seconds] Stabs a user, putting them on quiet for a random time up to 10 mins.""" irc.queueMsg( ircmsgs.IrcMsg('MODE {0} +q {1}'.format( channel, irc.state.nickToHostmask(user)))) t = time.time() r = timer if not r > 0: r = random.randint(30, 600) expires = t + r len = {} len['m'] = len['s'] = 0 while r > 59: len['m'] += 1 r -= 60 len['s'] = r irc.queueMsg( ircmsgs.IrcMsg( 'NOTICE {0} :{1} has been quieted for {2}:{3:0>2}'.format( msg.nick, user, len['m'], len['s']))) def f(): irc.queueMsg( ircmsgs.IrcMsg('MODE {0} -q {1}'.format(channel, user))) schedule.addEvent(f, expires) irc.noReply()
def clearOffenses(self, host): if self.offenses[host] > 1: self.offenses[host] -= 1 schedule.addEvent(self.clearOffenses, time.time()+300, args=[host]) else: del self.offenses[host]
def newquestion(self): inactiveShutoff = self.registryValue('inactiveShutoff', self.channel) if self.num == 0: self.active = False elif self.unanswered > inactiveShutoff and inactiveShutoff >= 0: self.reply('Seems like no one\'s playing any more.') self.active = False elif len(self.questions) == 0: self.reply('Oops! I ran out of questions!') self.active = False if not self.active: self.stop() return self.hints = 0 self.num -= 1 self.numAsked += 1 which = self.rng.randint(0, len(self.questions) - 1) q = self.questions.pop(which) sep = self.registryValue('questionFileSeparator') self.q = q[:q.find(sep)] self.a = q[q.find(sep) + len(sep):].split(sep) color = self.registryValue('color', self.channel) self.reply('\x03%s#%d of %d: %s' % (color, self.numAsked, self.total, self.q)) def event(): self.timedEvent() timeout = self.registryValue('timeout', self.channel) numHints = self.registryValue('numHints', self.channel) eventTime = time.time() + timeout / (numHints + 1) if self.active: schedule.addEvent(event, eventTime, 'next_%s' % self.channel)
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)
def request(self, irc, msg, args, channel, reason): """<channel> - channel name for which you make request, <reason> - reason why do you want bot (it must be some good reason, not some bullshit) Request bot for <channel>, you must specify <reason> why do you want it.""" # TODO: Before anything happens we should check if <channel> is valid IRC channel name # because if it's not we won't be able to join it, collect irc.state and our code will # probably brake in the unwanted manner #TODO: If we're already on channel nothing should be done and user should be # presented with explanation (we still have to implement that in our code)""" nick = msg.nick isChannelBanned = self._checkChannelBan(channel) # TODO: change this because this will probably return dict of more info about ban if isChannelBanned == "Valid": isRequesterBanned = self._checkRequesterBan(nick) # TODO: Change this because this will probably behave like channel ban and will return dict if isRequesterBanned == "Valid": # We're doing it this way because it's much more easier than trying to reimplement # admin join function with all those network, group, et. stuff adminPlugin = irc.getCallback("Admin") adminPlugin.join(irc, msg, [channel.lower()]) # We must schedule this command because when bot joins some channel it neads few seconds # to collect irc.state and we can't access those right after the join schedule.addEvent(self._channelState, time.time() + 5, args=[irc, msg, nick, channel, adminPlugin]) elif isRequesterBanned == "Banned": irc.reply("You can't request bot becuase you're on ban list.") else: irc.reply("There was some ugly internal error. Please try again and notify my owner about this.") elif isChannelBanned == "Banned": irc.reply("This channel is banned and you can't request bot for it.") else: irc.reply("There was some ugly internal error. Please try again and notify my owner about this.")
def doPrivmsg(self, irc, msg): channel, text = msg.args text = text.lower() if '#' in channel: #print self.regex #irc.reply('testing %s against %s' % (text, self._regexString)) if self.regex.match(text): try: hostmask = irc.state.nickToHostmask(msg.nick) except KeyError: return (nick, user, host) = ircutils.splitHostmask(hostmask) user = self._fnUser.sub('*', user) banmask = ircutils.joinHostmask('*', user, msg.host) if ircutils.hostmaskPatternEqual(banmask, irc.prefix): return irc.queueMsg(ban(channel, banmask, 'For swearing. 5 minute timeout')) irc.queueMsg(kick(channel, msg.nick, 'For swearing')) def unBan(): if channel in irc.state.channels and \ banmask in irc.state.channels[channel].bans: irc.queueMsg(unban(channel, banmask)) schedule.addEvent(unBan, time.time()+300) elif 'f*g' in text.split(): try: hostmask = irc.state.nickToHostmask(msg.nick) except KeyError: return (nick, user, host) = ircutils.splitHostmask(hostmask) irc.reply('No thanks %s I don\'t smoke' % user) return msg
def __init__(self, irc, victim, wires, detonateTime, goodWire, channel, sender, showArt, showCorrectWire, debug): self.victim = victim self.startTime = time.time(); self.detonateTime = detonateTime self.wires = wires self.goodWire = goodWire self.active = True self.channel = channel self.sender = sender self.irc = irc self.showArt = showArt self.showCorrectWire = showCorrectWire self.debug = debug self.thrown = False self.responded = False self.rng = random.Random() self.rng.seed() if self.debug: self.irc.reply('I just created a bomb in %s' % channel) def detonate(): self.detonate(irc) schedule.addEvent(detonate, self.startTime + self.detonateTime, '%s_bomb' % self.channel) formattedTime = "%02d:%02d:%02d" % (detonateTime / 3600, detonateTime / 60, detonateTime % 60) s = 'stuffs a bomb down %s\'s pants. The display reads [%s]. The wires are: %s.' % (self.victim, formattedTime, utils.str.commaAndify(wires)) self.irc.queueMsg(ircmsgs.action(self.channel, s)) if self.victim == irc.nick: time.sleep(1) cutWire = self.rng.choice(self.wires) self.irc.queueMsg(ircmsgs.privmsg(self.channel, '@cutwire %s' % cutWire)) time.sleep(1) self.cutwire(self.irc, cutWire)
def _reply(self, irc, msg, channel, text): """Send a response to text""" cobeBrain = Brain(self._getBrainDirectoryForChannel(channel)) response = cobeBrain.reply(text).encode('utf-8') response = self._strip_nick(irc, msg, response) for i in range(response.lower().count(self.magicnick.lower())): # If first word is nick, switch with the callers nick. if self.magicnick in response: response = response.replace(self.magicnick, random.choice(list(irc.state.channels[msg.args[0]].users))) if self.magicnick.lower() in response: response = response.replace(self.magicnick.lower(), random.choice(list(irc.state.channels[msg.args[0]].users))) cobeBrain.learn(response) # Let's have the bot learn the wacky things it says self.log.info("Attempting to respond in {0} with message: {1}".format(channel, response)) # delay the response here so we look real? if self.registryValue('responseDelay', channel): self.log.info("Delayed the response in %s." % channel) delayseconds = time.time() + random.randint(2, 5) schedule.addEvent(irc.queueMsg(ircmsgs.privmsg(channel, response)), delayseconds) else: irc.queueMsg(ircmsgs.privmsg(channel, response))
def nextround(self): channel = self.channel game = self cah = game.game try: self.cardsPlayed = {} cah.next_round() #Print Black Card to channel. self._printBlackCard(self.channel) for nick in self.players: self._msgHandToPlayer(nick) self._msg(channel, "The white cards have been PMed to the players, you have 60 seconds to choose.") self.acceptingWhiteCards = True #TODO: do we need a round flag? schedule.addEvent(self.endround, time.time() + 60, "round_%s" % channel) except Exception: #TODO: add no more round logic #playerScores = sorted(cah.score.iteritems(), key=operator.itemgetter(1), reverse=True) #scores = [] winner = None formattedScores = [] print cah.score winner = self._findHighScore(cah.score) for name, score in cah.score.iteritems(): formattedScores.append("%s: %d" % (name, score)) self._msg(channel, "Game Over! %s is the Winner! Scores: %s " % (winner[0][0], ", ".join(formattedScores)))
def do437(self, irc, msg): """Nick/channel temporarily unavailable.""" target = msg.args[0] t = time.time() + 30 if irc.isChannel(target): # Let's schedule a rejoin. networkGroup = conf.supybot.networks.get(irc.network) def rejoin(): irc.queueMsg(networkGroup.channels.join(target)) # We don't need to schedule something because we'll get another # 437 when we try to join later. schedule.addEvent(rejoin, t) self.log.info( 'Scheduling a rejoin to %s at %s; ' 'Channel temporarily unavailable.', target, t) else: irc = self.pendingNickChanges.get(irc, None) if irc is not None: def nick(): irc.queueMsg(ircmsgs.nick(target)) schedule.addEvent(nick, t) self.log.info( 'Scheduling a nick change to %s at %s; ' 'Nick temporarily unavailable.', target, t) else: self.log.debug('Got 437 without Admin.nick being called.')
def social(self, irc, msg, args, channel, user, junk): """[#powder] <user> Sets a redirection ban from #powder to #powder-social, kicks the user (exploiting a users auto-rejoin to force them to #powder-social) then lifts the ban. Also sends the user a notice informing them of what happened.""" if channel not in '#powder': channel = '#powder' hostmask = irc.state.nickToHostmask(user) irc.queueMsg(ircmsgs.IrcMsg( 'MODE #powder +b {0}$#powder-social'.format(hostmask))) irc.queueMsg(ircmsgs.IrcMsg( 'KICK #powder {0} :Take it to #powder-social'.format(user))) irc.queueMsg(ircmsgs.invite(user, '#powder-social')) irc.queueMsg(ircmsgs.IrcMsg(( 'NOTICE {0} :{1} has requested you take your current conversation', 'to #powder-social.').format( user, msg.nick))) expires = time.time() + 300 def f(): irc.queueMsg(ircmsgs.IrcMsg( 'MODE #powder -b {0}$#powder-social'.format(hostmask))) schedule.addEvent(f, expires)
def run_callback(callback, id_): ''' Run the callback 'now' on main thread. ''' try: schedule.removeEvent(id_) except KeyError: pass schedule.addEvent(callback, time.time(), id_)
def stab(self,irc,msg,args,channel,user,timer): """<user> [seconds] Stabs a user, putting them on quiet for a random time up to 10 mins.""" irc.queueMsg(ircmsgs.IrcMsg('MODE {0} +q {1}'.format(channel,irc.state.nickToHostmask(user)))) t = time.time() r = timer if not r > 0: r = random.randint(30,600) expires = t+r len={} len['m'] = len['s'] = 0 while r > 59: len['m']+=1 r-=60 len['s'] = r irc.queueMsg(ircmsgs.IrcMsg('NOTICE {0} :{1} has been quieted for {2}:{3:0>2}'.format(msg.nick,user,len['m'],len['s']))) def f(): irc.queueMsg(ircmsgs.IrcMsg('MODE {0} -q {1}'.format(channel,user))) schedule.addEvent(f,expires) irc.noReply()
def annoy(self, irc, msg, args, channel, nick, mins): """[channel] <nick> [mins] Repeats everything the user says via a NOTICE for 2 minutes if [mins] is not specified. Blame Doxin for this.""" if not mins or mins == 0: mins = 2 expires = time.time() + mins * 60 try: def f(): try: self.annoyUser.pop(self.annoyUser.index(nick.lower())) self.log.info('ANNOY: No longer annoying {0}'.format(nick)) except: self.log.info('ANNOY: Expired for {0}'.format(nick)) schedule.addEvent(f, expires) except: irc.error('I borked.') return 0 self.log.info('ANNOY: Annoying {0} for {1} minutes'.format(nick, mins)) self.annoyUser += [nick.lower()]
def newquestion(self): inactiveShutoff = self.registryValue('inactiveShutoff', self.channel) if self.num == 0: self.active = False elif self.unanswered > inactiveShutoff and inactiveShutoff >= 0: self.reply(_('Seems like no one\'s playing any more.')) self.active = False elif len(self.questions) == 0: self.reply(_('Oops! I ran out of questions!')) self.active = False if not self.active: self.stop() return self.id = None self.hints = 0 self.num -= 1 self.numAsked += 1 sep = self.registryValue('questionFileSeparator') q = self.questions.pop(len(self.questions) - 1).split(sep) if q[0].startswith('#'): self.id = q[0] self.q = q[1] self.a = [q[2]] if q[3]: self.p = int(q[3]) else: self.p = self.points else: self.q = q[0] self.a = [q[1]] if q[2]: self.p = int(q[2]) else: self.p = self.points color = self.registryValue('color', self.channel) self.reply( _('\x03%s#%d of %d: %s') % (color, self.numAsked, self.total, self.q)) ans = self.a[0] if "(" in self.a[0]: a1, a2, a3 = re.match("(.*)\((.*)\)(.*)", self.a[0]).groups() self.a.append(a1 + a3) self.a.append(a2) blankChar = self.registryValue('blankChar', self.channel) blank = re.sub('\w', blankChar, ans) self.reply("HINT: {0}".format(blank)) if self.id: f = open(self.historyfile, 'a') f.write("{0}\n".format(self.id)) f.close() def event(): self.timedEvent() timeout = self.registryValue('timeout', self.channel) numHints = self.registryValue('numHints', self.channel) eventTime = time.time() + timeout / (numHints + 1) if self.active: schedule.addEvent(event, eventTime, 'next_%s' % self.channel)
def nextround(self): channel = self.channel game = self cah = game.game try: self.cardsPlayed = {} cah.next_round() # Print Black Card to channel. self._printBlackCard(self.channel) for nick in self.players: self._msgHandToPlayer(nick) self._msg( channel, "The white cards have been sent to players, you have 60 seconds to choose.", ) self.acceptingWhiteCards = True # TODO: do we need a round flag? schedule.addEvent(self.endround, time.time() + 60, "round_%s" % channel) except Exception: # TODO: add no more round logic # playerScores = sorted(cah.score.iteritems(), key=operator.itemgetter(1), reverse=True) # scores = [] winner = None formattedScores = [] print(cah.score) winner = self._findHighScore(cah.score) for name, score in cah.score.items(): formattedScores.append("%s: %d" % (name, score)) self._msg( channel, "Game Over! %s is the Winner! Scores: %s " % (winner[0][0], ", ".join(formattedScores)), )
def hint(self): if not self.active or self.correct: return try: schedule.removeEvent("event_%s" % self.channel) except: pass self.lastHint = self.currentHint if self.hints <= self.numHints and self.hints > 0 and self.numHints > 0: ans = self.a[0] self.show.setdefault(self.id, None) self.revealed.setdefault(self.id, None) hintPercentage = self.registryValue("hintPercentage", self.channel) divider = round(self.divider * hintPercentage) self.divider -= divider if not self.show[self.id]: self.show[self.id] = list(self.blank) if not self.revealed[self.id]: self.revealed[self.id] = list( range(len(self.show[self.id]))) i = 0 while i < divider and len(self.revealed[self.id]) > 1: try: rand = self.revealed[self.id].pop( random.randint(0, len(self.revealed[self.id])) - 1) if self.show[self.id][rand] == self.blankChar: self.show[self.id][rand] = list(ans)[rand] i += 1 except: break self.currentHint = "".join(self.show[self.id]) if self.hints > 0 and self.lastHint != self.currentHint: self.p -= int(round(self.p * self.reduction, -1)) if self.points > self.p: points = self.p else: points = None if self.timeout > 0: timeLeft = str(round(self.endTime - time.time())).zfill( len(str(self.timeout))) reply = self.hint_template.render(hint=self.currentHint, time=timeLeft, points=points) if self.showHints or self.showTime: def event(): self.timedEvent() eventTime = time.time() + self.waitTime if eventTime < self.endTime: schedule.addEvent(event, eventTime, "event_%s" % self.channel) else: reply = self.hint_template.render(hint=self.currentHint, time=None, points=points) self.reply(reply) self.hints += 1
def newquestion(self): if not self.active: return self.clear() inactiveShutoff = self.registryValue("inactiveShutoff", self.channel) if (self.num == 0 or self.answered == self.total or self.numAsked == self.total): self.stop() return elif self.unanswered > inactiveShutoff and inactiveShutoff > 0: self.reply( "Seems like no one's playing any more. Jeopardy! stopped.") self.stop() return elif len(self.questions) == 0: self.reply("Oops! I ran out of questions!") self.stop() return self.show = {} self.revealed = {} self.id = None self.hints = 0 self.shown = 0 self.num -= 1 self.numAsked += 1 q = self.questions.pop(len(self.questions) - 1).split("|") question = {} self.id = q[0] question["airdate"] = q[1] self.p = int(q[2]) self.points = self.p question["category"] = q[3] question["clue"] = q[4] self.a = q[5] question["points"], question["number"], question["total"] = ( self.p, self.numAsked, self.total, ) self.question = self.question_template.render(question) self.a = re.sub(r"\(\d of\)", "", self.a) self.divider = round(len(re.sub("[^a-zA-Z0-9]+", "", self.a))) self.a = [self.a] self.blank = re.sub(r"\w", self.blankChar, self.a[0]) self.currentHint = self.blank if "(" in self.a[0]: a1, a2, a3 = re.match(r"(.*)\((.*)\)(.*)", self.a[0]).groups() self.a.append(a1 + a3) self.a.append(a2) if self.numAsked > 1 and self.delay > 0: delayTime = time.time() + self.delay def event(): self.next_question() schedule.addEvent(event, delayTime, "clue_%s" % self.channel) else: self.next_question()
def floodPunish(self, irc, msg, floodType, dummy = False): channel = msg.args[0] if (not irc.nick in irc.state.channels[channel].ops) and\ (not irc.nick in irc.state.channels[channel].halfops): self.log.warning("%s flooded in %s, but not opped.",\ msg.nick, channel) return if msg.nick in self.immunities: self.log.debug("Not punnishing %s, they are immune.", msg.nick) return if msg.nick in irc.state.channels[channel].ops or\ msg.nick in irc.state.channels[channel].halfops or\ msg.nick in irc.state.channels[channel].voices: self.log.debug("%s flooded in %s. But"\ + " I will not punish them because they have"\ + " special access.", msg.nick, channel) return if ircdb.checkCapability(msg.prefix, 'trusted') or\ ircdb.checkCapability(msg.prefix, 'admin') or\ ircdb.checkCapability(msg.prefix, channel + ',op'): self.log.debug("%s flooded in %s. But"\ + " I will not punish them because they are"\ + " trusted.", msg.nick, channel) return if msg.host in self.offenses and self.offenses[msg.host] > 2: hostmask = irc.state.nickToHostmask(msg.nick) banmaskstyle = conf.supybot.protocols.irc.banmask banmask = banmaskstyle.makeBanmask(hostmask) if not dummy: irc.queueMsg(ircmsgs.ban(channel, banmask)) self.log.warning("Banned %s (%s) from %s for repeated"\ + " flooding.", banmask, msg.nick, channel) reason = floodType + " flood detected." if floodType == "Paste": reason += " Use a pastebin like pastebin.ubuntu.com or gist.github.com." if not dummy: irc.queueMsg(ircmsgs.kick(channel, msg.nick, reason)) self.log.warning("Kicked %s from %s for %s flooding.",\ msg.nick, channel, floodType) # Don't schedule the same nick twice if not (msg.host in self.offenses): schedule.addEvent(self.clearOffenses, time.time()+300, args=[msg.host]) self.offenses[msg.host] = 0 # Incremented below self.offenses[msg.host] += 1 self.immunities[msg.nick] = True schedule.addEvent(self.unImmunify, time.time()+3, args=[msg.nick])
def doBan(): irc.queueMsg(ircmsgs.ban(channel, banmask)) if expiry > 0: def f(): if channel in irc.state.channels and \ banmask in irc.state.channels[channel].bans: irc.queueMsg(ircmsgs.unban(channel, banmask)) schedule.addEvent(f, expiry)
def listCats(): self.catsjoining = False irc.reply('Users in this round: %s' % ', '.join(self.players.keys()), prefixNick=False) irc.reply('For this round, the categories are...', prefixNick=False) self.gamecard = filter(None, random.choice(self.gamecards).splitlines()) for x in self.gamecard: irc.reply(x, prefixNick=False) schedule.addEvent(chooseLetter, time.time() + 5)
def saveLast(self, irc, msg, match): r""".+""" channel = msg.args[0] try: self.buffer[channel] except: self.buffer[channel] = [] # Stuff for multikick if channel in self.kickuser: for each in self.kickuser[channel]: if (each in msg.nick.lower() and not self.kickuser[channel][each]['num'] <= 0): irc.queueMsg(ircmsgs.ban(msg.args[0], msg.nick)) irc.queueMsg( ircmsgs.kick( msg.args[0], msg.nick, '{0}'.format( self.kickuser[channel][each]['msg'].replace( '#n', str(self.kickuser[channel][each] ['num']))))) self.kickuser[channel][each]['num'] -= 1 def un(): irc.queueMsg(ircmsgs.unban(msg.args[0], msg.nick)) schedule.addEvent(un, time.time() + random.randint(10, 60)) # 30,120 # END line = match.group(0).replace("\x01ACTION", "*").strip("\x01") if msg.nick.lower() in self.annoyUser: def fu(): self._notice( irc, msg.nick, "\x02\x03{0},{1}{2}".format(random.randint(0, 15), random.randint(0, 15), line)) schedule.addEvent(fu, time.time() + random.randint(2, 60)) if re.match(r"^u[/].*[/].*[/].*$", match.group(0)) \ or re.match(r"^s[/].*[/].*$", match.group(0)): return 1 self.buffer[channel].insert(0, [msg.nick, line]) if len(self.buffer[channel]) > self.buffsize: self.buffer[channel].pop(self.buffsize) return 1
def _schedule_next_event(self): period = self.registryValue('pollPeriod') if period > 0: if not self.fetcher or not self.fetcher.isAlive(): self.fetcher = GitFetcher(self.repository_list, period) self.fetcher.start() schedule.addEvent(self._poll, time.time() + period, name=self.name()) else: self._stop_polling()
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)
def act (self, irc, msg, channel, command, owner): tokens = callbacks.tokenize(command) msg.command = 'PRIVMSG' (n,i,h) = ircutils.splitHostmask(owner) msg.prefix = ircutils.joinHostmask(irc.nick,i,h) def d(): self.Proxy(irc.irc, msg, tokens) # Wait 30 seconds before sending PM schedule.addEvent(d,time.time()+30)
def schedule_msg(msg, dismiss): def f(): if not dismiss(): irc.queueMsg(msg) else: self.log.info('Dismissing auto-mode for %s.', msg.args[2]) delay = self.registryValue('delay', channel, network) if delay: schedule.addEvent(f, time.time() + delay) else: f()
def doBan(): if irc.state.channels[channel].isOp(bannedNick): irc.queueMsg(ircmsgs.deop(channel, bannedNick)) irc.queueMsg(ircmsgs.ban(channel, banmask)) irc.queueMsg(ircmsgs.kick(channel, bannedNick, reason)) if expiry > 0: def f(): if channel in irc.state.channels and \ banmask in irc.state.channels[channel].bans: irc.queueMsg(ircmsgs.unban(channel, banmask)) schedule.addEvent(f, expiry)
def doPrivmsg(self, irc, msg): """This is called everytime an IRC message is recieved.""" (recipients, text) = msg.args for channel in recipients.split(','): if irc.isChannel(channel): enable = self.registryValue('enable', channel=channel) if not enable: return maxKick = self.registryValue('maxKick', channel=channel) self.queueKick.enqueue(msg) if self.queueKick.len(msg) > 4: #self.queueKick.reset(msg) self.queueBan.enqueue(msg) maxKickBeforeBan = self.registryValue('maxKickToBan', channel=channel) reason = self.registryValue('reasonKick', channel=channel) if self.queueBan.len(msg) > maxKickBeforeBan: #self.queueBan.reset(msg) self.queueLongBan.enqueue(msg) maxBanToLongBan = self.registryValue('maxBanToLongBan', channel=channel) duration = int(0) if self.queueLongBan.len(msg) > maxBanToLongBan: #self.queueLongBan.reset(msg) duration = int( self.registryValue('durationLongBan', channel=channel)) else: duration = int( self.registryValue('durationBan', channel=channel)) hostmask = irc.state.nickToHostmask(msg.nick) (nick, user, host) = ircutils.splitHostmask(hostmask) banmask = ircutils.joinHostmask('*', '*', host) irc.sendMsg(ircmsgs.ban(channel, banmask)) if duration > 0: def ub(): if channel in irc.state.channels and banmask in irc.state.channels[ channel].bans: irc.queueMsg( ircmsgs.unban(channel, banmask)) schedule.addEvent(ub, time.time() + duration) reason = self.registryValue('reasonBan', channel=channel) # reason = reason % utils.timeElapsed(duration) # irc.sendMsg(ircmsgs.IrcMsg('remove %s %s : %s' % (channel, msg.nick, reason))) irc.reply('remove %s %s : %s' % (channel, msg.nick, reason)) self.log.info('remove %s %s : %s' % (channel, msg.nick, reason)) irc.sendMsg(ircmsgs.kick(channel, msg.nick, reason))