Exemplo n.º 1
0
def welcome_token(token: str = '',
                  message_format: FormatEnum = Query(FormatEnum.txt,
                                                     alias='format')):
    """Return welcome message to user based on given response format. Endpoint only available to users with valid token
     - token argument is used in decorator."""

    return format_message('Welcome!', message_format)
    def onMessage(self, author_id, message_object, thread_id, thread_type,
                  **kwargs):
        if not self.isLoggedIn():
            self.login(self.email, self.password)
            with open("session.json", "w") as f:
                json.dump(self.getSession(), f)

        if author_id == self.uid:
            return

        if thread_id != self.thread_id:
            return

        user = self.fetchUserInfo(author_id)[author_id]

        if message_object.text is not None:
            text = (utils.format_message(
                user.name + RandomMessageGenerator.get_random_said()) +
                    message_object.text)
        else:
            text = None

        urls = [
            self.fetchImageUrl(f.uid) for f in filter(
                lambda x: not isinstance(x, fbchat.ShareAttachment),
                message_object.attachments,
            )
        ]

        if urls == []:
            urls = None

        self.send_handler(self.get_client_name(), text, urls)
Exemplo n.º 3
0
    def give_access(self, sock):
        '''
        Host responds to client request IF passwords match.
        '''
        msg = {
            'source': "give_access",
            'message': None,
            '_from': None,
            '_to': None,
            '_type': "authentication",
            '_order': None,
        }

        while True:
            data = sock.recv(1024)
            if data:
                string_data = data.decode('utf-8')
                formatted_data = format_message(string_data)
                if formatted_data.get(
                        "_type") == "authentication" and formatted_data.get(
                            "message") == self.password:
                    msg["message"] = "granted"
                    formatted_msg = json.dumps(msg)
                    sock.send(formatted_msg)
                    return True
                else:
                    return False
Exemplo n.º 4
0
def welcome_session(session_token: str = Cookie(''),
                    message_format: FormatEnum = Query(FormatEnum.txt,
                                                       alias='format')):
    """Return welcome message to user based on given response format. Endpoint only available to users with valid
    session cookie - request argument is used in decorator."""

    return format_message('Welcome!', message_format)
    async def on_message(self, message):
        if message.author == self.user:
            return

        if message.channel.id != self.channel:
            return

        try:
            if message.content != None and len(message.content) > 0:
                text = (utils.format_message(
                    message.author.name +
                    RandomMessageGenerator.get_random_said()) +
                        message.content)
            else:
                text = None

            if len(message.attachments) > 0:
                urls = [a.url for a in message.attachments]
            else:
                urls = None

            self.send_handler(self.get_client_name(), text, urls)

        except Exception as e:
            print(e)
Exemplo n.º 6
0
 def receive(self, sock):
     while True:
         data = sock.recv(1024)
         if data:
             string_data = data.decode('utf-8')
             print(string_data)
             formatted_data = format_message(string_data)
             self.recv_queue.put(formatted_data)
Exemplo n.º 7
0
def join_chat():
    """Sent by clients when they enter a room.
    A status message is broadcast to all people in the room."""
    backend = get_backend()
    uid = userid()
    chat_info = backend.get_chat_info(uid)
    backend.send(uid,
                 Event.JoinEvent(chat_info.agent_index, uid, str(time.time())))
    return jsonify(message=format_message("You entered the room.", True))
Exemplo n.º 8
0
async def guide(context):
    """ Link to guide on the forum """
    lookup, at_users, message = await init_command(context)
    task, _ = get_task(message, list(lookup["tasks"].keys()))
    if not task:
        return
    msg = "There's a guide for {} here: {}".format(
        task.title(), lookup["url"] + lookup["tasks"][task])
    msg = format_message(msg, at_users)
    await context.send(msg)
Exemplo n.º 9
0
async def faqs(context):
    """ Link to FAQs """
    lookup, at_users, message = await init_command(context)

    is_task = True
    tasks = faq_cache.contents
    if "search" in message:
        is_task = False
        search_term = " ".join(message[message.index("search") + 1:])
        logger.info("search_term: %s", search_term)
        if not search_term:
            is_task = True
            task = None
        else:
            task = faq_cache.search(search_term)
            logger.info("results: %s", task)
            if len(task) > lookup["results"]:
                logger.info("Too many results. Limiting: %s / %s",
                            lookup["results"], len(task))
                task = None
            if not task:
                is_task = True
                task = None
    else:
        task, _ = get_task(message, list(tasks.keys()))
    logger.info("final task: %s", task)
    if is_task:
        url = lookup["url"] if task is None else lookup["url"] + tasks[task]
        section = "on" if task is None else "in the {} section of".format(
            task.title())
        msg = "Your question is answered {} our FAQ page at: {}".format(
            section, url)
        msg = format_message(msg, at_users)
    else:
        urls = "\n\t".join([
            "`{}`: {}".format(val, lookup["url"] + key)
            for key, val in task.items()
        ])
        msg = (
            "Your question is answered on our FAQ page. Try one of these answers related to "
            "the term `{}`: \n\t{}".format(search_term, urls))
        msg = format_message(msg, at_users)
    await context.send(msg)
