示例#1
0
    def doJoin(self, irc, msg):
        channel = msg.args[0]
        if self.registryValue('enabled', channel):
            if not ircutils.strEqual(irc.nick, msg.nick):
                irc = callbacks.SimpleProxy(irc, msg)

                now = time.time()
                throttle = self.registryValue('throttle', channel)
                if now - self.lastBacklog.get((channel, msg.nick), now-1-throttle) < throttle:
                    return
                else:
                    self.lastBacklog[channel, msg.nick] = now
                
                try:    
                    lines = int(self.db["1337allthechannels1337", msg.nick])
                except:
                    lines = int(self.registryValue('lines'))
                    
                if lines != 0:
                    irc.queueMsg(ircmsgs.notice(msg.nick, "Hello "+msg.nick+". I will now show you up to "+str(lines)+" messages from "+channel+", before you joined. To change this behavior, write me: @setbackloglines [0-25]. Setting it to zero disables this feature. Time is GMT."))
                    logg = self.logck.get(channel, lines)
                    for i in range(0, lines):
                        if len(logg) <= 0: 
                            break;
                        else:
                            irc.queueMsg(ircmsgs.notice(msg.nick,str((logg[:1]).pop())))
                            logg = logg[1:]


            self.doLog(irc, channel, '*** %s <%s> has joined %s', msg.nick, msg.prefix, channel)
示例#2
0
 def testReply(self):
     irc = getTestIrc()
     prefix = 'foo!bar@baz'
     channelMsg = ircmsgs.privmsg('#foo', 'bar baz', prefix=prefix)
     nonChannelMsg = ircmsgs.privmsg('supybot', 'bar baz', prefix=prefix)
     irc._tagMsg(channelMsg)
     irc._tagMsg(nonChannelMsg)
     self.assertEqual(
         ircmsgs.notice(nonChannelMsg.nick, 'foo'),
         callbacks._makeReply(irc, channelMsg, 'foo', private=True))
     self.assertEqual(ircmsgs.notice(nonChannelMsg.nick, 'foo'),
                      callbacks._makeReply(irc, nonChannelMsg, 'foo'))
     self.assertEqual(
         ircmsgs.privmsg(channelMsg.args[0], '%s: foo' % channelMsg.nick),
         callbacks._makeReply(irc, channelMsg, 'foo'))
     self.assertEqual(
         ircmsgs.privmsg(channelMsg.args[0], 'foo'),
         callbacks._makeReply(irc, channelMsg, 'foo', prefixNick=False))
     self.assertEqual(
         ircmsgs.notice(nonChannelMsg.nick, 'foo'),
         callbacks._makeReply(irc,
                              channelMsg,
                              'foo',
                              notice=True,
                              private=True))
示例#3
0
 def wtp(self, irc, msg, args):
     """Best place."""
     coms = ['EN', 'BR', 'FR', 'TR', 'RU', 'ES', 'CN', 'VK', 'NL', 'PL', 'HU', 'RO', 'ID', 'DE']
     room = random.randint(1,10)
     mice = random.randint(1,35)
     com = random.choice(coms)
     if mice == 1:
         irc.sendMsg(ircmsgs.notice(msg.nick, "Based on the gathered server, room, and player statistics, you're best off playing in room %s on %s, despite the presence of 1 mice." % (room, com)))
     else:
         irc.sendMsg(ircmsgs.notice(msg.nick, "Based on the gathered server, room, and player statistics, you're best off playing in room %s on %s, despite the presence of %s mice." % (room, com, mice)))
示例#4
0
文件: plugin.py 项目: kg-bot/SupyBot
    def botlist(self, irc, msg, args):
        """takes no arguments

        Sends notice to you with list of our bot"""
        global channel
        channel = msg.args[0]
        global nick
        nick = msg.nick
        if channel == '#bots':
            with open('Bots/%s.json' % 'botlist', 'r') as bots:
                b = json.loads(bots.read())
                bot_names = ', '.join(v for v in b)
                irc.queueMsg(ircmsgs.notice(nick, bot_names))
        else:
            irc.queueMsg(ircmsgs.notice(nick, "This command is available only on #bots channel"))
示例#5
0
 def testReply(self):
     prefix = "foo!bar@baz"
     channelMsg = ircmsgs.privmsg("#foo", "bar baz", prefix=prefix)
     nonChannelMsg = ircmsgs.privmsg("supybot", "bar baz", prefix=prefix)
     self.assertEqual(ircmsgs.notice(nonChannelMsg.nick, "foo"), callbacks.reply(channelMsg, "foo", private=True))
     self.assertEqual(ircmsgs.notice(nonChannelMsg.nick, "foo"), callbacks.reply(nonChannelMsg, "foo"))
     self.assertEqual(
         ircmsgs.privmsg(channelMsg.args[0], "%s: foo" % channelMsg.nick), callbacks.reply(channelMsg, "foo")
     )
     self.assertEqual(
         ircmsgs.privmsg(channelMsg.args[0], "foo"), callbacks.reply(channelMsg, "foo", prefixNick=False)
     )
     self.assertEqual(
         ircmsgs.notice(nonChannelMsg.nick, "foo"), callbacks.reply(channelMsg, "foo", notice=True, private=True)
     )
示例#6
0
 def onlinehelpers(self, irc, msg, args, type):
     """Returns online helpers list."""
     try:
         req = urllib2.Request('http://www.aha2y.nl/API/transformice/online_helpers.php')
         response = urllib2.urlopen(req)
         modlist = response.read()
         if type:
             if type == "--verbose":
                 irc.reply(modlist, prefixNick=False)
             else:
                 irc.sendMsg(ircmsgs.notice(msg.nick, "Incorrect usage."))
         else:
             irc.sendMsg(ircmsgs.notice(msg.nick, modlist))
     except urllib2.HTTPError, err:
         irc.sendMsg(ircmsgs.notice(msg.nick, "Error: the API seems to be down. Please try again later."))
