def run_loop(stdscreen): command_handler = CommandHandler(stdscreen) search_key = 115 select_key = ord('\n') spotify_client_key = 102 quit_key = 113 goto_index_key = 105 artist_tracks_key = 116 album_tracks_key = 97 move_up_key = curses.KEY_UP move_up_key_2 = 107 move_down_key = curses.KEY_DOWN move_down_key_2 = 106 next_song_key = curses.KEY_RIGHT next_song_key_2 = 108 prev_song_key = curses.KEY_LEFT prev_song_key_2 = 104 play_pause_key = 32 back_key = 98 forward_key = 110 command_list_key = 99 country_change_key = 121 command_dict = { move_up_key: command_handler.move_up, move_down_key: command_handler.move_down, next_song_key: command_handler.next_song, prev_song_key: command_handler.prev_song, move_up_key_2: command_handler.move_up, move_down_key_2: command_handler.move_down, next_song_key_2: command_handler.next_song, prev_song_key_2: command_handler.prev_song, search_key: command_handler.search_content, select_key: command_handler.current_song, spotify_client_key: command_handler.show_client, goto_index_key: command_handler.play_at_index, artist_tracks_key: command_handler.get_artist_top, album_tracks_key: command_handler.get_album_tracks, play_pause_key: command_handler.toggle_play_pause, back_key: command_handler.prev_track_list, forward_key: command_handler.next_track_list, command_list_key: command_handler.print_command_list, country_change_key: command_handler.country_check, } curses.curs_set(0) intro(stdscreen) command_handler.country_check() command_handler.prompt_area.addstr(0, 0, "Good To Go! Start a search with [S]") command_handler.prompt_area.refresh() while True: char_input = stdscreen.getch() if char_input == quit_key: sys.exit() elif char_input in command_dict: command_dict.get(char_input)()
def access(bot, event): """Report user's access levels.""" target = event.target if event.type == 'pubmsg' else event.source.nick sender = event.source.nick dummy = CommandHandler(event, bot) access_level = dummy.perm_level() bot.connection.privmsg(target, f'{sender} has level {access_level} clearance.')
def __init__(self, bot_jid, stream): self.bot_jid = bot_jid self._stream = stream self.cmd_handler = CommandHandler(message_bus=self) self.admin_cmd_handler = AdminCMDHandler(message_bus=self) self.logger = get_logger() self.offline_split_symbol = "$_$_$_$" return
def run_loop(stdscreen): command_handler = CommandHandler(stdscreen) search_key = 115 select_key = ord('\n') spotify_client_key = 102 quit_key = 113 goto_index_key = 105 artist_tracks_key = 116 album_tracks_key = 97 move_up_key = curses.KEY_UP move_up_key_2 = 107 move_down_key = curses.KEY_DOWN move_down_key_2 = 106 next_song_key = curses.KEY_RIGHT next_song_key_2 = 108 prev_song_key = curses.KEY_LEFT prev_song_key_2 = 104 play_pause_key = 32 back_key = 98 forward_key = 110 command_list_key = 99 country_change_key = 121 command_dict = { move_up_key : command_handler.move_up, move_down_key : command_handler.move_down, next_song_key : command_handler.next_song, prev_song_key : command_handler.prev_song, move_up_key_2 : command_handler.move_up, move_down_key_2 : command_handler.move_down, next_song_key_2 : command_handler.next_song, prev_song_key_2 : command_handler.prev_song, search_key : command_handler.search_content, select_key : command_handler.current_song, spotify_client_key : command_handler.show_client, goto_index_key : command_handler.play_at_index, artist_tracks_key : command_handler.get_artist_top, album_tracks_key : command_handler.get_album_tracks, play_pause_key : command_handler.toggle_play_pause, back_key : command_handler.prev_track_list, forward_key : command_handler.next_track_list, command_list_key : command_handler.print_command_list, country_change_key : command_handler.country_check, } curses.curs_set(0) intro(stdscreen) command_handler.country_check() command_handler.prompt_area.addstr(0, 0, "Good To Go! Start a search with [S]") command_handler.prompt_area.refresh() while True: char_input = stdscreen.getch() if char_input == quit_key: sys.exit() elif char_input in command_dict: command_dict.get(char_input)()
class MusicBot(irc.IRCClient): """A logging IRC bot.""" commandPrefix = "!music" def __init__(self): self.commandHandler = CommandHandler(CommandManager()) def connectionMade(self): irc.IRCClient.connectionMade(self) self.logger = MessageLogger(open(self.factory.filename, "a")) self.logger.log("[connected at %s]" % time.asctime(time.localtime(time.time()))) def connectionLost(self, reason): irc.IRCClient.connectionLost(self, reason) self.logger.log("[disconnected at %s]" % time.asctime(time.localtime(time.time()))) self.logger.close() # callbacks for events def signedOn(self): """Called when bot has succesfully signed on to server.""" self.join(self.factory.channel) def privmsg(self, user, channel, msg): """This will get called when the bot receives a message.""" user = user.split("!", 1)[0] self.logger.log("<%s> %s" % (user, msg)) if channel == self.factory.channel: if str.startswith(msg, self.commandPrefix): print "command prefix found!\n" words = msg.split(" ") commandName = "help" if len(words) > 1: commandName = words[1] arguments = words[2::] output = self.commandHandler.handleCommand(self, user, commandName, arguments) if output is not None: self.sendMessage(output) def registerCommand(self, command): self.commandHandler.getCommandManager().addCommand(command) def sendMessage(self, message): print "sending message" print message lines = message.split("\n") for line in lines: self.say(self.factory.channel, line) def getCommandHandler(self): return self.commandHandler def getMaster(self): return self.factory.master
def run(self) -> None: discord_client = discord.Client() weather_service = WeatherService( self._settings.integration_settings.open_weather_map_api_key, self._settings.integration_settings.weather_underground_api_key) message_factory = MessageFactory(self._settings) command_handler = CommandHandler(self._settings, weather_service, discord_client, message_factory) weather_discord_service = WeatherDiscordService( self._settings.measurement_system, self._settings.home_settings, weather_service, discord_client) @discord_client.event async def on_message(message) -> None: await command_handler.handle(message) discord_client.loop.create_task( weather_discord_service.send_home_forecast()) discord_client.loop.create_task( weather_discord_service.update_profile()) discord_client.loop.create_task( weather_discord_service.update_presence()) discord_client.run( self._settings.integration_settings.discord_bot_token)
def __init__(self, bot_jid, stream): self.bot_jid = bot_jid self._stream = stream self.cmd_handler = CommandHandler(message_bus = self) self.admin_cmd_handler = AdminCMDHandler(message_bus = self) self.logger = get_logger() self.offline_split_symbol = "$_$_$_$" return
def help(bot, event): """Find help strings.""" target = event.target if event.type == 'pubmsg' else event.source.nick args = event.arguments[0].split()[1:] if len(args) == 0: return bot.connection.privmsg( target, 'Please see https://meta.miraheze.org/wiki/User:Void-bot/Help') command = CommandHandler.get_command(args[0]) if command is False or command.help is False: return bot.connection.privmsg( target, f'Sorry, I could not find help on {args[0]}.') bot.connection.privmsg(target, command.help)
def cmd_enable(bot, event): """Enable a command.""" target = event.target if event.type == 'pubmsg' else event.source.nick args = event.arguments[0].split()[1:] if len(args) == 0: return bot.connection.privmsg( target, "I can't enable what you don't tell me about.") if not CommandHandler.enable_command(args[0]): return bot.connection.privmsg( target, f'I can\'t enable what does not exist! (Could not find "{args[0]}")' ) else: logs.info(f'{event.source.nick} has enabled command {args[0]}')
class MessageBus(object): """ 消息总线 用于发送消息和桥接bot和命令 接收消息分发给群成员 处理消息命令,指派给相应的命令处理 供命令处理返回命令或广播命令结果 """ def __init__(self, bot_jid, stream): self.bot_jid = bot_jid self._stream = stream self.cmd_handler = CommandHandler(message_bus = self) self.admin_cmd_handler = AdminCMDHandler(message_bus = self) self.logger = get_logger() self.offline_split_symbol = "$_$_$_$" return def make_message(self, to, typ, body): """ 构造消息 `to` - 接收人 JID `typ` - 消息类型 `body` - 消息主体 """ if typ not in ['normal', 'chat', 'groupchat', 'headline']: typ = 'chat' m = Message(from_jid = self.bot_jid, to_jid = to, stanza_type = typ, body = body) return m def send_to_admin(self, stanza, body): """ 给管理员发送消息 """ [self.send_message(stanza, admin, body, True) for admin in ADMINS] def send_private_msg(self, stanza, to, body): """ 发送私信 """ frm = stanza.from_jid nick = Logics.get_one(frm).nick body = "[%s 悄悄对你说] %s" % (nick, body) self.send_message(stanza, to, body, True) def send_message(self, stanza, to, body, log = False): """ 发送消息 `stanza` - 消息节 `to` - 接收人 接收人不在线发送离线消息 `body` - 消息主体 `log` - 记录历史消息 """ if to == USER: return if log: Logics.add_history(stanza.from_jid, to, body) if Logics.is_online(to): mode = Logics.get_info(to, 'mode').value if mode == 'talk' or not mode: if isinstance(to, (str, unicode)): to = JID(to) self.logger.debug("send '{0}' to {1!r}".format(body, to)) typ = stanza.stanza_type self._stream.send(self.make_message(to, typ, body)) else: body = NOW() + ' ' + body self.logger.debug("store offline message'{0}' for {1!r}" .format(body, to)) offline_message = Logics.get_info(to, 'offline_message', '').value off_msgs = offline_message.split(self.offline_split_symbol) if len(off_msgs) >= 10: offline_message = self.offline_split_symbol.join(off_msgs[-9:]) offline_message += self.offline_split_symbol + body Logics.set_info(to, 'offline_message', offline_message) def send_offline_message(self, stanza): """ 发送离线消息 """ show = stanza.show frm = stanza.from_jid offline_message = Logics.get_info(frm, 'offline_message', '').value if offline_message: off_msgs = offline_message.split(self.offline_split_symbol) offline_message = "\n".join(off_msgs) offline_message = "离线期间的消息:\n" + offline_message m = self.make_message(frm, 'chat', offline_message) self._stream.send(m) Logics.set_online(frm, show) Logics.set_info(frm, 'offline_message', '') def handle_code(self, stanza, body, nick, back): if body.startswith("```"): bodys = body.split("\n") typ = bodys[0].strip("`").strip() typ = typ if typ else "text" codes = "\n".join(bodys[1:]).strip("```") self.cmd_handler._paste(stanza, typ, codes, nick, back) def send_all_msg(self, stanza, body): """ 给除了自己的所有成员发送消息 """ nick = Logics.get_one(stanza.from_jid).nick if stanza.from_jid.bare().as_string() == USER: return if cityid(body.strip()): return self.send_command(stanza, '-_tq ' + body.strip()) if body.strip() == 'help': return self.send_command(stanza, '-help') if body.strip() == 'ping': return self.send_command(stanza, '-_ping') if body.startswith("```"): back = partial(self.send_back_msg, stanza) self.handle_code(stanza, body, nick, back) mode = Logics.get_info(stanza.from_jid, 'mode').value if mode == 'quiet': body = u'你处于{0},请使用-cd命令切换到 {1} '\ u'后发言'.format(MODES[mode], MODES['talk']) return self.send_back_msg(stanza, body) if body.startswith(">>>"): self.cmd_handler.shell(stanza, body.lstrip(">").lstrip()) members = Logics.get_members(stanza.from_jid) members = [m.email for m in members] if len(body) > 200: def long_back(body, content): nick, url = content.split(" ") body = u"{0}\n{1}".format(url, body.split("\n")[0][0:50]) self.send_back_msg(stanza, u"内容过长,贴到:{0}".format(url)) self.logger.info("{0} send message {1} to {2!r}" .format(stanza.from_jid, body, members)) Logics.add_history(stanza.from_jid, 'all', body) [self.send_message(stanza, m, "[{0}] {1}".format(nick, body)) for m in members] back = partial(long_back, body) self.handle_code(stanza, "```\n" + body, nick, back) return Logics.add_history(stanza.from_jid, 'all', body) self.logger.info("{0} send message {1} to {2!r}" .format(stanza.from_jid, body, members)) if body.startswith('/me'): body = body.replace('/me', nick + ' ') else: if nick != "qxbot": body = "[{0}] {1}".format(nick, body) [self.send_message(stanza, m, body) for m in members] def send_back_msg(self, stanza, body): """ 发送返回消息 """ to = stanza.from_jid.bare().as_string() typ = stanza.stanza_type self._stream.send(self.make_message(to, typ, body)) def send_sys_msg(self, stanza, body): """ 发送系统消息 """ members = Logics.get_members() members = [m.email for m in members] [self.send_message(stanza, m, body) for m in members] def send_command(self, stanza, body): """ 处理命令 为防止阻塞使用线程池处理命令 """ email = get_email(stanza.from_jid) self.logger.info("{0} run command {1}".format(stanza.from_jid, body)) if email in ADMINS: target = self.admin_cmd_handler._run_cmd else: target = self.cmd_handler._run_cmd target(stanza, body) def send_status(self, statustext, to = None): if to: to_jid = JID(to) p = Presence(status=statustext, to_jid = to_jid) else: p = Presence(status = statustext) self._stream.send(p) def send_subscribe(self, jid): """ 发送订阅 """ p1 = Presence(from_jid = self.bot_jid, to_jid = jid, stanza_type = 'subscribe') p = Presence(from_jid = self.bot_jid, to_jid = jid, stanza_type = 'subscribed') self._stream.send(p) self._stream.send(p1) def send_unsubscribe(self, jid): p1 = Presence(from_jid = self.my_jid, to_jid = jid, stanza_type = 'unsubscribe') p = Presence(from_jid = self.my_jid, to_jid = jid, stanza_type = 'unsubscribed') self._stream.send(p) self._stream.send(p1)
def create_controller_from_moveset(self, moveset, input_player): """Creates a controller object from a moveset""" #Create the command handlers for the controller aerial_movement_command_types = [command_type for command_type in CommandCollections.AERIAL_MOVEMENTS] aerial_movement_command_handler = CommandHandler( aerial_movement_command_types ) aerial_action_command_types = [command_type for command_type in CommandCollections.AERIAL_ACTIONS] aerial_action_command_handler = CommandHandler( aerial_action_command_types ) stun_movement_command_handler = CommandHandler( [command_type for command_type in CommandCollections.STUN_MOVEMENTS] ) ground_movement_command_types = [command_type for command_type in CommandCollections.GROUND_MOVEMENTS] ground_movement_command_handler = CommandHandler( ground_movement_command_types, True ) attack_command_handler = CommandHandler( [command_type for command_type in CommandCollections.ATTACK_ACTIONS] ) #create the key to command mappings for the controller movement_key_to_command_type = dict( [(get_control_key(input_player.player_position, action_type), action_type) for action_type in InputActionTypes.MOVEMENTS] ) attack_key_to_command_type = dict( [(get_control_key(input_player.player_position, action_type), action_type) for action_type in CommandCollections.ATTACK_ACTIONS if action_type != InputActionTypes.FORWARD] ) #Set aerial no movement actions float_action = self.create_action( PlayerStates.FLOATING, moveset.movement_animations[PlayerStates.FLOATING] ) tap_no_movement = Command( InputActionTypes.NO_MOVEMENT, CommandDurations.TAP ) aerial_action_command_handler.add_command([tap_no_movement], float_action) hold_no_movement = Command( InputActionTypes.NO_MOVEMENT, CommandDurations.HOLD ) aerial_action_command_handler.add_command([hold_no_movement], float_action) #Set ground no movement actions stand_action = self.create_action( PlayerStates.STANDING, moveset.movement_animations[PlayerStates.STANDING] ) tap_no_movement = Command( InputActionTypes.NO_MOVEMENT, CommandDurations.TAP ) ground_movement_command_handler.add_command([tap_no_movement], stand_action) hold_no_movement = Command( InputActionTypes.NO_MOVEMENT, CommandDurations.HOLD ) ground_movement_command_handler.add_command([hold_no_movement], stand_action) #Set jump actions jump_action = self.create_action( PlayerStates.JUMPING, moveset.movement_animations[PlayerStates.JUMPING], None ) tap_jump_command = Command( InputActionTypes.JUMP, CommandDurations.TAP ) hold_jump_command = Command( InputActionTypes.JUMP, CommandDurations.HOLD ) ground_movement_command_handler.add_command( [tap_jump_command], jump_action ) aerial_action_command_handler.add_command( [tap_jump_command], jump_action ) ground_movement_command_handler.add_command( [hold_jump_command], jump_action ) aerial_action_command_handler.add_command( [hold_jump_command], jump_action ) #Set move up actions tap_up_command = Command( InputActionTypes.MOVE_UP, CommandDurations.TAP ) hold_up_command = Command( InputActionTypes.MOVE_UP, CommandDurations.HOLD ) stun_movement_command_handler.add_command( [tap_up_command], StunMotion( (0, -1 * input_player.tap_stun_acceleration), (0, -1 * input_player.max_stun_velocity) ) ) stun_movement_command_handler.add_command( [hold_up_command], StunMotion( (0, -1 * input_player.hold_stun_acceleration), (0, -1 * input_player.max_stun_velocity) ) ) #Set move down actions crouch_action = self.create_action( PlayerStates.CROUCHING, moveset.movement_animations[PlayerStates.CROUCHING], None ) tap_down_command = Command( InputActionTypes.MOVE_DOWN, CommandDurations.TAP ) hold_down_command = Command( InputActionTypes.MOVE_DOWN, CommandDurations.HOLD ) ground_movement_command_handler.add_command( [tap_down_command], crouch_action ) ground_movement_command_handler.add_command( [hold_down_command], crouch_action ) aerial_movement_command_handler.add_command( [tap_down_command], AerialMotion( (0, input_player.aerial_acceleration), (0, input_player.max_aerial_velocity) ) ) aerial_movement_command_handler.add_command( [hold_down_command], AerialMotion( (0, input_player.aerial_acceleration), (0, input_player.max_aerial_velocity) ) ) stun_movement_command_handler.add_command( [tap_down_command], StunMotion( (0, input_player.tap_stun_acceleration), (0, input_player.max_stun_velocity) ) ) stun_movement_command_handler.add_command( [hold_down_command], StunMotion( (0, input_player.hold_stun_acceleration), (0, input_player.max_stun_velocity) ) ) #Set move right actions tap_right_command = Command( InputActionTypes.MOVE_RIGHT, CommandDurations.TAP ) hold_right_command = Command( InputActionTypes.MOVE_RIGHT, CommandDurations.HOLD ) input_player.walk_right_action = self.create_action( PlayerStates.WALKING, moveset.movement_animations[PlayerStates.WALKING], PlayerStates.FACING_RIGHT ) input_player.run_right_action = self.create_action( PlayerStates.RUNNING, moveset.movement_animations[PlayerStates.RUNNING], PlayerStates.FACING_RIGHT ) ground_movement_command_handler.add_command( [tap_right_command, tap_right_command], input_player.run_right_action ) ground_movement_command_handler.add_command( [hold_right_command, tap_right_command], input_player.run_right_action ) ground_movement_command_handler.add_command( [tap_right_command], input_player.walk_right_action ) ground_movement_command_handler.add_command( [hold_right_command], input_player.walk_right_action ) aerial_movement_command_handler.add_command( [tap_right_command], AerialMotion( (input_player.aerial_acceleration, 0), (input_player.max_aerial_velocity, 0) ) ) aerial_movement_command_handler.add_command( [hold_right_command], AerialMotion( (input_player.aerial_acceleration, 0), (input_player.max_aerial_velocity, 0) ) ) stun_movement_command_handler.add_command( [tap_right_command], StunMotion( (input_player.tap_stun_acceleration, 0), (input_player.max_stun_velocity, 0) ) ) stun_movement_command_handler.add_command( [hold_right_command], StunMotion( (input_player.hold_stun_acceleration, 0), (input_player.max_stun_velocity, 0) ) ) #Set move left actions tap_left_command = Command( InputActionTypes.MOVE_LEFT, CommandDurations.TAP ) hold_left_command = Command( InputActionTypes.MOVE_LEFT, CommandDurations.HOLD ) input_player.walk_left_action = self.create_action( PlayerStates.WALKING, moveset.movement_animations[PlayerStates.WALKING], PlayerStates.FACING_LEFT ) input_player.run_left_action = self.create_action( PlayerStates.RUNNING, moveset.movement_animations[PlayerStates.RUNNING], PlayerStates.FACING_LEFT ) ground_movement_command_handler.add_command( [tap_left_command, tap_left_command], input_player.run_left_action ) ground_movement_command_handler.add_command( [hold_left_command, tap_left_command], input_player.run_left_action ) ground_movement_command_handler.add_command( [tap_left_command], input_player.walk_left_action ) ground_movement_command_handler.add_command( [hold_left_command], input_player.walk_left_action ) aerial_movement_command_handler.add_command( [tap_left_command], AerialMotion( (-1 * input_player.aerial_acceleration, 0), (-1 * input_player.max_aerial_velocity, 0) ) ) aerial_movement_command_handler.add_command( [hold_left_command], AerialMotion( (-1 * input_player.aerial_acceleration, 0), (-1 * input_player.max_aerial_velocity, 0) ) ) stun_movement_command_handler.add_command( [tap_left_command], StunMotion( (-1 * input_player.tap_stun_acceleration, 0), (-1 * input_player.max_stun_velocity, 0) ) ) stun_movement_command_handler.add_command( [hold_left_command], StunMotion( (-1 * input_player.hold_stun_acceleration, 0), (-1 * input_player.max_stun_velocity, 0) ) ) #Set attack actions for attack_name in moveset.get_attacks(): attack_type = moveset.get_attack_type(attack_name) attack_action = None if InputActionTypes.JUMP in moveset.attack_key_combinations[attack_name]: attack_action = JumpAttack(attack_type) else: attack_action = Attack(attack_type) attack_action.set_acceleration(attack_type) self.action_factory._set_action_animations( attack_action, moveset.attack_animations[attack_name], attack_action.acceleration ) attack_action.set_attack_data(input_player.model) input_player.actions[attack_name] = attack_action if InputActionTypes.JUMP in moveset.attack_key_combinations[attack_name]: short_command_list = [ command_type for command_type in moveset.attack_key_combinations[attack_name] if command_type != InputActionTypes.JUMP ] tap_commands = [] for command_type in short_command_list: tap_commands.append(Command(command_type, CommandDurations.TAP)) aerial_action_command_handler.add_command( tap_commands, attack_action ) hold_commands = [] for command_type in short_command_list: if (command_type in InputActionTypes.MOVEMENTS or command_type == InputActionTypes.FORWARD): hold_commands.append(Command(command_type, CommandDurations.HOLD)) else: hold_commands.append(Command(command_type, CommandDurations.TAP)) aerial_action_command_handler.add_command( hold_commands, attack_action ) tap_commands = [] for command_type in moveset.attack_key_combinations[attack_name]: tap_commands.append(Command(command_type, CommandDurations.TAP)) aerial_action_command_handler.add_command( tap_commands, attack_action ) hold_commands = [] for command_type in moveset.attack_key_combinations[attack_name]: if (command_type in InputActionTypes.MOVEMENTS or command_type == InputActionTypes.FORWARD): hold_commands.append(Command(command_type, CommandDurations.HOLD)) else: hold_commands.append(Command(command_type, CommandDurations.TAP)) aerial_action_command_handler.add_command( hold_commands, attack_action ) else: tap_commands = [] for command_type in moveset.attack_key_combinations[attack_name]: tap_commands.append(Command(command_type, CommandDurations.TAP)) attack_command_handler.add_command( tap_commands, attack_action ) hold_commands = [] for command_type in moveset.attack_key_combinations[attack_name]: if (command_type in InputActionTypes.MOVEMENTS or command_type == InputActionTypes.FORWARD): hold_commands.append(Command(command_type, CommandDurations.TAP)) else: hold_commands.append(Command(command_type, CommandDurations.TAP)) attack_command_handler.add_command( hold_commands, attack_action ) return Controller( movement_key_to_command_type, attack_key_to_command_type, aerial_movement_command_handler, aerial_action_command_handler, stun_movement_command_handler, ground_movement_command_handler, attack_command_handler )
class MessageBus(object): """ 消息总线 用于发送消息和桥接bot和命令 接收消息分发给群成员 处理消息命令,指派给相应的命令处理 供命令处理返回命令或广播命令结果 """ def __init__(self, bot_jid, stream): self.bot_jid = bot_jid self._stream = stream self.cmd_handler = CommandHandler(message_bus=self) self.admin_cmd_handler = AdminCMDHandler(message_bus=self) self.logger = get_logger() self.offline_split_symbol = "$_$_$_$" return def make_message(self, to, typ, body): """ 构造消息 `to` - 接收人 JID `typ` - 消息类型 `body` - 消息主体 """ if typ not in ['normal', 'chat', 'groupchat', 'headline']: typ = 'chat' m = Message(from_jid=self.bot_jid, to_jid=to, stanza_type=typ, body=body) return m def send_to_admin(self, stanza, body): """ 给管理员发送消息 """ [self.send_message(stanza, admin, body, True) for admin in ADMINS] def send_private_msg(self, stanza, to, body): """ 发送私信 """ frm = stanza.from_jid nick = Logics.get_one(frm).nick body = "[%s 悄悄对你说] %s" % (nick, body) self.send_message(stanza, to, body, True) def send_message(self, stanza, to, body, log=False): """ 发送消息 `stanza` - 消息节 `to` - 接收人 接收人不在线发送离线消息 `body` - 消息主体 `log` - 记录历史消息 """ if to == USER: return if log: Logics.add_history(stanza.from_jid, to, body) if Logics.is_online(to): mode = Logics.get_info(to, 'mode').value if mode == 'talk' or not mode: if isinstance(to, (str, unicode)): to = JID(to) self.logger.debug("send '{0}' to {1!r}".format(body, to)) typ = stanza.stanza_type self._stream.send(self.make_message(to, typ, body)) else: body = NOW() + ' ' + body self.logger.debug("store offline message'{0}' for {1!r}".format( body, to)) offline_message = Logics.get_info(to, 'offline_message', '').value off_msgs = offline_message.split(self.offline_split_symbol) if len(off_msgs) >= 10: offline_message = self.offline_split_symbol.join(off_msgs[-9:]) offline_message += self.offline_split_symbol + body Logics.set_info(to, 'offline_message', offline_message) def send_offline_message(self, stanza): """ 发送离线消息 """ show = stanza.show frm = stanza.from_jid offline_message = Logics.get_info(frm, 'offline_message', '').value if offline_message: off_msgs = offline_message.split(self.offline_split_symbol) offline_message = "\n".join(off_msgs) offline_message = "离线期间的消息:\n" + offline_message m = self.make_message(frm, 'chat', offline_message) self._stream.send(m) Logics.set_online(frm, show) Logics.set_info(frm, 'offline_message', '') def handle_code(self, stanza, body, nick, back): if body.startswith("```"): bodys = body.split("\n") typ = bodys[0].strip("`").strip() typ = typ if typ else "text" codes = "\n".join(bodys[1:]).strip("```") self.cmd_handler._paste(stanza, typ, codes, nick, back) def send_all_msg(self, stanza, body): """ 给除了自己的所有成员发送消息 """ nick = Logics.get_one(stanza.from_jid).nick if stanza.from_jid.bare().as_string() == USER: return if cityid(body.strip()): return self.send_command(stanza, '-_tq ' + body.strip()) if body.strip() == 'help': return self.send_command(stanza, '-help') if body.strip() == 'ping': return self.send_command(stanza, '-_ping') if body.startswith("```"): back = partial(self.send_back_msg, stanza) self.handle_code(stanza, body, nick, back) mode = Logics.get_info(stanza.from_jid, 'mode').value if mode == 'quiet': body = u'你处于{0},请使用-cd命令切换到 {1} '\ u'后发言'.format(MODES[mode], MODES['talk']) return self.send_back_msg(stanza, body) if body.startswith(">>>"): self.cmd_handler.shell(stanza, body.lstrip(">").lstrip()) members = Logics.get_members(stanza.from_jid) members = [m.email for m in members] if len(body) > 200: def long_back(body, content): nick, url = content.split(" ") body = u"{0}\n{1}".format(url, body.split("\n")[0][0:50]) self.send_back_msg(stanza, u"内容过长,贴到:{0}".format(url)) self.logger.info("{0} send message {1} to {2!r}".format( stanza.from_jid, body, members)) Logics.add_history(stanza.from_jid, 'all', body) [ self.send_message(stanza, m, "[{0}] {1}".format(nick, body)) for m in members ] back = partial(long_back, body) self.handle_code(stanza, "```\n" + body, nick, back) return Logics.add_history(stanza.from_jid, 'all', body) self.logger.info("{0} send message {1} to {2!r}".format( stanza.from_jid, body, members)) if body.startswith('/me'): body = body.replace('/me', nick + ' ') else: if nick != "qxbot": body = "[{0}] {1}".format(nick, body) [self.send_message(stanza, m, body) for m in members] def send_back_msg(self, stanza, body): """ 发送返回消息 """ to = stanza.from_jid.bare().as_string() typ = stanza.stanza_type self._stream.send(self.make_message(to, typ, body)) def send_sys_msg(self, stanza, body): """ 发送系统消息 """ members = Logics.get_members() members = [m.email for m in members] [self.send_message(stanza, m, body) for m in members] def send_command(self, stanza, body): """ 处理命令 为防止阻塞使用线程池处理命令 """ email = get_email(stanza.from_jid) self.logger.info("{0} run command {1}".format(stanza.from_jid, body)) if email in ADMINS: target = self.admin_cmd_handler._run_cmd else: target = self.cmd_handler._run_cmd target(stanza, body) def send_status(self, statustext, to=None): if to: to_jid = JID(to) p = Presence(status=statustext, to_jid=to_jid) else: p = Presence(status=statustext) self._stream.send(p) def send_subscribe(self, jid): """ 发送订阅 """ p1 = Presence(from_jid=self.bot_jid, to_jid=jid, stanza_type='subscribe') p = Presence(from_jid=self.bot_jid, to_jid=jid, stanza_type='subscribed') self._stream.send(p) self._stream.send(p1) def send_unsubscribe(self, jid): p1 = Presence(from_jid=self.my_jid, to_jid=jid, stanza_type='unsubscribe') p = Presence(from_jid=self.my_jid, to_jid=jid, stanza_type='unsubscribed') self._stream.send(p) self._stream.send(p1)
def __init__(self): self.commandHandler = CommandHandler(CommandManager())