Exemplo n.º 10
0
async def forums(context):
    """ Link to the forums """
    lookup, at_users, message = await init_command(context)
    task, _ = get_task(message, lookup["tasks"])
    ext = "index.php" if task is None else "viewforum.php?f={}".format(
        lookup["tasks"][task])
    section = "" if task is None else "the {} section of ".format(task.title())
    msg = "You should check out {}our Forum at: {}".format(
        section, lookup["url"] + ext)
    msg = format_message(msg, at_users)
    await context.send(msg)
Exemplo n.º 11
0
async def support(context):
    """ Support section of forum command """
    lookup, at_users, message = await init_command(context)
    task, _ = get_task(message, list(lookup["tasks"].keys()))
    url = "{}{}".format(lookup["url"],
                        "3" if task is None else lookup["tasks"][task])
    section = "in" if task is None else "in the {} section of".format(
        task.title())
    msg = format_message(
        "This question has been asked and answered {} our Support Forum at: "
        "{}".format(section, url), at_users)
    await context.send(msg)
Exemplo n.º 12
0
def text():
    backend = get_backend()
    message = unicode(request.args.get('message'))
    displayed_message = format_message(u"You: {}".format(message), False)
    uid = userid()
    time_taken = float(request.args.get('time_taken'))
    received_time = time.time()
    start_time = received_time - time_taken
    chat_info = backend.get_chat_info(uid)
    backend.send(
        uid,
        Event.MessageEvent(chat_info.agent_index, message, str(received_time),
                           str(start_time)))
    return jsonify(message=displayed_message, timestamp=str(received_time))
Exemplo n.º 13
0
async def tag(context):
    """ Tag search  command """
    lookup, at_users, message = await init_command(context)
    url = lookup["url"]

    if len(message) != 2:
        logger.debug("No or multiple tags provided")
        return

    tag = message[1]
    url += tag

    msg = "You should try these posts tagged `{}` at our forum: {}".format(
        tag, url)
    msg = format_message(msg, at_users)
    await context.send(msg)
Exemplo n.º 14
0
def send_message(update, ctx):
    message_text = utils.format_message(update.message)
    if len(message_text) == 0:
        update.message.reply_text(storage.get_string("EMPTY_MSG"))
    else:
        try:
            bot.send_message(storage.get_target_chat(),
                             message_text,
                             reply_markup=utils.make_report_keyboard(
                                 update.message.from_user.id),
                             parse_mode=ParseMode.HTML)
            update.message.reply_text(storage.get_string("MSG_SENT"))
        except Exception as e:
            template = Template(storage.get_string("CANT_SEND"))
            update.message.reply_text(
                template.safe_substitute(message=e.message))
Exemplo n.º 15
0
async def search(context):
    """ Search the forum command """
    lookup, at_users, message = await init_command(context)
    terms = None
    url = lookup["url"]
    if len(message) > 1:
        terms = "+".join(message[1:])
        url += "?keywords={}".format(terms)

    if terms is None:
        results = ""
    else:
        results = ". Here are the results for `{}`".format(" ".join(
            terms.split("+")))
    msg = "You should try the Search page at our forum{}: {}".format(
        results, url)
    msg = format_message(msg, at_users)
    await context.send(msg)
Exemplo n.º 16
0
    def ask_access(self, sock):
        '''
        Client sends access request to Host and waits for response.
        Client notifies TextEditor if access is denied.
        '''
        msg = {
            'source': "ask_access",
            'message': self.password,
            '_from': None,
            '_to': None,
            '_type': "authentication",
            '_order': None,
        }

        formatted_msg = json.dumps(msg)
        sock.send(formatted_msg)

        for ticks in range(0, 1000):
            data = sock.recv(1024)
            if data:
                string_data = data.decode('utf-8')
                formatted_data = format_message(string_data)
                if formatted_data.get(
                        "_type") == "authentication" and formatted_data.get(
                            "message") == "granted":
                    return True
                else:
                    break

        failed_msg = {
            'source': "ask_access",
            'message': "denied",
            '_from': None,
            '_to': None,
            '_type': "authentication",
            '_order': None,
        }
        self.recv_queue.put(failed_msg)
        return False