示例#7
0
 def testReply(self):
     prefix = 'foo!bar@baz'
     channelMsg = ircmsgs.privmsg('#foo', 'bar baz', prefix=prefix)
     nonChannelMsg = ircmsgs.privmsg('supybot', 'bar baz', prefix=prefix)
     self.assertEqual(ircmsgs.notice(nonChannelMsg.nick, 'foo'),
                      callbacks.reply(channelMsg, 'foo', private=True))
     self.assertEqual(ircmsgs.notice(nonChannelMsg.nick, 'foo'),
                      callbacks.reply(nonChannelMsg, 'foo'))
     self.assertEqual(
         ircmsgs.privmsg(channelMsg.args[0], '%s: foo' % channelMsg.nick),
         callbacks.reply(channelMsg, 'foo'))
     self.assertEqual(ircmsgs.privmsg(channelMsg.args[0], 'foo'),
                      callbacks.reply(channelMsg, 'foo', prefixNick=False))
     self.assertEqual(
         ircmsgs.notice(nonChannelMsg.nick, 'foo'),
         callbacks.reply(channelMsg, 'foo', notice=True, private=True))
示例#8
0
 def onlinemods(self, irc, msg, args):
     """Returns online moderator list."""
     try:
         web = urllib.urlopen("http://cheese.formice.com/online-mods")
         s = web.read()
     except urllib2.HTTPError, err:
         irc.sendMsg(ircmsgs.notice(msg.nick, "Error: the API seems to be down. Please try again later."))
示例#9
0
 def doPrivmsg(self, irc, msg):
     if irc.isChannel(msg.args[0]):
         (tgt, payload) = msg.args
         if tgt in self.channels:
             for line in self._processLine(self.channels[tgt], payload):
                 irc.queueMsg(ircmsgs.notice(tgt, line.encode('utf-8')))
                 irc.noReply()
示例#10
0
 def doPrivmsg(self, irc, msg):
     if irc.isChannel(msg.args[0]):
         (tgt, payload) = msg.args
         if tgt in self.channels:
             for line in self._processLine(self.channels[tgt], payload):
                 irc.queueMsg(ircmsgs.notice(tgt, line.encode('utf-8')))
                 irc.noReply()
示例#11
0
 def testPersistentCache(self):
     """Save pending reviews and when bans were last checked. This is needed for plugin
     reloads"""
     msg1 = ircmsgs.privmsg('nick', 'Hello World')
     msg2 = ircmsgs.privmsg(
         'nick', 'Hello World')  # duplicate msg, should be ignored
     msg2 = ircmsgs.privmsg('nick', 'Hello World2')
     msg3 = ircmsgs.notice('#chan', 'Hello World')
     msg4 = ircmsgs.privmsg('nick_', 'Hello World')
     pr = self.getCallback().pendingReviews
     pr['host.net'] = [('op', msg1), ('op', msg2), ('op_', msg3)]
     pr['home.net'] = [('dude', msg4)]
     self.assertResponse('banreview',
                         'Pending ban reviews (4): op_:1 dude:1 op:2')
     pr.close()
     pr.clear()
     pr.open()
     self.assertResponse('banreview',
                         'Pending ban reviews (4): op_:1 dude:1 op:2')
     items = pr['host.net']
     self.assertTrue(items[0][0] == 'op' and items[0][1] == msg1)
     self.assertTrue(items[1][0] == 'op' and items[1][1] == msg2)
     self.assertTrue(items[2][0] == 'op_' and items[2][1] == msg3)
     items = pr['home.net']
     self.assertTrue(items[0][0] == 'dude' and items[0][1] == msg4)
示例#12
0
 def _msgmaker(self, target, s):
     msg = dynamic.msg
     channel = dynamic.channel
     if self.registryValue("noticeNonPrivmsgs", dynamic.channel) and msg.command != "PRIVMSG":
         return ircmsgs.notice(target, s)
     else:
         return ircmsgs.privmsg(target, s)
示例#13
0
 def listener_thread(self):
     ''' Take messages from process, write them to irc.'''
     while not self.listen_abort:
         try:
             if not self.pipe[1].poll(0.5):
                 continue
             msg, channels = self.pipe[1].recv()
             for channel in channels:
                 for irc in world.ircs:
                     if channel in irc.state.channels:
                         if self.config.topic_regex:
                             self.replace_topic(irc, channel,
                                                self.config.topic_regex, msg)
                         elif self.config.privmsg:
                             irc.queueMsg(ircmsgs.privmsg(channel, msg))
                         else:
                             irc.queueMsg(ircmsgs.notice(channel, msg))
                     else:
                         self.log.warning(
                             "Can't write to non-joined channel: " + channel)
         except EOFError:
             self.listen_abort = True
         except Exception:
             self.log.debug("LISTEN: Exception", exc_info = True)
             self.listen_abort = True
     self.log.debug("LISTEN: exiting")
 def testReplyTo(self):
     prefix = 'foo!bar@baz'
     msg = ircmsgs.privmsg('#foo', 'bar baz', prefix=prefix)
     self.assertEqual(callbacks.reply(msg, 'blah', to='blah'),
                      ircmsgs.privmsg('#foo', 'blah: blah'))
     self.assertEqual(callbacks.reply(msg, 'blah', to='blah', private=True),
                      ircmsgs.notice('blah', 'blah'))
示例#15
0
 def send(s):
     if not relay.hasTargetIRC:
         self.log.info('LinkRelay:  IRC %s not yet scraped.' %
                       relay.targetNetwork)
     elif relay.targetIRC.zombie:
         self.log.info('LinkRelay:  IRC %s appears to be a zombie'%
                       relay.targetNetwork)
     elif relay.targetChannel not in relay.targetIRC.state.channels:
         self.log.info('LinkRelay:  I\'m not in in %s on %s' %
                       (relay.targetChannel, relay.targetNetwork))
     else:
         if 'network' not in args:
             if self.registryValue('includeNetwork', relay.targetChannel):
                 args['network'] = '@' + irc.network
             else:
                 args['network'] = ''
         s %= args
         if isPrivmsg or \
                 self.registryValue('nonPrivmsgs', channel) == 'privmsg':
             msg = ircmsgs.privmsg(relay.targetChannel, s)
         elif self.registryValue('nonPrivmsgs', channel) == 'notice':
             msg = ircmsgs.notice(relay.targetChannel, s)
         else:
             return
         msg.tag('relayedMsg')
         relay.targetIRC.sendMsg(msg)
