def handle_autoreply(bot, event): """Handle autoreplies to keywords in messages""" # Test if message is not empty if not event.text: return text = event.text.lower().replace(' ', '') # Test if autoreplies are enabled if not bot.get_config_suboption(event.conv_id, 'autoreplies_enabled'): return # Test if there are actually any autoreplies autoreplies_list = bot.get_config_suboption(event.conv_id, 'autoreplies') if not autoreplies_list: return foundKeyword = False for kwds, sentence in autoreplies_list: for kw in kwds: if find_keyword(kw, text): yield from event.conv.send_message(text_to_segments(sentence)) foundKeyword = True break if foundKeyword == False: yield from event.conv.send_message(text_to_segments('Sorry! I am not yet configured to respond on this.'))
def set(bot, event, *args): """Change configuration for this chat Usage: set [key] [subkey] [...] [value]""" # If we don't have enough args to set a key, return the chat, do nada if len(args) < 2: yield from event.conv.send_message(text_to_segments(_('Not enough arguments'))) return conv_args = ["conversations", event.conv_id] config_args = conv_args + list(args)[:-1] print(config_args, args[-1]) # Set the value for this chat bot.config.set_by_paths(config_args, json.loads(args[-1])) bot.config.save() value = bot.config.get_by_path(config_args) if value is None: value = _('Key not found!') config_path = ' '.join(k for k in config_args[2:]) text = ( '**{}:**\n' '{}' ).format(config_path, json.dumps(value, indent=2, sort_keys=True)) yield from event.conv.send_message(text_to_segments(text))
def define(bot, event, *args): """Define a word using Merriam-Webster Usage: define tautologous""" query = ' '.join(args) url = 'http://www.merriam-webster.com/dictionary/{}'.format(quote(query)) req = requests.get(url) tree = html.fromstring(req.text) # Get the simple definition try: el = tree.xpath('//span[@class="intro-colon"]')[0] except: yield from event.conv.send_message(text_to_segments("Word not found!")) definition = el.getparent().text_content().strip() # Get the word attributes el = tree.xpath('//div[@class="word-attributes"]')[0] attrs = [x.text_content().strip() for x in el.xpath('span')] attrs = ' | '.join(attrs).replace('\\', '/') text = _('{}\n{}\n{}').format(bold(query), italicize(escape_formatting(attrs)), definition) yield from event.conv.send_message(text_to_segments(text))
def cam(bot, event, *args): """Upload a picture from a webcam. Store a new webcam by giving it a webcam name followed by a url to the camera. Usage: cam [webcam] [url]""" cams = bot.config.get_by_path(["webcams"]) if not cams: cams = dict() bot.config.set_by_path(["webcams"], cams) bot.config.save() # See if we're storing a webcam if len(args) > 1 and args[-1].startswith('http'): cam = ' '.join(args[:-1]) url = args[-1] bot.config.set_by_paths(["webcams", cam], url) bot.config.save() yield from event.conv.send_message( text_to_segments('{} saved!'.format(bold(cam)))) else: cam = ' '.join(args) url = cams.get(cam) if url: image_id = yield from bot.upload_images([url]) yield from event.conv.send_message([], image_id=image_id[0]) else: if not cams: yield from event.conv.send_message( text_to_segments('No webcams saved!')) else: text = '{}\n{}'.format(bold('webcams'), ', '.join(cams.keys())) yield from event.conv.send_message(text_to_segments(text))
def cam(bot, event, *args): """Upload a picture from a webcam. Store a new webcam by giving it a webcam name followed by a url to the camera. Usage: cam [webcam] [url]""" cams = bot.config.get_by_path(["webcams"]) if not cams: cams = dict() bot.config.set_by_path(["webcams"], cams) bot.config.save() # See if we're storing a webcam if len(args) > 1 and args[-1].startswith('http'): cam = ' '.join(args[:-1]) url = args[-1] bot.config.set_by_paths(["webcams", cam], url) bot.config.save() yield from event.conv.send_message(text_to_segments('{} saved!'.format(bold(cam)))) else: cam = ' '.join(args) url = cams.get(cam) if url: image_id = yield from bot.upload_images([url]) yield from event.conv.send_message([], image_id=image_id[0]) else: if not cams: yield from event.conv.send_message(text_to_segments('No webcams saved!')) else: text = '{}\n{}'.format(bold('webcams'), ', '.join(cams.keys())) yield from event.conv.send_message(text_to_segments(text))
def notes(bot, event, *args): """Display all saved notes Usage: notes""" config_args = ["notes"] # Make sure there's a notes dictionary try: saved = bot.config.get_by_path(config_args) except: yield from event.conv.send_message(text_to_segments('No notes saved!')) return if not saved: yield from event.conv.send_message(text_to_segments('No notes saved!')) return # Get all of the notes and their infos response = [] for subject in saved: note = saved[subject] text = '{} *by {} at {}*'.format(bold(subject), note['author'], note['timestamp']) response.append(text) yield from event.conv.send_message(text_to_segments('\n'.join(response)))
def lol(bot, event, *args): """Command to fetching data from RiotAPI, usage: /lol <username> /lol list /lol add <username> /lol remove <username> """ api = RiotAPI() apiKey = bot.config.get_by_path(['lol_api_key']) if apiKey is None: yield from event.conv.send_message(text_to_segments('API key is not defined')) raise StopEventHandling if len(args) == 0: yield from event.conv.send_message(text_to_segments('username / command not specified')) raise StopEventHandling api.APIKEY = apiKey playerName = args[0] #ugly if! if (playerName == 'list'): yield from listLol(bot, event, api, *args[1:]) elif (playerName == 'add'): yield from addLol(bot, event, api, *args[1:]) elif (playerName == 'remove'): yield from removeLol(bot, event, *args[1:]) else: player = api.getPlayerByName(playerName) msg = "Player not found" + str(player) if (playerName.lower() == player['name'].lower()): msg = getPlayerInfo(api, player) yield from event.conv.send_message(text_to_segments(msg))
def set(bot, event, *args): """Change configuration for this chat Usage: set [key] [subkey] [...] [value]""" # If we don't have enough args to set a key, return the chat, do nada if len(args) < 2: yield from event.conv.send_message( text_to_segments(_('Not enough arguments'))) return conv_args = ["conversations", event.conv_id] config_args = conv_args + list(args)[:-1] print(config_args, args[-1]) # Set the value for this chat bot.config.set_by_paths(config_args, json.loads(args[-1])) bot.config.save() value = bot.config.get_by_path(config_args) if value is None: value = _('Key not found!') config_path = ' '.join(k for k in config_args[2:]) text = ('**{}:**\n' '{}').format(config_path, json.dumps(value, indent=2, sort_keys=True)) yield from event.conv.send_message(text_to_segments(text))
def conv_refresh(bot, event, conv_name, *args): """Create new conversation with same users as in old one except kicked users (use . for current conversation) Usage: /bot conv_refresh conversation_name [kicked_user_name_1] [kicked_user_name_2] [...]""" conv_name = strip_quotes(conv_name) convs = [event.conv ] if conv_name == '.' else bot.find_conversations(conv_name) kicked_chat_ids = get_unique_users(bot, args) for c in convs: old_chat_ids = {u.id_.chat_id for u in bot.find_users('', conv=c)} new_chat_ids = list(old_chat_ids - set(kicked_chat_ids)) # Create new conversation res = yield from bot._client.createconversation(new_chat_ids, force_group=True) conv_id = res['conversation']['id']['id'] yield from bot._client.setchatname(conv_id, c.name) yield from bot._conv_list.get(conv_id).send_message( text_to_segments( _('**Welcome!**\n' 'This is new refreshed conversation. Old conversation has been ' 'terminated, but you are one of the lucky ones who survived cleansing! ' 'If you are still in old conversation, please leave it.'))) # Destroy old one and leave it yield from bot._client.setchatname(c.id_, _('[TERMINATED] {}').format(c.name)) yield from c.send_message( text_to_segments( _('**!!! WARNING !!!**\n' 'This conversation has been terminated! Please leave immediately!' ))) yield from bot._conv_list.leave_conversation(c.id_)
def conv_refresh(bot, event, conv_name, *args): """Create new conversation with same users as in old one except kicked users (use . for current conversation) Usage: /bot conv_refresh conversation_name [kicked_user_name_1] [kicked_user_name_2] [...]""" conv_name = strip_quotes(conv_name) convs = [event.conv] if conv_name == '.' else bot.find_conversations(conv_name) kicked_chat_ids = get_unique_users(bot, args) for c in convs: old_chat_ids = {u.id_.chat_id for u in bot.find_users('', conv=c)} new_chat_ids = list(old_chat_ids - set(kicked_chat_ids)) # Create new conversation res = yield from bot._client.createconversation(new_chat_ids, force_group=True) conv_id = res['conversation']['id']['id'] yield from bot._client.setchatname(conv_id, c.name) yield from bot._conv_list.get(conv_id).send_message( text_to_segments(_('**Welcome!**\n' 'This is new refreshed conversation. Old conversation has been ' 'terminated, but you are one of the lucky ones who survived cleansing! ' 'If you are still in old conversation, please leave it.')) ) # Destroy old one and leave it yield from bot._client.setchatname(c.id_, _('[TERMINATED] {}').format(c.name)) yield from c.send_message( text_to_segments(_('**!!! WARNING !!!**\n' 'This conversation has been terminated! Please leave immediately!')) ) yield from bot._conv_list.leave_conversation(c.id_)
def handle_command(bot, event): """Handle command messages""" # Test if message is not empty if not event.text: return # Get list of bot aliases aliases_list = bot.get_config_suboption(event.conv_id, 'commands_aliases') if not aliases_list: aliases_list = [default_bot_alias] command_aliases = command.get_command_aliases(bot, event.conv_id) all_list = aliases_list + command_aliases # Test if message starts with bot alias if not find_bot_alias(all_list, event.text): return # Test if command handling is enabled if not bot.get_config_suboption(event.conv_id, 'commands_enabled'): raise StopEventHandling # Parse message line_args = shlex.split(event.text, posix=False) f_name = '' # Test if command length is sufficient if not find_bot_alias(command_aliases, event.text) and len(line_args) < 2: yield from event.conv.send_message( text_to_segments(_('{}: How may I serve you?'+', '.join([str(x) for x in command_aliases])).format(event.user.full_name)) ) raise StopEventHandling elif find_bot_alias(command_aliases, event.text): f_name = line_args[0][1:].lower() else: f_name = line_args[1].lower() # Test if user has permissions for running command commands_admin_list = command.get_admin_commands(bot, event.conv_id) if commands_admin_list and (f_name in commands_admin_list): admins_list = bot.get_config_suboption(event.conv_id, 'admins') if event.user_id.chat_id not in admins_list: yield from event.conv.send_message( text_to_segments(_('{}: I\'m sorry, Dave. I\'m afraid I can\'t do that.').format(event.user.full_name)) ) raise StopEventHandling # Run command if find_bot_alias(command_aliases, event.text): new_args = line_args[:] new_args[0] = new_args[0][1:] yield from command.run(bot, event, *new_args) else: yield from command.run(bot, event, *line_args[1:]) # Prevent other handlers from processing event raise StopEventHandling
def countdown(bot, event, *args): """Countdown from a given number to 1 Usage: countdown 7""" start = int(args[0]) if args else 5 while start: start -= 1 yield from event.conv.send_message(text_to_segments(str(start + 1))) time.sleep(1) text = random.choice(["KABLOOM!", "WHOO!", "PARTY!", "GO!", "HAIL SKYNET!"]) yield from event.conv.send_message(text_to_segments(text))
def handle_command(bot, event): """Handle command messages""" # Test if message is not empty if not event.text: return # Get list of bot aliases aliases_list = bot.get_config_suboption(event.conv_id, 'commands_aliases') if not aliases_list: aliases_list = [default_bot_alias] # Test if message starts with bot alias if not find_bot_alias(aliases_list, event.text): return # Test if command handling is enabled if not bot.get_config_suboption(event.conv_id, 'commands_enabled'): raise StopEventHandling # Parse message line_args = shlex.split(event.text, posix=False) # Test if command length is sufficient if len(line_args) < 2: yield from event.conv.send_message( text_to_segments(_('{}: How may I serve you?').format(event.user.full_name)) ) raise StopEventHandling # Test if user has permissions for running command commands_admin_list = command.get_admin_commands(bot, event.conv_id) if commands_admin_list and line_args[1].lower() in commands_admin_list: admins_list = bot.get_config_suboption(event.conv_id, 'admins') if event.user.full_name not in admins_list: yield from event.conv.send_message( text_to_segments(_('{}: I\'m sorry. I can\'t do that.').format(event.user.full_name)) ) raise StopEventHandling #use the nltk to get the noun word. conv = str(" ".join(str(x) for x in line_args[1:])) tokens = TextBlob(conv) keyword = [] for word, pos in tokens.tags: if pos == 'NN' or pos == 'VB': keyword.append(word) print(str(keyword)) # Run command yield from command.run(bot, event, keyword, *line_args[1:]) # Prevent other handlers from processing event raise StopEventHandling
def countdown(bot, event, *args): """Countdown from a given number to 1 Usage: countdown 7""" start = int(args[0]) if args else 5 while start: start -= 1 yield from event.conv.send_message(text_to_segments(str(start + 1))) time.sleep(1) text = random.choice( ["KABLOOM!", "WHOO!", "PARTY!", "GO!", "HAIL SKYNET!"]) yield from event.conv.send_message(text_to_segments(text))
def magnet(bot, event, *args): """Get the magnet link from the last list of torrents searched Usage: magnet 3""" magnets = bot.config.get_by_path(["conversations", event.conv_id, "torrent_links"]) if magnets: magnet = magnets.get(int(args[0])) if magnet: yield from event.conv.send_message(text_to_segments(magnet)) return else: yield from event.conv.send_message(text_to_segments("No such search result")) else: yield from event.conv.send_message(text_to_segments('No recent torrent searches'))
def handle_command(bot, event): """Handle command messages""" # Test if message is not empty if not event.text: return # Get list of bot aliases aliases_list = bot.get_config_suboption(event.conv_id, 'commands_aliases') if not aliases_list: aliases_list = [default_bot_alias] # Test if message starts with bot alias if not find_bot_alias(aliases_list, event.text): return # Test if command handling is enabled if not bot.get_config_suboption(event.conv_id, 'commands_enabled'): raise StopEventHandling # Parse message line_args = shlex.split(event.text, posix=False) # Test if command length is sufficient if len(line_args) < 2: yield from event.conv.send_message( text_to_segments(_('{}: 무엇을 도와드릴까요?').format(event.user.full_name)) ) raise StopEventHandling # Test if user has permissions for running command commands_admin_list = command.get_admin_commands(bot, event.conv_id) if commands_admin_list and line_args[1].lower() in commands_admin_list: admins_list = bot.get_config_suboption(event.conv_id, 'admins') if event.user_id.chat_id not in admins_list: yield from event.conv.send_message( text_to_segments(_('{}: 권한이 없습니다.').format(event.user.full_name)) ) raise StopEventHandling # Run command yield from command.run(bot, event, *line_args[1:]) #Check whether the bot alias is too long or not if is_bot_alias_too_long(event.text): yield from event.conv.send_message( text_to_segments(_('**Tip**: /bot 대신에 /b, /, ! 등을 사용할 수 있어요')) ) # Prevent other handlers from processing event raise StopEventHandling
def wiki(bot, event, *args): """Busca algo en la wikipedia\n Uso: bot wiki [Busqueda] """ nombre = ' '.join(args) busqueda = '_'.join(args) link = 'http://es.wikipedia.org/w/index.php?search={}'.format(busqueda) text = _('{} en Wikipedia: ' + '\n {}').format(nombre, link) yield from event.conv.send_message(text_to_segments(text))
def clever(bot, event, cmd=None, *args): """Turn clever replies on or off, optionally setting a chance of responding Usage: clever [off|on|1/5]""" if cmd == 'off' or cmd is None: var = "clever_enabled" val = False text = _("Reverting to normal bot mode *beep boop*") elif cmd == 'on': var = "clever_enabled" val = True text = _("Mind if I join in on this conversation?") else: text = ' '.join([cmd] + list(args)) print('"{}"'.format(text)) matches = re.findall('^(\d+) ?/ ?(\d+)$', text) if matches: [(a, b)] = matches var = "clever_chance" val = int(a) / int(b) text = _("I'll try to be clever {:.0%} of the time").format(val) else: return try: is_set = bot.config.get_by_path(["conversations", event.conv_id, var]) == val except: is_set = False if not is_set: bot.config.set_by_paths(["conversations", event.conv_id, var], val) bot.config.save() yield from event.conv.send_message(text_to_segments(text))
def este(bot, event, *args): """Los [ro]bots no soportan las paradojas\n Uso: <bot> Este enunciado es mentira [frase]""" arg = ' '.join(args) text = '???' if arg == 'enunciado es mentira': text = _('No pienses en ello, no pienses en ello, no pienses en ello') yield from event.conv.send_message(text_to_segments(text))
def sino(bot, event, *args): """Simplemente te dice Si o No.\n Uso: <bot> sino [frase]""" if (randint(0, 1)) == 1: text = 'Si' else: text = 'No' yield from event.conv.send_message(text_to_segments(text))
def verdad(bot, event, *args): """Responde al azar si es verdad o no.\n Uso: <bot> verdad [frase]""" if (randint(0, 1)) == 1: text = 'Si' else: text = 'No' yield from event.conv.send_message(text_to_segments(text))
def como(bot, event, *args): """Preguntarle como esta al bot\nUso: <bot> como estas?""" arg = ' '.join(args) text = '???' if arg == 'estas?' or 'estas' or 'estas??': text = 'Bien, gracias' yield from event.conv.send_message(text_to_segments(text))
def sudo(bot, event, *args): """Permisos de administrador! (o no)\n Uso: [bot] sudo make me a sandwich""" arg = ' '.join(args) text = '???' if arg == 'make me a sandwich' or 'sandwich' or 'make me a sándwich' or 'sándwich': text = 'A sus ordenes, un sandwich enseguida' yield from event.conv.send_message(text_to_segments(text))
def buen(bot, event, que, *args): """Que bueno es el bot\b <bot> buen (bot)""" if strip_quotes(que) == "bot": text = _('Gracias, me esfuerzo') else: text = _('QUE?') yield from event.conv.send_message(text_to_segments(text))
def make(bot, event, *args): """Make me a sandiwch \n Uso: <bot> make me a sandwich""" arg = ' '.join(args) text = '???' if arg == 'me a sandwich' or 'sandwich' or 'me a sándwich' or 'sándwich': text = 'Que? no, haztelo tu' yield from event.conv.send_message(text_to_segments(text))
def autotranslate(bot, event): """Translate all messages in a chat to a predefined language""" # Test if message is not empty if not event.text: return # Test if automatic translations are enabled try: enabled = bot.config.get_by_path(["conversations", event.conv_id, "translate_all", "enabled"]) except: enabled = False if not enabled: return # Don't process anything that begins with the command character commands_character = bot.get_config_suboption(event.conv_id, 'commands_character') if event.text.startswith(commands_character): return # Translate the last message try: lang = bot.config.get_by_path(["conversations", event.conv_id, "translate_all", "language"]) except: try: lang = bot.get_config_suboption(event.conv_id, 'translate_default') except: lang = None if not lang: lang = "es" yield from event.conv.send_message(text_to_segments(_translate(event.text, lang))) # Stop commands from running while translating in a solo chat raise StopEventHandling
def clever_responder(bot, event): """Handle clever replies to messages""" # Test if message is not empty if not event.text: return # Test if clever replies are enabled enabled = bot.get_config_suboption(event.conv_id, 'clever_enabled') if not enabled: return # Don't process anything that begins with the command character commands_character = bot.get_config_suboption(event.conv_id, 'commands_character') if event.text.startswith(commands_character): return # Determine odds of replying chance = bot.get_config_suboption(event.conv_id, 'clever_chance') if chance: # If we only reply to every 1/ X messages, # see if a random float is greater than those odds if random.random() > chance: return # Grab or create a cleverbot client for this chat client = cleverbot.clients.get(event.conv_id, cleverbot.Cleverbot()) # Get a response from cleverbot response = client.ask(event.text) yield from event.conv.send_message(text_to_segments(response)) # Stop other handlers from processing event raise StopEventHandling
def _kill_scrabble(bot, event, seconds=15): print("starting scrabble timer") scrabble_args = ['conversations', event.conv_id, 'scrabble'] scrabble_opts = bot.config.get_by_path(scrabble_args) yield from asyncio.sleep(seconds) print("scrabble timer finished") # Format the results and update the leaderboard points = sorted(scrabble_opts['points']['current'].items(), key=lambda x: x[1], reverse=True) for i in range(0, len(points)): points[i] = list(points[i]) user = points[i][0] user_overall = scrabble_opts['points']['overall'].get(user, 0) user_overall += points[i][1] points[i].append(user_overall) bot.config.set_by_paths(scrabble_args + ['points', 'overall', user], user_overall) print(points) text = '**Game Over**\n{}'.format('\n'.join( ['%s: %s *(%s overall)*' % (x, y, z) for (x, y, z) in points])) # Reset the game print("resetting scrabble") bot.config.set_by_paths(scrabble_args + ['letters'], list()) bot.config.set_by_paths(scrabble_args + ['guesses'], list()) bot.config.set_by_paths(scrabble_args + ['points', 'current'], dict()) bot.config.save() print("sending message to chat") yield from event.conv.send_message(text_to_segments(_(text)))
def handle_autoreply(bot, event): """Handle autoreplies to keywords in messages""" # Test if message is not empty if not event.text: return # Test if autoreplies are enabled if not bot.get_config_suboption(event.conv_id, 'autoreplies_enabled'): return # Test if there are actually any autoreplies autoreplies_list = bot.get_config_suboption(event.conv_id, 'autoreplies') if not autoreplies_list: return for kwds, sentence in autoreplies_list: for kw in kwds: if find_keyword(kw, event.text): if not is_image(sentence): yield from event.conv.send_message(text_to_segments(sentence)) return else: image_id_list = yield from bot.upload_images([sentence]) yield from event.conv.send_message([], image_id=image_id_list[0]) return
def choose(bot, event, *args): """Choose an item from a list Usage: choose item1 item2 item3...""" if args: result = random.choice(args) yield from event.conv.send_message(text_to_segments(result))
def tip(bot, event, *args): """Tipear fedora o trilby\n <bot> tip <fedora/trilby>""" arg = ' '.join(args) text = '???' if arg == 'fedora' or 'trilby': text = 'https://youtu.be/oe9uK9QGCUI' yield from event.conv.send_message(text_to_segments(text))
def torrent(bot, event, *args): """Start torrenting a result from the last list of torrents searched Usage: torrent 3""" magnets = bot.config.get_by_path(["conversations", event.conv_id, "torrent_links"]) if magnets: magnet = magnets.get(int(args[0])) if magnet: torrent = rpc_client.add_torrent(magnet) text = "Added {}".format(bold(torrent.name)) yield from event.conv.send_message(text_to_segments(text)) return else: yield from event.conv.send_message(text_to_segments("No such search result")) else: yield from event.conv.send_message(text_to_segments('No recent torrent searches'))
def torrents(bot, event, *args): """Get a list of torrents being downloaded / seeded Usage: torrents""" torrents = rpc_client.get_torrents() texts = [] for torrent in torrents: text = "{} {:0.1f}%".format(bold(torrent.name), torrent.progress) if torrent.status == 'downloading': seconds = torrent.eta.seconds % 60 minutes = int(torrent.eta.seconds / 60) hours = int(minutes / 60) if minutes > 60: minutes = minutes % 60 times = [ str(hours) + "h" if hours else "", str(minutes) + "m" if minutes else "", str(seconds) + "s" ] text += " *({})*".format(" ".join(times).strip()) else: text += " " + italicize(torrent.status) texts.append(text) yield from event.conv.send_message(text_to_segments("\n".join(texts)))
def _kill_scrabble(bot, event, seconds=15): print("starting scrabble timer") scrabble_args = ['conversations', event.conv_id, 'scrabble'] scrabble_opts = bot.config.get_by_path(scrabble_args) yield from asyncio.sleep(seconds) print("scrabble timer finished") # Format the results and update the leaderboard points = sorted(scrabble_opts['points']['current'].items(), key=lambda x: x[1], reverse=True) for i in range(0, len(points)): points[i] = list(points[i]) user = points[i][0] user_overall = scrabble_opts['points']['overall'].get(user, 0) user_overall += points[i][1] points[i].append(user_overall) bot.config.set_by_paths(scrabble_args + ['points', 'overall', user], user_overall) print(points) text = '**Game Over**\n{}'.format( '\n'.join(['%s: %s *(%s overall)*' % (x, y, z) for (x, y, z) in points]) ) # Reset the game print("resetting scrabble") bot.config.set_by_paths(scrabble_args + ['letters'], list()) bot.config.set_by_paths(scrabble_args + ['guesses'], list()) bot.config.set_by_paths(scrabble_args + ['points', 'current'], dict()) bot.config.save() print("sending message to chat") yield from event.conv.send_message(text_to_segments(_(text)))
def handle_membership_change(bot, event): """Handle conversation membership change""" # Test if watching for membership changes is enabled if not bot.get_config_suboption(event.conv_id, 'membership_watching_enabled'): return # Generate list of added or removed users event_users = [event.conv.get_user(user_id) for user_id in event.conv_event.participant_ids] names = ', '.join([user.full_name for user in event_users]) # JOIN if event.conv_event.type_ == hangups.MembershipChangeType.JOIN: # Test if user who added new participants is admin admins_list = bot.get_config_suboption(event.conv_id, 'admins') if event.user_id.chat_id in admins_list: yield from event.conv.send_message( text_to_segments(_('{}: Welcome!').format(names)) ) else: text = _( '**!!! WARNING !!!**\n' '{} invited user {} without authorization!\n' '\n' '{}: Please leave this conversation immediately!' ).format(event.user.full_name, names, names) bot.send_message(event.conv, text) # LEAVE else: bot.send_message(event.conv, _('{} has jilted us :-( Hasta la vista, baby!').format(names))
def handle_membership_change(bot, event): """Handle conversation membership change""" # Test if watching for membership changes is enabled if not bot.get_config_suboption(event.conv_id, 'membership_watching_enabled'): return # Generate list of added or removed users event_users = [event.conv.get_user(user_id) for user_id in event.conv_event.participant_ids] names = ', '.join([user.full_name for user in event_users]) # JOIN if event.conv_event.type_ == hangups.MEMBERSHIP_CHANGE_TYPE_JOIN: # Test if user who added new participants is admin admins_list = bot.get_config_suboption(event.conv_id, 'admins') if event.user_id.chat_id in admins_list: yield from event.conv.send_message( text_to_segments(_('{}: Welcome!').format(names)) ) else: text = _( '**!!! WARNING !!!**\n' '{} invited user {} without authorization!\n' '\n' '{}: Please leave this conversation immediately!' ).format(event.user.full_name, names, names) bot.send_message(event.conv, text) # LEAVE else: bot.send_message(event.conv, _('{} has jilted us :-( Hasta la vista, baby!').format(names))
def help(bot, event, cmd=None, *args): """Help me, Obi-Wan Kenobi. You're my only hope. Usage: help [command]""" cmd = cmd if cmd else 'help' try: command_fn = command.commands[cmd] except KeyError: yield from command.unknown_command(bot, event) return text = _('**{}:**\n' '{}').format(cmd, _(command_fn.__doc__)) if cmd == 'help': # See if the user has admin privileges to limit commands displayed admins_list = bot.get_config_suboption(event.conv_id, 'admins') if event.user_id.chat_id not in admins_list: command_list = command.get_user_commands(bot, event.conv_id) else: command_list = command.commands.keys() text += _('\n\n' '**Supported commands:**\n' '{}').format(', '.join(sorted(command_list))) yield from event.conv.send_message(text_to_segments(text))
def test(bot, event, *args): cmd = 'echo "yuhuu..."' process = subprocess.Popen( cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE ) out = process.communicate()[0] yield from event.conv.send_message(text_to_segments('output: ' + str(out)))
def config(bot, event, cmd=None, *args): """Zobrazí nebo upraví konfiguraci bota Parametry: /bot config [get|set] [key] [subkey] [...] [value]""" if cmd == 'get' or cmd is None: config_args = list(args) value = bot.config.get_by_path(config_args) if config_args else dict(bot.config) elif cmd == 'set': config_args = list(args[:-1]) if len(args) >= 2: bot.config.set_by_path(config_args, json.loads(args[-1])) bot.config.save() value = bot.config.get_by_path(config_args) else: yield from command.unknown_command(bot, event) return else: yield from command.unknown_command(bot, event) return if value is None: value = 'Parameter does not exist!' config_path = ' '.join(k for k in ['config'] + config_args) segments = [hangups.ChatMessageSegment('{}:'.format(config_path), is_bold=True), hangups.ChatMessageSegment('\n', hangups.SegmentType.LINE_BREAK)] segments.extend(text_to_segments(json.dumps(value, indent=2, sort_keys=True))) bot.send_message_segments(event.conv, segments)
def fortune(bot, event, *args): cmd = '/usr/games/fortune' process = subprocess.Popen( cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE#, shell=True ) out = process.communicate()[0] yield from event.conv.send_message(text_to_segments(str(out)))
def quit(bot, event, *args): """Oh my God! They killed Kenny! You bastards!""" print( _('HangupsBot killed by user {} from conversation {}').format( event.user.full_name, get_conv_name(event.conv, truncate=True))) yield from event.conv.send_message(text_to_segments(_('Et tu, Brute?'))) yield from bot._client.disconnect()
def config(bot, event, cmd=None, *args): """Show or change bot configuration Usage: /bot config [get|set] [key] [subkey] [...] [value]""" if cmd == 'get' or cmd is None: config_args = list(args) value = bot.config.get_by_path(config_args) if config_args else dict(bot.config) elif cmd == 'set': config_args = list(args[:-1]) if len(args) >= 2: bot.config.set_by_path(config_args, json.loads(args[-1])) bot.config.save() value = bot.config.get_by_path(config_args) else: yield from command.unknown_command(bot, event) return else: yield from command.unknown_command(bot, event) return if value is None: value = _('Key not found!') config_path = ' '.join(k for k in ['config'] + config_args) text = ( '**{}:**\n' '{}' ).format(config_path, json.dumps(value, indent=2, sort_keys=True)) yield from event.conv.send_message(text_to_segments(text))
def config(bot, event, cmd=None, *args): """Show or change bot configuration Usage: config [get | set] [key] [subkey] [...] [value]""" if cmd == 'get' or cmd is None: config_args = list(args) value = bot.config.get_by_path(config_args) if config_args else dict( bot.config) elif cmd == 'set': config_args = list(args[:-1]) if len(args) >= 2: bot.config.set_by_path(config_args, json.loads(args[-1])) bot.config.save() value = bot.config.get_by_path(config_args) else: yield from command.unknown_command(bot, event) return else: yield from command.unknown_command(bot, event) return if value is None: value = _('Key not found!') config_path = ' '.join(k for k in ['config'] + config_args) text = ('**{}:**\n' '{}').format(config_path, json.dumps(value, indent=2, sort_keys=True)) yield from event.conv.send_message(text_to_segments(text))
def handle_image(bot, event): """Handle autoreplies to keywords in messages""" # Test if message is not empty if not event.text: return # Test if autoreplies are enabled #if not bot.get_config_suboption(event.conv_id, 'autoreplies_enabled'): # return # Test if there are actually any autoreplies #autoreplies_list = bot.get_config_suboption(event.conv_id, 'autoreplies') #if not autoreplies_list: # return links = re.findall('(https?://\S+(?:jpg|gif|png))', event.text) if len(links) == 0: return for link in links: file_end = re.search('(...)$', link) file_path = '/tmp/hg-image-' + str(random.randint(0,100))+'.'+file_end.groups()[0] download(link, file_path) file = open(file_path, 'rb') yield from event.conv.send_message(text_to_segments(''), file) file.close() os.remove(file_path)
def user_find(bot, event, user_name="", *args): """Find users known to bot by their name Usage: /bot user_find [user_name]""" user_name = strip_quotes(user_name) text = [_('**Search results for user name "{}":**').format(user_name)] for u in bot.find_users(user_name): text.append(user_to_text(u)) yield from event.conv.send_message(text_to_segments("\n".join(text)))
def quit(bot, event, *args): """Oh my God! They killed Kenny! You bastards!""" print(_('HangupsBot killed by user {} from conversation {}').format( event.user.full_name, get_conv_name(event.conv, truncate=True) )) yield from event.conv.send_message(text_to_segments(_('Et tu, Brute?'))) yield from bot._client.disconnect()
def conv_send(bot, event, conv_name, *args): """Send message to conversation as bot (use . for current conversation) Usage: /bot conv_send conversation_name text""" conv_name = strip_quotes(conv_name) convs = [event.conv] if conv_name == '.' else bot.find_conversations(conv_name) for c in convs: yield from c.send_message(text_to_segments(' '.join(args)))
def spoof(bot, event, *args): """Spoof IngressBot on specified GPS coordinates Usage: /bot spoof latitude,longitude [hack|fire|deploy|mod] [level] [count]""" link = 'https://plus.google.com/u/0/{}/about'.format(event.user.id_.chat_id) text = _( '**!!! WARNING !!!**\n' 'Agent {} ({}) has been reported to Niantic for attempted spoofing!' ).format(event.user.full_name, link) yield from event.conv.send_message(text_to_segments(text))
def conv_leave(bot, event, conv_name='', *args): """Leave current (or specified) conversation Usage: /bot conv_leave [conversation_name]""" conv_name = strip_quotes(conv_name) convs = [event.conv] if not conv_name or conv_name == '.' else bot.find_conversations(conv_name) for c in convs: yield from c.send_message(text_to_segments(_('I\'ll be back!'))) yield from bot._conv_list.leave_conversation(c.id_)
def conv_refresh(bot, event, conv_name, *args): """Create new conversation with same users as in old one except kicked users (use . for current conversation) Usage: /bot conv_refresh conversation_name [kicked_user_name_1] [kicked_user_name_2] [...]""" conv_name = strip_quotes(conv_name) convs = [event.conv] if conv_name == '.' else bot.find_conversations(conv_name) kicked_chat_ids = get_unique_users(bot, args) for c in convs: new_chat_ids = {u for u in bot.find_users('', conv=c) if u.id_.chat_id not in set(kicked_chat_ids)} invitee_ids = [InviteeID( gaia_id=u.id_.gaia_id, fallback_name=u.full_name ) for u in new_chat_ids] # Create new conversation request = hangouts_pb2.CreateConversationRequest( request_header=bot._client.get_request_header(), type=hangouts_pb2.CONVERSATION_TYPE_GROUP, client_generated_id=bot._client.get_client_generated_id(), name=c.name, invitee_id=invitee_ids ) res = yield from bot._client.create_conversation(request) conv_id = res.conversation.conversation_id.id bot._conv_list.add_conversation(res.conversation) conv = bot._conv_list.get(conv_id) yield from conv.rename(c.name) yield from conv.send_message( text_to_segments(('**Welcome!**\n' 'This is the new refreshed conversation. Old conversation has been ' 'terminated, but you are one of the lucky ones who survived cleansing! ' 'If you are still in old conversation, please leave it.')) ) # Destroy old one and leave it yield from c.rename(('[TERMINATED] {}').format(c.name)) yield from c.send_message( text_to_segments(('**!!! WARNING !!!**\n' 'This conversation has been terminated! Please leave immediately!')) ) yield from c.leave()
def adminify(bot, event, user_name='', *args): """Add user as admin by name or ID Usage: adminify [user_name|ID]""" username = strip_quotes(user_name) matches = bot.find_users(user_name) if matches > 1: text = [_('**Multiple matches for name "{}":**').format(user_name)] for match in matches: text.append(user_to_text(match)) yield from event.conv.send_message(text_to_segments('\n'.join(text))) else: pass
def conv_create(bot, event, conv_name, *args): """Create new conversation and invite users to it Usage: /bot conv_create conversation_name [user_name_1] [user_name_2] [...]""" conv_name = strip_quotes(conv_name) chat_id_list = get_unique_users(bot, args) if not chat_id_list: yield from command.unknown_command(bot, event) return res = yield from bot._client.createconversation(chat_id_list, force_group=True) conv_id = res['conversation']['id']['id'] yield from bot._client.setchatname(conv_id, conv_name) yield from bot._conv_list.get(conv_id).send_message(text_to_segments(_('Welcome!')))
def removeLol(bot, event, *args): if (len(args) != 1): yield from event.conv.send_message(text_to_segments("One player name required")) raise StopEventHandling playerName = args[0] players = bot.get_config_suboption(event.conv_id, "lol_players") delta = len(players) for p in players: if(p['name'].lower() == playerName.lower()): players.remove(p) bot.config.set_by_path(["conversations", event.conv_id, "lol_players"], players) delta = delta - len(players) msg = "Player not found" if(delta == 1): msg = "Player " + playerName + " removed" bot.config.changed = True elif(delta > 1): msg = delta + " players removed" bot.config.changed = True bot.config.save() yield from event.conv.send_message(text_to_segments(msg))
def aktion(bot, event, *args): """Aktionsstand in der Mensa Usage: /mensa aktion [tag] tag: morgen oder wochentag (Montag, Mittwoch,...)""" url = get_url(args) soup = get_soup(url) text = _( '**{}**\n\n' '**Aktionsstand**\n' '{}' ).format(get_date(soup), get_foods(soup,'.special')) yield from event.conv.send_message(text_to_segments(text))
def addLol(bot, event, api, *args): playerName = args[0] player = api.getPlayerByName(playerName) msg = "Player not found" if (playerName.lower() == player['name'].lower()): players = bot.get_config_suboption(event.conv_id, "lol_players") if players is None: players = [] bot.config.set_by_path(["conversations", event.conv_id, "lol_players"], players + [player]) bot.config.changed = True bot.config.save() msg = player['name'] + " on " + str(player['summonerLevel']) + " level was added" yield from event.conv.send_message(text_to_segments(msg))
def suppe(bot, event, *args): """Suppen in der Mensa Usage: /mensa suppe [tag] tag: morgen oder wochentag (Montag, Mittwoch,...)""" url = get_url(args) soup = get_soup(url) text = _( '**{}**\n\n' '**Suppen**\n' '{}' ).format(get_date(soup), get_foods(soup,'.soups')) yield from event.conv.send_message(text_to_segments(text))