def test_settz_create_and_update(self): self.bot.on_pubmsg( None, Event('pubmsg', NickMask('[email protected]'), '#test', ['.settz America/Chicago'])) self.bot.reply_to.assert_called_with( NickMask('[email protected]'), '#test', 'Your timezone has been set to America/Chicago') c = self.bot.db.cursor() c.execute('SELECT tz FROM tz_info WHERE nick = ?', ('test', )) tz, = next(c) assert tz == 'America/Chicago' self.bot.on_pubmsg( None, Event('pubmsg', NickMask('[email protected]'), '#test', ['.settz America/New_York'])) self.bot.reply_to.assert_called_with( NickMask('[email protected]'), '#test', 'Your timezone has been set to America/New_York') c = self.bot.db.cursor() c.execute('SELECT tz FROM tz_info WHERE nick = ?', ('test', )) tz, = next(c) assert tz == 'America/New_York'
def on_pubmsg(self, conn, event): if event.target in self.channels: is_oper = False # event.source is like '[email protected]' assert event.source.count('!') == 1 user = NickMask(event.source).nick # Don't respond to other create bots to avoid loops if user.startswith('create'): return if user in self.channels[event.target].opers(): is_oper = True assert len(event.arguments) == 1 raw_text = event.arguments[0] def respond(raw_text, ping=True): fmt = '{user}: {raw_text}' if ping else '{raw_text}' full_raw_text = fmt.format(user=user, raw_text=raw_text) self.say(event.target, full_raw_text) was_mentioned = raw_text.startswith((IRC_NICKNAME + ' ', IRC_NICKNAME + ': ')) for listener in self.listeners: text = raw_text if listener.require_mention: if was_mentioned: # Chop off the bot nickname. text = text.split(' ', 1)[1] else: continue if ( (listener.require_oper or listener.require_privileged_oper) and not is_oper ): continue # Prevent people from creating a channel, becoming oper, # inviting the bot, and approving/rejecting accounts without # "real" oper privilege. if listener.require_privileged_oper and event.target not in IRC_CHANNELS_OPER: continue match = listener.pattern.search(text) if match is not None: msg = MatchedMessage( channel=event.target, text=text, raw_text=raw_text, match=match, is_oper=is_oper, nick=user, respond=respond, ) listener.fn(self, msg) # everything gets logged self.recent_messages.appendleft((user, raw_text))
def test_time_for_other_not_found(self): self.bot.on_pubmsg( None, Event('pubmsg', NickMask('[email protected]'), '#test', ['.time other'])) self.bot.reply_to.assert_called_with(NickMask('[email protected]'), '#test', "I don't know other's timezone.")
def test_time_in_tz_not_found(self): self.bot.on_pubmsg( None, Event('pubmsg', NickMask('[email protected]'), '#test', ['.time NotA/Timezone'])) self.bot.reply_to.assert_called_with( NickMask('[email protected]'), '#test', "I don't know about that timezone.")
def reply(self, e, text): "Send TEXT to public channel or as private msg, in reply to event E." if e.eventtype() == "pubmsg": self.say_public("%s: %s" % (NickMask(e.source()).nick, text), e.target()) elif e.eventtype() == "privmsg": self.say_private(NickMask(e.source()).nick, text) elif e.eventtype() == "dccmsg": self.connection.notice(NickMask(e.source()).nick, text) else: self.say_private(NickMask(e.source()).nick, text)
def test_random_normal(self): with mock.patch('bavi.modules.random.choice', return_value=4) as mock_random: self.bot.on_pubmsg( None, Event('pubmsg', NickMask('user!ident@host'), '#test', ['.choose 1,2,3,4,5'])) self.bot.reply_to.assert_called_with( NickMask('user!ident@host'), '#test', 'Your choices: 1, 2, 3, 4, 5, I chose: 4.')
def test_random_pick(self): with mock.patch('bavi.modules.random.choice', return_value='g') as mock_random: self.bot.on_pubmsg( None, Event('pubmsg', NickMask('user!ident@host'), '#test', ['.pick a|b|c|d|e|f|g'])) self.bot.reply_to.assert_called_with( NickMask('user!ident@host'), '#test', 'Your choices: a, b, c, d,' ' e, f, g, I chose: g.')
def test_time_for_other(self): self.bot.on_pubmsg( None, Event('pubmsg', NickMask('[email protected]'), '#test', ['.settz America/Chicago'])) self.bot.on_pubmsg( None, Event('pubmsg', NickMask('[email protected]'), '#test', ['.time other'])) response = self.bot.say.call_args[0][1] assert response.startswith('Current time in America/Chicago is: ')
def test_random_trailing_whitespace(self): with mock.patch('bavi.modules.random.choice', return_value='blue fish') as mock_random: self.bot.on_pubmsg( None, Event('pubmsg', NickMask('user!ident@host'), '#test', ['.pick one fish, two fish, red fish, blue fish'])) self.bot.reply_to.assert_called_with( NickMask('user!ident@host'), '#test', 'Your choices: one fish, two fish,' ' red fish, blue fish, I chose: blue fish.')
def on_pubmsg(self, c, e): message = e.arguments[0] def by_oper(): chan = self.channels[e.target] nick = NickMask(e.source).nick allow = (chan.is_oper(nick) or chan.is_halfop(nick) or chan.is_voiced(nick)) if not allow: c.privmsg( e.target, "{0}: dis-donc, tête de noeud, tu crois que je suis ton larbin ?" .format(nick)) self.victim = nick return allow if message.startswith("!whitelist "): if by_oper(): self.do_whitelist(message[11:]) return elif message.startswith("!blacklist "): if by_oper(): self.do_blacklist(message[11:]) return elif trump_re.search(message): if self.trump_rl(e.source): self.victim = NickMask(e.source).nick logging.info("{0} abused trump card".format(e.source)) c.privmsg( e.target, "{0}: c'est bientôt fini, de me dire ta gueule à tout va ? c'est pas comme ça que tu vas relever le niveau." .format(self.victim)) else: logging.info("{0} used trump card".format(e.source)) return for word in get_words(message): if self.check_word(word): continue if self.rl(e.source): logging.info("Grace time allowed to {0}".format(e.source)) break reply = choice(insult_messages).format(word, NickMask(e.source).nick, self.victim) c.privmsg(e.target, reply) break
def test_settz_missing_timezone(self): self.bot.on_pubmsg( None, Event('pubmsg', NickMask('[email protected]'), '#test', ['.settz'])) self.bot.reply_to.assert_called_with( NickMask('[email protected]'), '#test', 'Give me a timezone, for example .settz America/Los_Angeles') c = self.bot.db.cursor() c.execute('SELECT tz FROM tz_info WHERE nick = ?', ('test', )) assert len(list(c)) == 0
def test_settz_invalid_timezone(self): self.bot.on_pubmsg( None, Event('pubmsg', NickMask('[email protected]'), '#test', ['.settz NotA/RealTimezone'])) self.bot.reply_to.assert_called_with( NickMask('[email protected]'), '#test', "I don't know about that timezone") c = self.bot.db.cursor() c.execute('SELECT tz FROM tz_info WHERE nick = ?', ('test', )) assert len(list(c)) == 0
def on_join(self, c, e): nick = NickMask(e.source()).nick chan = e.target() log.info('on_join %s @ %s | %s' % (nick, chan, self.eventToString(e))) self.botEvent({ 'key': 'join', 'value': nick, 'extra': {'target': chan} }) chan = self.delChannelPrefix(chan) greet_sect = 'greet_%s' % chan if self.config.has_key(greet_sect) and self.config[greet_sect].has_key(nick): msg = self.config[greet_sect][nick] self.say_public(msg, chan) op_sect = 'op_%s' % chan if self.config.has_key(op_sect) and self.config[op_sect].has_key(nick): tmp = e.source().split('!') ident, ip = tmp[1].split('@') if self.config[op_sect][nick] == ip: log.info('Op %s @ %s because ip matches config' % (nick, ip)) self.do_op(nick, chan) else: log.info('Do not op %s @ %s because ip does not match config: %s' % (nick, ip, self.config[op_sect][nick])) if nick == self.connection.get_nickname(): self.do_opme(chan)
def on_kick(self, c, e): nick = e.arguments[0] chan = e.target if nick == c.get_nickname(): self.victim = NickMask(e.source).nick logging.info("New revenge victim: {0}".format(self.victim)) c.join(chan)
def on_pubmsg(self, serv, ev): """Method called when someone is talking on a public chan.""" message = ev.arguments[0] nick = NickMask(ev.source).nick if message.startswith('!'): # Extract command from message command_text = message[1:] command_parts = command_text.split(' ') command = IRCCommand( nick=nick, is_voiced=self.channels[self.channel].is_voiced(nick), command_name=command_parts[0].lower(), command_args=command_parts[1:]) get_logger().info("Received {}".format(command)) # Handle special case for spacestatus (path dependency...) if command.command_name.startswith('space'): command.command_name = 'spacestatus' try: # Retrieve the 'handle' function from corresponding module module = importlib.import_module( 'hms_irc.transmitters.{}'.format(command.command_name)) func = getattr(module, 'handle') # Call the handle function with all important arguments get_logger().info('Calling transmitter for {}'.format(command)) func(self.serv, self.channel, self.rabbit, command) except (ImportError, AttributeError) as e: get_logger().error(e) self.serv.privmsg(self.channel, 'Commande inexistante')
def test_command_alias_works(self): def handler(bot, source, target, message, **kwargs): bot.say(target, 'This is an example') self.bot.add_command('example', handler, aliases=['a1', 'a2']) self.bot.on_pubmsg( None, Event('pubmsg', NickMask('user!ident@host'), '#test', ['.a1'])) self.bot.connection.privmsg.assert_called_with('#test', 'This is an example') self.bot.on_pubmsg( None, Event('pubmsg', NickMask('user!ident@host'), '#test', ['.a2'])) self.bot.connection.privmsg.assert_called_with('#test', 'This is an example')
def __init__(self, string, user='******', source='pubmsg'): if isinstance(user, Player): user = '******'.format(user.nick, user.user) mask = NickMask(user) source = '#test' if source == 'pubmsg' else mask.nick event = Event('privmsg', mask, source, [string]) super().__init__(event)
def endnames(self, sender, **kw): channel = kw['channel'] # Sort users from highest permissions to lowest ulist = self.cusers[channel] ownlist = [] adminlist = [] oplist = [] halfoplist = [] vlist = [] nlist = [] for u in ulist: nu = NickMask(u) if '~' in nu.nick: ownlist.append(u) elif '&' in nu.nick: adminlist.append(u) elif '@' in nu.nick: oplist.append(u) elif '%' in nu.nick: halfoplist.append(u) elif '+' in nu.nick: vlist.append(u) else: nlist.append(u) ulist = ownlist + adminlist + oplist + halfoplist + vlist + nlist self.users.emit(channel, ulist) self.cusers[channel] = []
def on_pubmsg(self, c, e): try: nick = NickMask(e.source()).nick a = e.arguments()[0].split(":", 1) #print "pub_msg: %s" % a #print "pub_msg first char: '%s'" % a[0][0] # parse first word as a command if pre'ed by <botname:> if len(a) > 1 and irc_lower(a[0]) == irc_lower(self.connection.get_nickname()): #self.command_switch(e, a[1].strip()) a2 = e.arguments()[0].split(" ") if len(a2[0][1:]) > 0: self.command_switch(nick,e,a2[1],a2[2:]) # parse first word as a command if pre'ed by "!" elif e.arguments()[0][0] == '!': a2 = e.arguments()[0].split(" ") if len(a2[0][1:]) > 0: self.command_switch(nick,e,a2[0][1:],a2[1:]) # else: send as generic pubmessage event else: a2 = e.arguments()[0] data = {'key':'pubmessage', 'value':a2, 'extra': {'nick':nick}} self.botEvent(data) return except Exception, e: self.say_public('Exception in on_pubmsg: %s' % e) log.warn('Exception in on_privmsg: %s' % utils.e2str(e))
def __init__(self, **kwargs): self.source = NickMask( kwargs.get('source', '[email protected]')) self.target = kwargs.get('target', None) self.arguments = kwargs.get('arguments', ['']) self.type = kwargs.get('type', None)
def test_time_in_tz_utc(self): self.bot.on_pubmsg( None, Event('pubmsg', NickMask('[email protected]'), '#test', ['.time UTC'])) response = self.bot.say.call_args[0][1] assert response.startswith('Current time in UTC is: ')
def test_command_not_found_replies_to_user(self): self.bot.on_pubmsg( None, Event('pubmsg', NickMask('user!ident@host'), '#test', ['.notacommand 1 2'])) self.bot.connection.privmsg.assert_called_with( '#test', "user: I don't know about that command.")
def joined(self, event: Event): # TODO shouldn't have to bother with NickMask u = NickMask(event.source) # TODO easier way to get own info if u.nick == self.bot.connection.nick: self.sendmsg( "Vicky Vicky Vicky, can't you see. Sometimes your joins just hypnotize me." )
def on_join(self, _, event): nm = NickMask(event.source) if nm.nick == self.name: log.info('joined %s', self.channel) self.log_channel.create() thread = Thread(target=channel_reader, args=(self, )) thread.setDaemon(True) thread.start()
def on_kick(self, c, e): source_nick = NickMask(e.source).nick kickee = e.arguments[0] self.append_to_log("* " + kickee + " was kicked from " + self.channel + " by " + source_nick) self.prvmsg_append_to_log(c, self.channel, "Bwahahaha! *snicker*") if kickee == self._nickname: c.join(self.channel)
def __init__(self, server, user, user_id=None, groupchat=None): user = NickMask(user) # user.nick # user.userhost # user.host # user.user self.server = server self._id = None User.__init__(self, server.protocol, user.nick)
def privmsg(self, user_host, channel, msg): # check if private message if channel != self.nickname: return # create pseudo-event object e = Event("privmsg", NickMask(user_host), channel, msg.split()) logger.info(f"MESSAGE: BOT:{self.nickname} <- USER:{e.source.nick}: {msg}") self.on_msg(e)
def action(self, user_host, channel, msg): # check if private message if channel != self.nickname: return # create pseudo-event object e = Event("action", NickMask(user_host), channel, ("!action " + msg).split()) logger.info(f"ACTION: BOT:{self.nickname} <- USER:{e.source.nick} {msg}") self.on_msg(e)
def test_reply_to_raises_when_given_invalid_channel(self): try: self.bot.reply_to(NickMask('user!ident@host'), '#wrong-channel', 'Some message') except KeyError: pass else: raise AssertionError('Expected KeyError for wrong channel') self.bot.connection.privmsg.assert_not_called()
def __init__(self, command, *params, tags=dict(), hostmask=""): self.command = command if len(params) == 0: self.params = [] elif len(params) == 1 and type(params[0]) in (list, tuple): self.params = list(params[0]) else: self.params = list(params) self.tags = tags self.hostmask = NickMask(hostmask) if hostmask else None