示例#16
0
    def doJoin(self, irc, msg):
        nick = ircutils.toLower(msg.nick)
        if len(msg.args) < 2:
            # extended-join is not supported
            return
        channel = msg.args[0].split(',')[0]
        account = msg.args[1]
        if ircutils.strEqual(irc.nick, msg.nick):
            # message from self
            return
        if 'batch' in msg.server_tags and \
                msg.server_tags['batch'] in irc.state.batches and \
                irc.state.batches[msg.server_tags['batch']].type == 'netjoin':
            # ignore netjoin
            return
        if not ircutils.isChannel(
                channel) or channel not in irc.state.channels:
            return
        if not self.registryValue('enabled', channel):
            return

        if account == '*':
            irc.queueMsg(
                ircmsgs.notice(
                    nick,
                    'You joined {}, but you are not identified to services and cannot speak.'
                    ' For help with identification, type "/msg nickserv help register"'
                    .format(channel)))
示例#17
0
文件: plugin.py 项目: kg-bot/SupyBot
 def doPrivmsg(self, irc, msg):
     nick = msg.nick
     channel = msg.args[0]
     message = msg.args[1]
     if channel == '#e-sim.secura.support':
         nicks = ', '.join(irc.state.channels['#e-sim.secura.support'].users)
         if nick in nicks:
             if message == '!rules':
                 irc.reply('You can use following arguments: \x034acc, bots, bugs, exploiting, password, trading, hts, pi, tat, eps, sp, f, responsibility, spam\x03 = For example: \x034+rules acc\x03')
             if message == '!commands':
                 irc.reply('>>> \x02Commands\x02: = \x02!rules\x02 & \x02!ts\x02 & \x02!ts help\x02 & \x02!wiki\x02 & \x02!ip form\x02 & \x02!forum\x02 & \x02!esim laws\x02')
             if message == '!ts':
                 irc.reply('http://tickets.e-sim.org/')
             if message == '!ts help':
                 irc.reply('http://secura.e-sim.org/article.html?id=16595')
             if message == '!wiki':
                 irc.reply('http://wiki.e-sim.org/index.php/Category:Tutorials')
             if message == '!ip form':
                 irc.reply('http://tinyurl.com/d9e23a')
             if message == '!forum':
                 irc.reply('http://forum.e-sim.org/')
             if message == '!esim laws':
                 irc.reply('http://secura.e-sim.org/laws.html')
         if channel != '#e-sim.secura.support':
             irc.queueMsg(ircmsgs.notice(nick, "This command is available only on one channel, this channel is set to +s (secret) and I'm not going to tell you channel name, sorry."))
示例#18
0
 def receivedCommand(self, data):
     """Received a command over the UDP wire."""
     error = None
     commanditems = data.split()
     if len(commanditems) > 2:
         network = commanditems.pop(0)
         channel = commanditems.pop(0)
         text = ' '.join(commanditems)
         netfound = False
         for irc in world.ircs:
             if irc.network == network:
                 netfound = True
                 chanfound = False
                 for onchannel in irc.state.channels:
                     if channel == onchannel[1:]:
                         chanfound = True
                         m = ircmsgs.notice(onchannel, text)
                         irc.sendMsg(m)
                 if not chanfound:
                     error = 'Bad Channel "%s"' % channel
         if not netfound:
             error = 'Bad Network "%s"' % network
     if error:
         self.log.info('Attempted external notice: %s', error)
     else:
         self.log.info('Successful external notice')
示例#19
0
 def doPrivmsg(self, irc, msg):
     if irc.isChannel(msg.args[0]):
         (tgt, payload) = msg.args
         for p in self.providers:
             for line in self.providers[p].doPrivmsg(tgt, payload):
                 irc.queueMsg(ircmsgs.notice(tgt, line.encode('utf-8')))
                 irc.noReply()
示例#20
0
 def _msgmaker(self, target, network, s):
     msg = dynamic.msg
     if self.registryValue('noticeNonPrivmsgs', target, network) and \
        msg.command != 'PRIVMSG':
         return ircmsgs.notice(target, s)
     else:
         return ircmsgs.privmsg(target, s)
示例#21
0
 def testReplyTo(self):
     prefix = 'foo!bar@baz'
     msg = ircmsgs.privmsg('#foo', 'bar baz', prefix=prefix)
     self.assertEqual(callbacks.reply(msg, 'blah', to='blah'),
                      ircmsgs.privmsg('#foo', 'blah: blah'))
     self.assertEqual(callbacks.reply(msg, 'blah', to='blah', private=True),
                      ircmsgs.notice('blah', 'blah'))
示例#22
0
    def rpm(self, irc, msg, args, remoteuser, otherIrc, text):
        """<remoteUser> <network> <text>

        Sends a private message to a user on a remote network."""
        found = found2 = False
        if not self.registryValue("remotepm.enable"):
            irc.error("This command is not enabled; please set 'config plugins.relaylink.remotepm.enable' "
                "to True.", Raise=True)
        for relay in self.relays:
            channels = otherIrc.state.channels
            for key, channel_ in channels.items():
                if ircutils.toLower(relay.targetChannel) \
                    == ircutils.toLower(key) and remoteuser in channel_.users:
                    found = True
                    break
            for ch in irc.state.channels:
                if ircutils.toLower(relay.sourceChannel) == \
                    ircutils.toLower(ch) and msg.nick in irc.state.channels[ch].users:
                    found2 = True
                    break
        if found and found2:
            prefix = msg.prefix if self.registryValue("remotepm.useHostmasks") else msg.nick
            if self.registryValue("remotepm.useNotice"):
                otherIrc.queueMsg(ircmsgs.notice(remoteuser, "Message from %s on %s: %s" % (prefix, irc.network, text)))
            else:
                otherIrc.queueMsg(ircmsgs.privmsg(remoteuser, "Message from %s on %s: %s" % (prefix, irc.network, text)))
        else:
            irc.error("User '%s' does not exist on %s or you are not sharing "
                "a channel with them." % (remoteuser, otherIrc.network), Raise=True)