Exemplo n.º 17
0
async def donate(context):
    """ Display donation messages """
    lookup, at_users, message = await init_command(context)

    content = dict()
    for key, val in lookup["tasks"].items():
        kwargs = dict(embed=dict(title=val["title"], type="rich"),
                      author=dict(name=val["name"], icon_url=val["icon"]))
        if "url" in val:
            kwargs["embed"]["url"] = val["url"]
            kwargs["author"]["url"] = val["url"]
        embed = Embed(**kwargs["embed"])
        embed.set_thumbnail(url=val["thumbnail"])
        embed.set_author(**kwargs["author"])

        if val.get("fields", None) is not None:
            for field in val["fields"]:
                embed.add_field(inline=False, **field)
        content[key] = embed
    logger.info("donator content: %s", content)

    donatee, _ = get_task(message, list(content.keys()))

    msg = format_message(lookup["msg"], at_users)
    await context.send(msg)
    await context.send(embed=content.pop("patreon"))

    if donatee != "patreon":
        embeds = [content[donatee]] if donatee else [
            content[key] for key in list(content.keys())
        ]
        msg = (
            "Alternatively you can give a one off donation to any of our Devs below:"
        )
        await context.send(msg)
        for embed in embeds:
            await context.send(embed=embed)
Exemplo n.º 18
0
def close(issue):
    text = utils.format_message(issue, config.closing_message)
    issue.add_comment(text)
    issue.close()
Exemplo n.º 19
0
def warn(issue):
    text = utils.format_message(issue, config.warning_message)
    issue.add_comment(text)
Exemplo n.º 20
0
def get_message(message_id):
    msg_list = current_user.db().search_messages("id:%s"%message_id)
    if len(msg_list) != 1:
        abort(404)
    m = msg_list[0]
    return jsonify(format_message(m))
Exemplo n.º 21
0
async def log(context):
    """ Request a crash report """
    lookup, at_users, _ = await init_command(context)
    msg = format_message(lookup["msg"], at_users)
    await context.send(msg)
Exemplo n.º 22
0
async def dfl(context):
    """ Output that we don't support DFL """
    lookup, at_users, _ = await init_command(context)
    msg = format_message(lookup["msg"], at_users)
    await context.send(msg)
Exemplo n.º 23
0
async def sysinfo(context):
    """ Output System Information """
    lookup, at_users, _ = await init_command(context)
    msg = format_message(lookup["msg"], at_users)
    await context.send(msg)
Exemplo n.º 24
0
    def receive(self, sock):
        '''
        This listens to receiving socket all the time.
        Large messages > 1024 bytes come in multiple messages, so those are handled aswell.
        '''
        msg = ""
        remaining = -1  # -1 for unknown
        while True:
            try:
                data = sock.recv(1024)
                # The problem occurs if header is found from the end of previous message due latency.
                if data:
                    string_data = data.decode('utf-8')
                    if (remaining <= 0):
                        # pass data to msg - start buffer if needed
                        if self.supportLongMessages:
                            try:
                                header_end_index = string_data.find(
                                    'ALD', 0, 15)
                                json_started = string_data.find('{', 0, 15)
                                if header_end_index == -1 or json_started < header_end_index:
                                    #Header not found
                                    msg = string_data
                                else:
                                    header_end = header_end_index + len("ALD")
                                    header = string_data[:header_end - 1]
                                    msg = string_data[header_end:]
                                    msg_length = int(
                                        header[len("HAR"):-(len("ALD") - 1)])
                                    remaining = msg_length - 1024
                            except ValueError as e:
                                print(e)
                                print("ValueError on parsing header")
                                pass
                        else:
                            msg = string_data

                    else:
                        # buffer has been started
                        msg += string_data
                        remaining = remaining - 1024

                    if remaining <= 0:
                        # message is ready to parse
                        try:
                            formatted_data = format_message(msg)
                            self.socket_recv_queue.put(formatted_data)
                        except ValueError as e:
                            print(e)
                            print("Message lost..")
                            pass
                    #print("Harald received:", string_data)

            except OSError:
                if self.host_sock:
                    print(
                        'Lost connection to Host. Closing this receive thread.'
                    )
                else:
                    print(
                        'Lost connection to a Client. Closing this receive thread.'
                    )
                sock.close()
                return
Exemplo n.º 25
0
def logout(message_format: FormatEnum = Query(FormatEnum.txt, alias='format')):
    """Return message to user after log out."""
    return format_message('Logged out!', message_format)