Exemplo n.º 1
0
def main():
    log.info("Starting bot.")

    bot = ICQBot(token=TOKEN, name=NAME, version=VERSION)

    while True:
        try:
            response = bot.fetch_events()
            for event in response.json()["response"]["data"]["events"]:
                if event["type"] == "im":
                    event_data = event["eventData"]
                    source_uin = event_data["source"]["aimId"]
                    message = event_data["message"]
                    if "stickerId" not in event_data:
                        bot.send_im(target=source_uin,
                                    message=process(message))
        except KeyboardInterrupt:
            log.info("Shutting down bot.")
            sys.exit()
        except:
            log.exception("Exception in main loop!")
Exemplo n.º 2
0
def main():
    log.info("Starting bot.")

    bot = ICQBot(token=TOKEN, name=NAME, version=VERSION)

    while True:
        # noinspection PyBroadException
        try:
            response = bot.fetch_events()
            for event in response.json()["response"]["data"]["events"]:
                if event["type"] == "im":
                    event_data = event["eventData"]
                    source_uin = event_data["source"]["aimId"]
                    message = event_data["message"]

                    try:
                        bot.set_typing(target=source_uin,
                                       typing_status=TypingStatus.TYPING.value)

                        # Getting info for file in message.
                        (_, _, path, _, _) = urlparse.urlsplit(message)
                        file_id = path.rsplit("/", 1).pop()
                        file_info_response = bot.get_file_info(file_id=file_id)
                        if file_info_response.status_code == requests.codes.not_found:
                            raise FileNotFoundException
                        link = file_info_response.json()["file_list"].pop(
                        )["dlink"]

                        # Starting file download.
                        file_response = bot._http_session.get(link,
                                                              stream=True)
                        if file_response.encoding is None:
                            file_response.encoding = 'utf-8'

                        # Downloading file and calculating stats.
                        stats = defaultdict(int)
                        status_codes = defaultdict(int)
                        for log_record in iterate_log(
                            (line for line in file_response.iter_lines(
                                decode_unicode=True) if line is not None)):
                            if isinstance(log_record, HTTPLogRecord):
                                (request, response) = (log_record.request,
                                                       log_record.response)

                                stats["requests_count"] += 1

                                if request.url.path == "/aim/startSession":
                                    stats["start_session_count"] += 1

                                if request.url.path == "/genToken":
                                    stats["gen_token_count"] += 1

                                if response:
                                    status_codes[response.status_code + " " +
                                                 response.reason_phrase] += 1
                                else:
                                    stats["no_response_count"] += 1

                        bot.send_im(
                            target=source_uin,
                            message=
                            ("Total requests: {requests_count}\n    /aim/startSession: {start_session_count}\n    /g"
                             "enToken: {gen_token_count}\n\nResponse count by status code:\n{status_codes}\n\nFound "
                             "problems:\n{problems}\n\n{phrase}").
                            format(
                                requests_count=stats["requests_count"],
                                start_session_count=stats[
                                    "start_session_count"],
                                gen_token_count=stats["gen_token_count"],
                                status_codes="\n".join([
                                    "    {code}: {count}".format(code=code,
                                                                 count=count)
                                    for (code,
                                         count) in sorted(status_codes.items())
                                ]),
                                problems=
                                "    Requests without response: {no_response_count}"
                                .format(no_response_count=stats[
                                    "no_response_count"]),
                                phrase=random.choice(PHRASES)))
                    except FileNotFoundException:
                        bot.send_im(target=source_uin,
                                    message=random.choice(PHRASES) +
                                    " Give me your log right now!")
                    except NotImplementedError:
                        bot.send_im(target=source_uin,
                                    message=random.choice(PHRASES) +
                                    " Log format is not supported!")
                    except Exception:
                        bot.send_im(target=source_uin,
                                    message=random.choice(PHRASES) +
                                    " Something has gone wrong!")
                        raise
                    finally:
                        bot.set_typing(target=source_uin,
                                       typing_status=TypingStatus.NONE.value)
        except KeyboardInterrupt:
            log.info("Shutting down bot.")
            sys.exit()
        except Exception:
            log.exception("Exception in main loop!")