示例#23
0
 def versioncheck(self, irc, msg, args=None, nick=None):
     """[<nick>]
     
     Checks the cjdns version of <nick>, or your nick if no args are given."""
     host = None
     if nick is not None and args is not None:
         if nick in irc.state.nicksToHostmasks:
             hostmask = irc.state.nicksToHostmasks[nick]
             host = hostmask.split("@")[-1]
         else:
             irc.error("Can't find user %s" % nick)
     else:
         host = msg.host
     if host is not None:
         if nick is None:
             nick = msg.nick
         cjdns = cjdnsadmin.connectWithAdminInfo()
         ping = cjdns.RouterModule_pingNode(host)
         if "version" in ping:
             version = ping['version']
             if not version in self.versions:
                 github = requests.get("https://api.github.com/repos/cjdelisle/cjdns/commits/%s" % version).json()
                 self.versions[version] = datetime.strptime(github['commit']['author']['date'], "%Y-%m-%dT%H:%M:%SZ")
             if self.versions[version] > self.latest['time']:
                 github = requests.get("https://api.github.com/repos/cjdelisle/cjdns/commits").json()
                 self.latest = {
                     "time": datetime.strptime(github[0]['commit']['author']['date'], "%Y-%m-%dT%H:%M:%SZ"),
                     "sha": github[0]['sha']
                     }
                 for version in github:
                     self.versions[version['sha']] = datetime.strptime(version['commit']['author']['date'])
             committime = self.versions[version]
             hostmask = "%s!%s@%s" % (msg.nick, msg.user, msg.host)
             if version != self.latest['sha']:
                 if datetime.now() - committime > timedelta(weeks=4):
                     sendNotice = True
                     if hostmask not in self.recentnotices:
                         self.recentnotices[hostmask] = datetime.now()
                     else:
                         if datetime.now() - self.recentnotices[hostmask] < timedelta(hours=6):
                             sendNotice = False
                     if sendNotice:
                         self.log.info("%s is running a commit from %s" % (msg.nick, pretty.date(committime)))
                         irc.queueMsg(ircmsgs.privmsg("#hyperboria", "%s is running an old version of cjdns! Using a commit from %s, by the looks of it. You really ought to update." % (msg.nick, pretty.date(committime))))
                 elif datetime.now() - committime > timedelta(weeks=2):
                     sendNotice = True
                     if hostmask not in self.recentnotices:
                         self.recentnotices[hostmask] = datetime.now()
                     else:
                         if datetime.now() - self.recentnotices[hostmask] < timedelta(hours=6):
                             sendNotice = False
                     if sendNotice:
                         self.log.info("%s is running a commit from %s" % (msg.nick, pretty.date(committime)))
                         irc.queueMsg(ircmsgs.notice(msg.nick, "You're running an old version of cjdns! Using a commit from %s, by the looks of it. You really ought to update." % pretty.date(committime)))
             elif args is not None:
                 irc.reply("%s is up to date" % nick)
                 irc.reply("%s is running %s (from %s)" % (nick, version, pretty.date(committime)))
         elif "error" in ping and args is not None:
             irc.reply("Error checking version of %s: %s" % (host, ping['error']))
示例#24
0
 def _send(self, irc, identifier, channel, text):
     if self.registryValue('bold'):
         identifier = ircutils.bold(identifier)
     notice = self.registryValue('notice')
     if notice:
         irc.queueMsg(ircmsgs.notice(channel, "%s: %s" % (identifier, text)))
     else:
         irc.queueMsg(ircmsgs.privmsg(channel, "%s: %s" % (identifier, text)))
示例#25
0
 def announce_entry(self, irc, channel, feed, entry):
     if self.should_send_entry(channel, entry):
         s = self.format_entry(channel, feed, entry, True)
         if self.registryValue('notice', channel):
             m = ircmsgs.notice(channel, s)
         else:
             m = ircmsgs.privmsg(channel, s)
         irc.queueMsg(m)
 def testReply(self):
     prefix = 'foo!bar@baz'
     channelMsg = ircmsgs.privmsg('#foo', 'bar baz', prefix=prefix)
     nonChannelMsg = ircmsgs.privmsg('supybot', 'bar baz', prefix=prefix)
     self.assertEqual(ircmsgs.notice(nonChannelMsg.nick, 'foo'),
                      callbacks.reply(channelMsg, 'foo', private=True))
     self.assertEqual(ircmsgs.notice(nonChannelMsg.nick, 'foo'),
                      callbacks.reply(nonChannelMsg, 'foo'))
     self.assertEqual(ircmsgs.privmsg(channelMsg.args[0],
                                      '%s: foo' % channelMsg.nick),
                      callbacks.reply(channelMsg, 'foo'))
     self.assertEqual(ircmsgs.privmsg(channelMsg.args[0],
                                      'foo'),
                      callbacks.reply(channelMsg, 'foo', prefixNick=False))
     self.assertEqual(ircmsgs.notice(nonChannelMsg.nick, 'foo'),
                      callbacks.reply(channelMsg, 'foo',
                                      notice=True, private=True))
示例#27
0
 def g(self, irc, msg, args, subject, message):
     """[@subject] <message>
     Sends a global notice / If '"@2+word subject" Some message' format is used, then subject allows multiple words."""
     caller = msg.nick
     subject = self.getSubject(subject)
     if subject != "":
         subject = "[%s] - " % (subject)
     irc.queueMsg(ircmsgs.notice("Global", "global %s%s (sent by %s)" % (subject, message, caller)))
示例#28
0
文件: plugin.py 项目: affix/Fedbot
 def deserialize(self, host, nick, command, channel, text):
     if command == 'PRIVMSG':
         msg = ircmsgs.privmsg(channel, text)
     elif command == 'NOTICE':
         msg = ircmsgs.notice(channel, text)
     else:
         return
     return (host, (nick, msg))
示例#29
0
 def doPrivmsg(self, irc, msg):
     if irc.isChannel(msg.args[0]):
         (tgt, payload) = msg.args
         for p in self.providers:
             for line in self.providers[p].doPrivmsg(tgt, payload):
                 assert isinstance(line, str)
                 irc.queueMsg(ircmsgs.notice(tgt, line))
                 irc.noReply()
示例#30
0
 def doJoin(self, irc, msg):
     channel = msg.args[0]
     nick = msg.nick
     if self.registryValue('channels', channel):
         mess = self.registryValue('mess', channel)
         irc.queueMsg(ircmsgs.notice(nick, mess))
         irc.noReply()
     else: return
示例#31
0
文件: plugin.py 项目: kg-bot/SupyBot
 def doJoin(self, irc, msg):
     t = msg.prefix
     nick_split = string.split(t, '!')
     nick = nick_split[0]
     big_nick = nick_split[0]
     channel = msg.args[0]
     if channel == '#bots':
         irc.queueMsg(ircmsgs.notice(nick, "Hello %s, welcome to \x02#BOTS\x02, type \x0310+botlist\x03 to see our available bots, and use \x0310+botdesc BOT-NAME\x03, to see description and info about some bot from \x0310+botlist\x03 list" % nick))
