def _confirm_project_settings(self, model): """ Prompt for confirmation, showing the user the settings they have specified for the project. It is *hoped* that this will reduce errors in the setup of projects, especially for the time of the booking. """ question_text = _( "You are about to create a project with the details:\n\n" \ "Client Name : %s\n" \ "Project Name : %s\n\n" \ "Start Time : %s\n" \ "End Time : %s\n\n" \ "ARE THESE DETAILS CORRECT? ") \ % (model.client_name, model.project_name, TimePresenter(model.start_time.time()), TimePresenter(model.end_time.time()) ) response = self._form.showQuestion(_("Project Exists"), question_text) if response == QMessageBox.No: return False return True
def create_project(self): """ Create a new project and booking via the rails api. """ model = self._create_model_from_form(self.pp_form_view) errors = model.verify(self.projects) if len(errors) > 0: self._form.showErrors("Please correct the following errors", errors) return # Ask the user to confirm the propect settings if not self._confirm_project_settings(model): return # if there are errors with creating the project they will be returned # as an array errors = model.create_project(self.rdb_proxy) if errors != None: # If there are errors it is likely to be because there is an # existing project which the settings clash with if self._prompt_use_existing_project(errors, model): model.uuid = self.rdb_proxy.find_project(model.client_name, model.project_name) else: return # We *should* have a model with a valid uuid for a project at this # point, if not show an error and return if model.uuid <= 0: msg = _("Could not create or obtain project id - unrecoverable " \ "internal error. (This shouldn't happen of course)") self._form.showError("There Were Errors", msg) return # attempt to create a booking errors = model.create_booking(self.rdb_proxy) if errors != None: self._form.showErrors("Could Not Create Booking", errors) return # We had no errors but we dont have a booking_id. The technical term # if this happens is WTF? if model.booking_id <= 0: msg = _("Could not create or obtain booking id - unrecoverable " \ "internal error. (This shouldn't happen of course)") self._form.showErrors(_("There Were Errors"), msg) return # Hide the forms and switch to the recorder window via the application # controller self.pp_list_view.hide() self.pp_form_view.hide() self.emit(SIGNAL("ShowRecorder"), model)
def lunch_time(self): """Say something at noon. Automatic sends a random message every week day 12pm. """ feeling_hungry = [ _('Lunch time'), _('I\'m gonna get something to eat') ] to_say = random.choice(feeling_hungry) for channel in list(self.bot.channels): self.bot.privmsg(channel, to_say)
async def handle_message(self, mask=None, event=None, target=None, data=None): """Handles channel's messages. Args: mask: An IrcString containing useful information. event: The IRC event, it can be PRIVMSG or NOTICE. target: Channel name. data: The message sent to the channel. """ if self.channel_rules and type(self.channel_rules) is list: try: # Verifies if any rule match with the given text message, # if it does, executes its callback. for rule, func in self.channel_rules: match = rule.search(data) if match: await func(target, match.group(1).encode('utf-8')) except Exception as e: print(e) self.bot.privmsg(target, _('Booom shakalaka')) await self.slack_meter(target, mask.nick, data)
def _prompt_use_existing_project(self, errors, model): """ Helper, tidies up create_project. """ question_text = _("The client '%s', already has a project named '%s'" \ ". Would you like to use this project? ") \ % (model.client_name, model.project_name) if "\n".join("".join(item[1]) for item in errors.items() ).find("already been taken") > 0: if self._form.showQuestion(_("Project Exists"), question_text) == QMessageBox.No: return False return True
async def horoscope(self, mask, target, args): """Prints daily horoscope. Signs: Aquarius, Aries, Cancer, Capricorn, Gemini, Leo, Libra, Pisces, Sagittarius, Scorpio, Taurus, Virgo. %%horoscope <sign> """ zodiac_signs = [ 'Aquarius', 'Aries', 'Cancer', 'Capricorn', 'Gemini', 'Leo', 'Libra', 'Pisces', 'Sagittarius', 'Scorpio', 'Taurus', 'Virgo' ] wished = (args.get('<sign>') or '').capitalize() if wished not in zodiac_signs: return f'{wished} is not a valid sign.' url = f'http://horoscope-api.herokuapp.com/horoscope/today/{wished}' async with aiohttp.ClientSession() as session: async with session.get(url) as response: response = await response.json() msg = _('I\'m sorry but the stars seems to be unreachable.') if response: horoscope = response.get('horoscope', '') if horoscope: msg = horoscope return msg
def good_morning(self): """Says something in the morning. Automatic sends a random message every week day 9am. """ feeling_sleepy = [ _('Good morning'), _('Good morning fellas'), _('Morning'), _('Hello everyone'), _('I definitely need a coffee. Oh, hello btw.') ] to_say = random.choice(feeling_sleepy) for channel in list(self.bot.channels): self.bot.privmsg(channel, to_say)
async def about(self, mask, target, args): """Prints about message. %%about """ message = _( ('Hi there, my name is {nick} and I am an IRC bot ' 'written in Python. If you wanna know more about me take ' 'a look at my Github page https://github.com/meleca/mr-roboto/. ' 'Currently running v{version}.')).format(nick=self.bot.nick, version=self.bot.version) self.bot.privmsg(target, message)
async def greeting(self, mask, target, args): """Saves a new greeting message to a specific nick. %%greeting <nick> <message>... """ try: table = self.bot.dataset['greetings'] channel = target.replace('#', '') nick = args['<nick>'].lower() message = ' '.join(args['<message>']) result = table.find_one(channel=channel, nick=nick) or {} options = '\n'.join([result.get('options', ''), message]) table.upsert( { 'channel': channel, 'nick': nick, 'options': options, }, ['channel', 'nick']) return _('Okie dokie') except Exception: return _('Sorry, looks like something went wrong :(')
async def joke(self, mask, target, args): """Prints a Joke. You can also pass a subject for an especific kind of joke. The available subjects are: 'chuck norris', and 'yo momma' %%joke [<subject>...] """ jokes_api = { 'icndb': 'http://api.icndb.com/jokes/random?escape=javascript', 'yomomma': 'http://api.yomomma.info/', } subject = None if '<subject>' in args and len(args['<subject>']) > 0: subject_list = [s.lower() for s in args['<subject>']] subject = ' '.join(subject_list) url = None if subject == 'chuck norris': url = jokes_api['icndb'] elif subject == 'yo momma': url = jokes_api['yomomma'] else: url = random.choice(list(jokes_api.values())) try: async with aiohttp.ClientSession() as session: async with session.get(url) as response: response = await response.json(content_type=None) # There are two different possible structures for the # response, one has a `joke` field at the response root, # and the other one has the `joke` field inside an element # cablled `value`, so we must try both in order to # reach the text. if type(response) is dict: if 'joke' in response: return response['joke'] elif ('value' in response and type(response['value']) is dict and 'joke' in response['value']): return response['value']['joke'] # No joke? That it is really sad :( raise Exception('No joke found') except Exception as e: print(e) return _('All work and no play makes Jack a dull boy')
def handle_text(target, subtype, data, charset='utf-8'): try: content = str(data, encoding=charset) except UnicodeDecodeError as e: data = data[:e.end - 1] if data: handle_text(target, subtype, data, charset) return else: self.bot.privmsg( target, _('It seems this site has a broken charset')) return page = html.fromstring(content) title = page.findtext('.//title') if title: history['title'] = title.strip() self.bot.privmsg(target, f'[{history.get("title")}]')
def say_hi(self, mask=None, channel=None): """Greets everyone who joins the channel. Args: mask: An IrcString containing useful information. channel: Channel name. """ if self.bot.nick != mask.nick: message = _('{nick}: Hi!').format(nick=mask.nick) nick = mask.nick.lower() table = self.bot.dataset['greetings'] result = table.find_one(channel=channel.replace('#', ''), nick=nick) or {} if result.get('options', ''): greeting = random.choice(result['options'].splitlines()) message = f'{mask.nick}: {greeting}' self.bot.privmsg(channel, message)
async def handle_url(self, target, url): """Handler for URLs. Attempts to load the URL address, if no problem occur it checks the response in order to validate its type and send the page title back to the channel if available. At the end updates the URLs history. Args: target: Channel name. url: A valid URL. """ history = { 'channel': target.replace('#', ''), 'url': url.decode('utf-8'), 'title': '', 'datetime': datetime.utcnow() } def handle_text(target, subtype, data, charset='utf-8'): try: content = str(data, encoding=charset) except UnicodeDecodeError as e: data = data[:e.end - 1] if data: handle_text(target, subtype, data, charset) return else: self.bot.privmsg( target, _('It seems this site has a broken charset')) return page = html.fromstring(content) title = page.findtext('.//title') if title: history['title'] = title.strip() self.bot.privmsg(target, f'[{history.get("title")}]') def handle_image(target, subtype, data): self.bot.privmsg(target, _('Looks like an image')) def handle_audio(target, subtype, data): self.bot.privmsg(target, _('Do you know I\'m deaf right?')) def handle_video(target, subtype, data): self.bot.privmsg(target, _('For God sake I\'m blind')) def handle_default(target, subtype, data): self.bot.privmsg(target, _('What kind of weed is that?')) type_handlers = { u'text': handle_text, u'image': handle_image, u'audio': handle_audio, u'video': handle_video } async with aiohttp.ClientSession() as session: async with session.get(url.decode('utf-8')) as request: # Extract mime type. rule = re.compile(r'^(\w+)/([\w\-\+]+)( *;.*)?$') match = rule.search(request.headers['CONTENT-TYPE']) if not match: self.bot.privmsg( target, _('My sources say that this links does not exists')) return mime_type = match.group(1) subtype = match.group(2) data = await request.read() if mime_type in type_handlers: if mime_type == u'text' and request.charset: type_handlers[mime_type](target, subtype, data, request.charset) else: type_handlers[mime_type](target, subtype, data) else: handle_default(target, subtype, data) table = self.bot.dataset['url_history'] table.upsert(history, ['channel', 'url'])
def handle_default(target, subtype, data): self.bot.privmsg(target, _('What kind of weed is that?'))
def handle_video(target, subtype, data): self.bot.privmsg(target, _('For God sake I\'m blind'))
def handle_audio(target, subtype, data): self.bot.privmsg(target, _('Do you know I\'m deaf right?'))
def handle_image(target, subtype, data): self.bot.privmsg(target, _('Looks like an image'))