示例#32
0
 def announce_entry(self, irc, channel, feed, entry):
     if self.should_send_entry(channel, entry):
         s = self.format_entry(channel, feed, entry, True)
         if self.registryValue("notice", channel):
             m = ircmsgs.notice(channel, s)
         else:
             m = ircmsgs.privmsg(channel, s)
         irc.queueMsg(m)
示例#33
0
    def _gegen(self, irc, msg, target):
        if self._is_voting_enabled(irc, msg, reply=True) and self._check_privileges(irc, msg, reply=True):

            channel = msg.args[0]
            users = irc.state.channels[channel].users
            voting_id = self._calculate_id(target, channel)

            if target == msg.nick or target == irc.nick:
                if self._can_be_kicked(irc, channel, msg.nick):
                    irc.queueMsg(ircmsgs.kick(channel, msg.nick, "Snibeti snab XDD"))
                    self._user_left(irc, msg.nick, channel)
                    return

            if voting_id in self.running_votes:
                voting = self.running_votes[voting_id]
                if voting.add_vote(msg.nick):
                    voting_count = voting.count_votes(users)
                    if voting_count >= voting.threshold:
                        if target in irc.state.channels[channel].ops:
                            irc.queueMsg(ircmsgs.notice(channel, "Einen Versuch war's wert! :--D"))
                            for nick in voting.votes:
                                if self._can_be_kicked(irc, channel, nick):
                                    irc.queueMsg(ircmsgs.kick(channel, nick, "Bis zum nächsten mal!"))
                                    self._user_left(irc, nick, channel)
                        else:
                            self._remove_kebab(irc, channel, target)
                        del self.running_votes[voting_id]
                    else:
                        irc.reply("Stimme gegen %s registriert. Braucht noch %d weitere Stimme(n)." % (
                            target, voting.threshold - voting_count))
                else:
                    voting_count = voting.count_votes(users)
                    irc.reply("Du hast bereits gegen %s gestimmt! Braucht noch %d weitere Stimme(n)." % (
                        target, voting.threshold - voting_count))

            else:
                active_users = self._calculate_active_user(irc, msg)

                if target not in active_users:
                    irc.reply("%s ist inaktiv. Antrag abgelehnt." % target)
                    return

                voting_threshold = self._calculate_voting_threshold(irc, msg, active_users)
                voting = Voting(channel, target, msg.nick, voting_threshold)
                voting.add_vote(msg.nick)

                self.running_votes[voting_id] = voting

                def clean_up():
                    if voting_id in self.running_votes:
                        message = "Abstimmung gegen %s ist erfolglos ausgelaufen." % self.running_votes[voting_id].target
                        irc.queueMsg(ircmsgs.notice(channel, message))
                        del self.running_votes[voting_id]

                schedule.addEvent(clean_up, time.time() + int(self.registryValue("voting_timeout")))

                irc.reply("Abstimmung gegen %s gestartet. Braucht noch %d weitere Stimme(n)." % (
                    target, voting.threshold - 1))
示例#34
0
 def doJoin(self, irc, msg):
     user = ircutils.userFromHostmask(msg.prefix)
     if user == 'root' or user == '~root':
         channel = msg.args[0]
         s = self.registryValue('warning', channel)
         if self.registryValue('warn', channel):
             irc.queueMsg(ircmsgs.notice(msg.nick, s))
         if self.registryValue('kick', channel):
             irc.queueMsg(ircmsgs.kick(channel, msg.nick, s))
示例#35
0
文件: plugin.py 项目: kg-bot/SupyBot
 def doJoin(self, irc, msg):
     t = msg.prefix
     nick_split = string.split(t, '!')
     nick = nick_split[0]
     big_nick = nick_split[0]
     channel = msg.args[0]
     if channel == '#e-sim.secura.support':
         nicks = ', '.join(irc.state.channels['#e-sim.secura.support'].users)
         if nick in nicks:
             irc.queueMsg(ircmsgs.notice(nick, 'Hi, %s. State your issue and wait patiently.' % big_nick))
示例#36
0
 def testReplyTo(self):
     irc = getTestIrc()
     prefix = 'foo!bar@baz'
     msg = ircmsgs.privmsg('#foo', 'bar baz', prefix=prefix)
     irc._tagMsg(msg)
     self.assertEqual(callbacks._makeReply(irc, msg, 'blah', to='blah'),
                      ircmsgs.privmsg('#foo', 'blah: blah'))
     self.assertEqual(
         callbacks._makeReply(irc, msg, 'blah', to='blah', private=True),
         ircmsgs.notice('blah', 'blah'))
示例#37
0
 def _user_left(self, irc, nick, channel=None):
     for voting_id in list(self.running_votes):
         voting = self.running_votes[voting_id]
         if nick == voting.target:
             if (channel and channel == voting.channel) or not channel:
                 irc.queueMsg(ircmsgs.notice(voting.channel, "%s hat den Kanal vor Ende der Abstimmung verlassen." % voting.target))
                 self._remove_kebab(irc, voting.channel, nick)
                 del self.running_votes[voting_id]
         elif nick in voting.votes:
             voting.votes.remove(nick)
示例#38
0
文件: plugin.py 项目: kg-bot/SupyBot
    def botdesc(self, irc, msg, args, bot):
        """<bot>

        Gives description about <bot>"""
        if channel != '#bots':
            irc.queueMsg(ircmsgs.notice(nick, "This command is available only on #bots channel"))
        else:
            try:
                with open('/Bots/%s.json' % bot, 'r') as bots:
                    a = json.loads(bots.read())
                    bot_channel = a['channel']
                    bot_website = a['website']
                    bot_owner = a['owner']
                    bot_description = a['description']
                    if bot_website is None:
                        irc.queueMsg(ircmsgs.notice(nick, "\x033%s\x03's channel: \x02%s\x02, \x033%s\x03's owner: \x02%s\x02, \x033%s\x03's description: \x02%s\x02" % (bot, bot_channel, bot, bot_owner, bot, bot_description)))
                    else:
                        irc.queueMsg(ircmsgs.notice(nick, "\x033%s\x03's channel: \x02%s\x02, \x033%s\x03's website: \x02%s\x02 , \x033%s\x03's owner: \x02%s\x02, \x033%s\x03's description: \x02%s\x02" % (bot, bot_channel, bot, bot_website, bot, bot_owner, bot, bot_description)))
            except IOError:
                irc.queueMsg(ircmsgs.notice(nick, "\x033%s\x03 has no description yet, if this is your bot please ping \x034@OPerater\x03 on \x02#bots\x02 to add it" % bot))
示例#39
0
 def doPrivmsg(self, irc, msg):
     if irc.isChannel(msg.args[0]):
         (tgt, payload) = msg.args
         nick = msg.nick
         m = re.match('status:\s*(.*)', payload, re.IGNORECASE)
         if m is None: return
         if not self._checkAuthed(irc, nick):
             irc.error("You need to be in one of the authentication channels for your message to get recorded.  These are: %s"%(str(conf.supybot.plugins.GroupStatus.get('authChannel')),))
         else:
                 if self.db.add(irc, tgt, nick, m.group(1)):
                     irc.queueMsg(ircmsgs.notice(tgt, "Recording %s's status update at %s."%(nick, 'https://gs.torproject.org/')))
                 irc.noReply()
示例#40
0
文件: plugin.py 项目: kg-bot/SupyBot
    def getk(self, irc, msg, args):
        """takes no arguments

        Returns your Public and Private key"""
        try:
            with open('G:\\supybot\\RSA-keys\\%s-keys.json' % msg.nick, 'r') as pk:
                b = json.loads(pk.read())
            publ_key = b[pub_key]
            prive_key = b[priv_key]
            irc.queueMsg(ircmsgs.notice(msg.nick, "Your keys are: %s, %s" % (publ_key, prive_key)))
        except:
            irc.reply("You havent generated any Public Keys so far")
示例#41
0
    def _notify_channel(self, channel):
	''' Tell an individual channel about the change in status. '''
	debug('StatusHandler._notify_channel:', channel)
        if channel not in self.registryValue('quiet_channels'):
	    # If this channel is supposed to recieve updates.
            if self.registryValue('use_notice'):
	       # And it is supposed to get a /NOTICE rather than /PRIVMSG.
	       # Then send a notice.
               msg = ircmsgs.notice(channel, self.registryValue('message_default'))
            else:
	       # Otherwise just use a /PRIVMSG.
               msg = ircmsgs.privmsg(channel, self.registryValue('message_default'))
	    self.irc.queueMsg(msg)
示例#42
0
 def doPaste(self, irc, cname, nick, text, ip):
     date = time.time()
     pid = self.db.addPaste(poster=nick, post=text, ip=ip, date=date)
     self.mostrecent.append(pid)
     if len(self.mostrecent) > self.registryValue('recentPasteCount'):
         self.mostrecent.pop(0)
     if self.registryValue('announce'):
         url = '%s/%s/%s/PasteBin?view=%s' % \
             (conf.supybot.plugins.Webserver.rootURL().rstrip('/'),
                 irc.network, cname[1:], pid)
         mess = 'Pastebin: New paste by %s at %s' % \
             (nick, format('%u', url))
         m = ircmsgs.notice(cname, mess)
         irc.sendMsg(m)
     return pid
示例#43
0
    def testReplyStatusmsg(self):
        irc = getTestIrc()
        prefix = 'foo!bar@baz'
        msg = ircmsgs.privmsg('+#foo', 'bar baz', prefix=prefix)
        irc._tagMsg(msg)

        # No statusmsg set, so understood as being a private message, so
        # private reply
        self.assertEqual(ircmsgs.notice(msg.nick, 'foo'),
                         callbacks._makeReply(irc, msg, 'foo'))

        irc.state.supported['statusmsg'] = '+'
        msg = ircmsgs.privmsg('+#foo', 'bar baz', prefix=prefix)
        irc._tagMsg(msg)
        self.assertEqual(ircmsgs.privmsg('+#foo', '%s: foo' % msg.nick),
                         callbacks._makeReply(irc, msg, 'foo'))
示例#44
0
 def send():
     if not relay.hasTargetIRC:
         self.log.info('LinkRelay:  IRC %s not yet scraped.' %
                       relay.targetNetwork)
     elif relay.targetIRC.zombie:
         self.log.info('LinkRelay:  IRC %s appears to be a zombie' %
                       relay.targetNetwork)
     elif relay.targetChannel not in relay.targetIRC.state.channels:
         self.log.info('LinkRelay:  I\'m not in in %s on %s' %
                       (relay.targetChannel, relay.targetNetwork))
     else:
         if isPrivmsg or \
                 self.registryValue('nonPrivmsgs', channel) == 'privmsg':
             msg = ircmsgs.privmsg(relay.targetChannel, s)
         elif self.registryValue('nonPrivmsgs', channel) == 'notice':
             msg = ircmsgs.notice(relay.targetChannel, s)
         else:
             return
         msg.tag('relayedMsg')
         relay.targetIRC.sendMsg(msg)
示例#45
0
 def doPrivmsg(self, irc, msg):
     if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
         return
     if ircutils.isChannel(msg.args[0]) and self.registryValue(
             "resolve", msg.args[0]):
         if msg.args[1].find("twitter") != -1:
             status_id = self._get_status_id(msg.args[1], search=True)
             if status_id:
                 try:
                     api = self._get_twitter_api(msg)
                     tweet = api.get_status(status_id)
                     text = tweet.text.replace("\n", " ")
                     text = html.parser.HTMLParser().unescape(text)
                     message = "Tweet von @{}: {}".format(
                         tweet.user.screen_name, text)
                     message = ircutils.safeArgument(
                         message.encode('utf-8'))
                     irc.queueMsg(ircmsgs.notice(msg.args[0], message))
                 except tweepy.TweepError as e:
                     log.error("Twitter.doPrivmsg: {}".format(repr(e)))
                     return
示例#46
0
        def do(type, always=False):
            cap = ircdb.makeChannelCapability(channel, type)
            cap_auto = ircdb.makeChannelCapability(channel, 'auto'+type)
            try:
                apply_mode = ircdb.checkCapability(msg.prefix, cap,
                        ignoreOwner=not self.registryValue('owner'),
                        ignoreChannelOp=True, ignoreDefaultAllow=True)
            except KeyError:
                apply_mode = False
            if self.registryValue('alternativeCapabilities', channel):
                try:
                    override = ircdb.checkCapability(msg.prefix, cap_auto,
                            ignoreOwner=not self.registryValue('owner'),
                            ignoreChannelOp=True, ignoreDefaultAllow=True)
                except KeyError:
                    override = False
            else:
                override = False
            if apply_mode or override or always:
                if override or self.registryValue(type, channel):
                    self.log.info('Scheduling auto-%s of %s in %s.',
                                  type, msg.prefix, channel)
                    delay = str(self.registryValue('delay', channel))
                    notice = ircmsgs.notice(msg.nick, "Welcome! Please wait, I'll give you " + type + " in " + delay + " seconds.")
                    irc.sendMsg(notice) 

                    def dismiss():
                        """Determines whether or not a mode has already
                        been applied."""
                        l = getattr(irc.state.channels[channel], type+'s')
                        return (msg.nick in l)
                    msgmaker = getattr(ircmsgs, type)
                    schedule_msg(msgmaker(channel, msg.nick),
                            dismiss)
                    raise Continue # Even if fallthrough, let's only do one.
                elif not fallthrough:
                    self.log.debug('%s has %s, but supybot.plugins.AutoMode.%s'
                                   ' is not enabled in %s, refusing to fall '
                                   'through.', msg.prefix, cap, type, channel)
                    raise Continue
示例#47
0
 def handle(self):
     try:
         while True:
             line = self.rfile.readline()
             if not line:
                 break
             line = line.strip()
             (channel, text) = line.split(' ', 1)
             if not channel or not text:
                 continue
             if self.server.channel_states.get(channel, "on") == "on":
                 if self.server.registryValue('use_notice'):
                     msg = ircmsgs.notice(channel, text)
                 else:
                     msg = ircmsgs.privmsg(channel, text)
                 for irc in world.ircs:
                     if channel in irc.state.channels:
                         irc.queueMsg(msg)
     except BaseException as e:
         """In the future there should be specific exception
         handlers here. Until then we'll just print out the base
         one."""
         print e
示例#48
0
    def multikick(self, irc, msg, args, channel, nick, num, message):
        """<nick> <num> [message]

		Kicks <nick> every time [s]he talks up to <num> (max 10) times with [message]. Use #n to insert number of remaining kicks."""
        if not channel: channel = "#powder"
        try:
            num = int(num)
        except:
            irc.error("Non-numeric value given.")
            return 0
        if num > 10: num = 10
        nick = nick.lower()
        self.kickuser[nick] = {}
        self.kickuser[nick]['num'] = num
        if not message or message == "":
            message = "#n kick(s) remaining."
        self.kickuser[nick]['msg'] = message

        irc.queueMsg(
            ircmsgs.notice(
                msg.nick,
                ("Kicking anyone with {} in their nick {} times.".format(
                    nick, num))))
示例#49
0
 def _notice(self, recip, msg):
     self.irc.queueMsg(ircmsgs.notice(recip, msg))
示例#50
0
 def _reply(self, irc, msg, payload, s):
     if s:
         s = '\x01%s %s\x01' % (payload, s)
     else:
         s = '\x01%s\x01' % payload
     irc.queueMsg(ircmsgs.notice(msg.nick, s))
示例#51
0
 def testMsgKeywordHandledProperly(self):
     msg = ircmsgs.notice('foo', 'bar')
     msg2 = ircmsgs.IrcMsg(msg=msg, command='PRIVMSG')
     self.assertEqual(msg2.command, 'PRIVMSG')
     self.assertEqual(msg2.args, msg.args)
示例#52
0
文件: plugin.py 项目: affix/Fedbot
 def _sendForward(self, irc, s, channel=None):
     if not irc:
         return
     for chan in self.registryValue('request.forward.channels', channel=channel):
         msg = ircmsgs.notice(chan, s)
         irc.queueMsg(msg)
示例#53
0
 def versioncheck(self, irc, msg, args=None, nick=None):
     """[<nick>]
     
     Checks the cjdns version of <nick>, or your nick if no args are given."""
     host = None
     if nick is not None and args is not None:
         if nick in irc.state.nicksToHostmasks:
             hostmask = irc.state.nicksToHostmasks[nick]
             host = hostmask.split("@")[-1]
         else:
             irc.error("Can't find user %s" % nick)
     else:
         host = msg.host
     if host is not None:
         if nick is None:
             nick = msg.nick
         hostmask = "%s!%s@%s" % (msg.nick, msg.user, msg.host)
         sendNotice = True
         if hostmask not in self.recentnotices:
             self.recentnotices[hostmask] = datetime.now()
         else:
             if datetime.now() - self.recentnotices[hostmask] < timedelta(
                     hours=6):
                 sendNotice = False
         if sendNotice or args is not None:
             cjdns = cjdnsadmin.connectWithAdminInfo()
             ping = cjdns.RouterModule_pingNode(
                 host, self.registryValue('timeout'))
             if "version" in ping:
                 version = ping['version']
                 if not version in self.versions:
                     github = requests.get(
                         "https://api.github.com/repos/cjdelisle/cjdns/commits/%s"
                         % version).json()
                     self.versions[version] = datetime.strptime(
                         github['commit']['author']['date'],
                         "%Y-%m-%dT%H:%M:%SZ")
                 if self.versions[version] > self.latest['time']:
                     github = requests.get(
                         "https://api.github.com/repos/cjdelisle/cjdns/commits"
                     ).json()
                     self.latest = {
                         "time":
                         datetime.strptime(
                             github[0]['commit']['author']['date'],
                             "%Y-%m-%dT%H:%M:%SZ"),
                         "sha":
                         github[0]['sha']
                     }
                     for version in github:
                         self.versions[version['sha']] = datetime.strptime(
                             version['commit']['author']['date'])
                 committime = self.versions[version]
                 if version != self.latest['sha']:
                     if datetime.now() - committime > timedelta(weeks=4):
                         self.log.info("%s is running a commit from %s" %
                                       (msg.nick, pretty.date(committime)))
                         irc.queueMsg(
                             ircmsgs.privmsg(
                                 msg.args[0],
                                 "%s is running an old version of cjdns! Using a commit from %s, by the looks of it. You really ought to update."
                                 % (msg.nick, pretty.date(committime))))
                     elif datetime.now() - committime > timedelta(weeks=2):
                         self.log.info("%s is running a commit from %s" %
                                       (msg.nick, pretty.date(committime)))
                         irc.queueMsg(
                             ircmsgs.notice(
                                 msg.nick,
                                 "You're running an old version of cjdns! Using a commit from %s, by the looks of it. You really ought to update."
                                 % pretty.date(committime)))
                 elif args is not None:
                     irc.reply("%s is up to date" % nick)
                     irc.reply("%s is running %s (from %s)" %
                               (nick, version, pretty.date(committime)))
             elif "error" in ping and args is not None:
                 irc.reply("Error checking version of %s: %s" %
                           (host, ping['error']))
示例#54
0
class IrcMsgQueueTestCase(SupyTestCase):
    mode = ircmsgs.op('#foo', 'jemfinch')
    msg = ircmsgs.privmsg('#foo', 'hey, you')
    msgs = [ircmsgs.privmsg('#foo', str(i)) for i in range(10)]
    kick = ircmsgs.kick('#foo', 'PeterB')
    pong = ircmsgs.pong('123')
    ping = ircmsgs.ping('123')
    topic = ircmsgs.topic('#foo')
    notice = ircmsgs.notice('jemfinch', 'supybot here')
    join = ircmsgs.join('#foo')
    who = ircmsgs.who('#foo')

    def testInit(self):
        q = irclib.IrcMsgQueue([self.msg, self.topic, self.ping])
        self.assertEqual(len(q), 3)

    def testLen(self):
        q = irclib.IrcMsgQueue()
        q.enqueue(self.msg)
        self.assertEqual(len(q), 1)
        q.enqueue(self.mode)
        self.assertEqual(len(q), 2)
        q.enqueue(self.kick)
        self.assertEqual(len(q), 3)
        q.enqueue(self.topic)
        self.assertEqual(len(q), 4)
        q.dequeue()
        self.assertEqual(len(q), 3)
        q.dequeue()
        self.assertEqual(len(q), 2)
        q.dequeue()
        self.assertEqual(len(q), 1)
        q.dequeue()
        self.assertEqual(len(q), 0)

    def testContains(self):
        q = irclib.IrcMsgQueue()
        q.enqueue(self.msg)
        q.enqueue(self.msg)
        q.enqueue(self.msg)
        self.failUnless(self.msg in q)
        q.dequeue()
        self.failUnless(self.msg in q)
        q.dequeue()
        self.failUnless(self.msg in q)
        q.dequeue()
        self.failIf(self.msg in q)

    def testRepr(self):
        q = irclib.IrcMsgQueue()
        self.assertEqual(repr(q), 'IrcMsgQueue([])')
        q.enqueue(self.msg)
        try:
            repr(q)
        except Exception as e:
            self.fail('repr(q) raised an exception: %s' % utils.exnToString(e))

    def testEmpty(self):
        q = irclib.IrcMsgQueue()
        self.failIf(q)

    def testEnqueueDequeue(self):
        q = irclib.IrcMsgQueue()
        q.enqueue(self.msg)
        self.failUnless(q)
        self.assertEqual(self.msg, q.dequeue())
        self.failIf(q)
        q.enqueue(self.msg)
        q.enqueue(self.notice)
        self.assertEqual(self.msg, q.dequeue())
        self.assertEqual(self.notice, q.dequeue())
        for msg in self.msgs:
            q.enqueue(msg)
        for msg in self.msgs:
            self.assertEqual(msg, q.dequeue())

    def testPrioritizing(self):
        q = irclib.IrcMsgQueue()
        q.enqueue(self.msg)
        q.enqueue(self.mode)
        self.assertEqual(self.mode, q.dequeue())
        self.assertEqual(self.msg, q.dequeue())
        q.enqueue(self.msg)
        q.enqueue(self.kick)
        self.assertEqual(self.kick, q.dequeue())
        self.assertEqual(self.msg, q.dequeue())
        q.enqueue(self.ping)
        q.enqueue(self.msgs[0])
        q.enqueue(self.kick)
        q.enqueue(self.msgs[1])
        q.enqueue(self.mode)
        self.assertEqual(self.kick, q.dequeue())
        self.assertEqual(self.mode, q.dequeue())
        self.assertEqual(self.ping, q.dequeue())
        self.assertEqual(self.msgs[0], q.dequeue())
        self.assertEqual(self.msgs[1], q.dequeue())

    def testNoIdenticals(self):
        configVar = conf.supybot.protocols.irc.queuing.duplicates
        original = configVar()
        try:
            configVar.setValue(True)
            q = irclib.IrcMsgQueue()
            q.enqueue(self.msg)
            q.enqueue(self.msg)
            self.assertEqual(self.msg, q.dequeue())
            self.failIf(q)
        finally:
            configVar.setValue(original)

    def testJoinBeforeWho(self):
        q = irclib.IrcMsgQueue()
        q.enqueue(self.join)
        q.enqueue(self.who)
        self.assertEqual(self.join, q.dequeue())
        self.assertEqual(self.who, q.dequeue())


##         q.enqueue(self.who)
##         q.enqueue(self.join)
##         self.assertEqual(self.join, q.dequeue())
##         self.assertEqual(self.who, q.dequeue())

    def testTopicBeforePrivmsg(self):
        q = irclib.IrcMsgQueue()
        q.enqueue(self.msg)
        q.enqueue(self.topic)
        self.assertEqual(self.topic, q.dequeue())
        self.assertEqual(self.msg, q.dequeue())

    def testModeBeforePrivmsg(self):
        q = irclib.IrcMsgQueue()
        q.enqueue(self.msg)
        q.enqueue(self.mode)
        self.assertEqual(self.mode, q.dequeue())
        self.assertEqual(self.msg, q.dequeue())
        q.enqueue(self.mode)
        q.enqueue(self.msg)
        self.assertEqual(self.mode, q.dequeue())
        self.assertEqual(self.msg, q.dequeue())
示例#55
0
 def _send_message(self, channel, msg):
     if self.plugin.registryValue('use-notices', channel):
         announce_msg = ircmsgs.notice(channel, msg)
     else:
         announce_msg = ircmsgs.privmsg(channel, msg)
     self.irc.queueMsg(announce_msg)