Exemplo n.º 1
0
def get_sys_logs(cr, uid):
    """
    Utility method to send a publisher warranty get logs messages.
    """
    pool = pooler.get_pool(cr.dbname)

    dbuuid = pool.get("ir.config_parameter").get_param(cr, uid, "database.uuid")
    db_create_date = pool.get("ir.config_parameter").get_param(cr, uid, "database.create_date")
    nbr_users = pool.get("res.users").search(cr, uid, [], count=True)
    contractosv = pool.get("publisher_warranty.contract")
    contracts = contractosv.browse(cr, uid, contractosv.search(cr, uid, []))
    user = pool.get("res.users").browse(cr, uid, uid)
    msg = {
        "dbuuid": dbuuid,
        "nbr_users": nbr_users,
        "dbname": cr.dbname,
        "db_create_date": db_create_date,
        "version": release.version,
        "contracts": [c.name for c in contracts],
        "language": user.context_lang,
    }

    add_arg = {"timeout": 30} if sys.version_info >= (2, 6) else {}
    arguments = {"arg0": msg, "action": "update"}
    arguments_raw = urllib.urlencode(arguments)
    url = config.get("publisher_warranty_url")
    uo = urllib2.urlopen(url, arguments_raw, **add_arg)
    try:
        submit_result = uo.read()
    finally:
        uo.close()

    result = safe_eval(submit_result) if submit_result else {}

    return result
Exemplo n.º 2
0
def get_sys_logs(cr, uid):
    """
    Utility method to send a publisher warranty get logs messages.
    """
    pool = pooler.get_pool(cr.dbname)

    dbuuid = pool.get('ir.config_parameter').get_param(cr, uid,
                                                       'database.uuid')
    db_create_date = pool.get('ir.config_parameter').get_param(
        cr, uid, 'database.create_date')
    limit_date = datetime.datetime.now()
    limit_date = limit_date - datetime.timedelta(15)
    limit_date_str = limit_date.strftime(misc.DEFAULT_SERVER_DATETIME_FORMAT)
    nbr_users = pool.get("res.users").search(cr, uid, [], count=True)
    nbr_active_users = pool.get("res.users").search(
        cr, uid, [("date", ">=", limit_date_str)], count=True)
    nbr_share_users = False
    nbr_active_share_users = False
    if "share" in pool.get("res.users")._columns \
            or "share" in pool.get("res.users")._inherit_fields:
        nbr_share_users = pool.get("res.users").search(cr,
                                                       uid,
                                                       [("share", "=", True)],
                                                       count=True)
        nbr_active_share_users = pool.get("res.users").search(
            cr,
            uid, [("share", "=", True), ("date", ">=", limit_date_str)],
            count=True)
    contractosv = pool.get('publisher_warranty.contract')
    contracts = contractosv.browse(cr, uid, contractosv.search(cr, uid, []))
    user = pool.get("res.users").browse(cr, uid, uid)
    msg = {
        "dbuuid": dbuuid,
        "nbr_users": nbr_users,
        "nbr_active_users": nbr_active_users,
        "nbr_share_users": nbr_share_users,
        "nbr_active_share_users": nbr_active_share_users,
        "dbname": cr.dbname,
        "db_create_date": db_create_date,
        "version": release.version,
        "contracts": [c.name for c in contracts],
        "language": user.context_lang,
    }

    add_arg = {"timeout": 30} if sys.version_info >= (2, 6) else {}
    arguments = {
        'arg0': msg,
        "action": "update",
    }
    arguments_raw = urllib.urlencode(arguments)
    url = config.get("publisher_warranty_url")
    uo = urllib2.urlopen(url, arguments_raw, **add_arg)
    try:
        submit_result = uo.read()
    finally:
        uo.close()

    result = safe_eval(submit_result) if submit_result else {}

    return result
Exemplo n.º 3
0
    def send(self, cr, uid, tb, explanations, remarks=None, issue_name=None):
        """ Method called by the client to send a problem to the publisher warranty server. """

        return True  # KGB

        if not remarks:
            remarks = ""

        valid_contracts = self._get_valid_contracts(cr, uid)
        valid_contract = valid_contracts[0]

        try:
            origin = 'client'
            dbuuid = self.pool.get('ir.config_parameter').get_param(cr, uid, 'database.uuid')
            db_create_date = self.pool.get('ir.config_parameter').get_param(cr, uid, 'database.create_date')
            user = self.pool.get("res.users").browse(cr, uid, uid)
            user_name = user.name
            email = user.user_email

            msg = {'contract_name': valid_contract.name,
                'tb': tb,
                'explanations': explanations,
                'remarks': remarks,
                'origin': origin,
                'dbname': cr.dbname,
                'dbuuid': dbuuid,
                'db_create_date': db_create_date,
                'issue_name': issue_name,
                'email': email,
                'user_name': user_name,
            }


            add_arg = {"timeout":30} if sys.version_info >= (2,6) else {}
            uo = urllib2.urlopen(config.get("publisher_warranty_url"),
                                    urllib.urlencode({'arg0': msg, "action": "send",}),**add_arg)
            try:
                submit_result = uo.read()
            finally:
                uo.close()

            result = safe_eval(submit_result)

            crm_case_id = result

            if not crm_case_id:
                return False

        except osv.except_osv:
            raise
        except Exception:
            _logger.warning("Error sending problem report", exc_info=1)
            raise osv.except_osv(_("Error"),
                                 _("Error during communication with the publisher warranty server."))

        return True
Exemplo n.º 4
0
    def send(self, cr, uid, tb, explanations, remarks=None, issue_name=None):
        """ Method called by the client to send a problem to the publisher warranty server. """

        if not remarks:
            remarks = ""

        valid_contracts = self._get_valid_contracts(cr, uid)
        valid_contract = valid_contracts[0]

        try:
            origin = "client"
            dbuuid = self.pool.get("ir.config_parameter").get_param(cr, uid, "database.uuid")
            db_create_date = self.pool.get("ir.config_parameter").get_param(cr, uid, "database.create_date")
            user = self.pool.get("res.users").browse(cr, uid, uid)
            user_name = user.name
            email = user.email

            msg = {
                "contract_name": valid_contract.name,
                "tb": tb,
                "explanations": explanations,
                "remarks": remarks,
                "origin": origin,
                "dbname": cr.dbname,
                "dbuuid": dbuuid,
                "db_create_date": db_create_date,
                "issue_name": issue_name,
                "email": email,
                "user_name": user_name,
            }

            add_arg = {"timeout": 30} if sys.version_info >= (2, 6) else {}
            uo = urllib2.urlopen(
                config.get("publisher_warranty_url"), urllib.urlencode({"arg0": msg, "action": "send"}), **add_arg
            )
            try:
                submit_result = uo.read()
            finally:
                uo.close()

            result = safe_eval(submit_result)

            crm_case_id = result

            if not crm_case_id:
                return False

        except osv.except_osv:
            raise
        except Exception:
            _logger.warning("Error sending problem report", exc_info=1)
            raise osv.except_osv(_("Error"), _("Error during communication with the publisher warranty server."))

        return True
Exemplo n.º 5
0
def get_sys_logs(cr, uid):
    """
    Utility method to send a publisher warranty get logs messages.
    """

    return False  # KGB

    pool = pooler.get_pool(cr.dbname)

    dbuuid = pool.get('ir.config_parameter').get_param(cr, uid, 'database.uuid')
    db_create_date = pool.get('ir.config_parameter').get_param(cr, uid, 'database.create_date')
    limit_date = datetime.datetime.now()
    limit_date = limit_date - datetime.timedelta(15)
    limit_date_str = limit_date.strftime(misc.DEFAULT_SERVER_DATETIME_FORMAT)
    nbr_users = pool.get("res.users").search(cr, uid, [], count=True)
    nbr_active_users = pool.get("res.users").search(cr, uid, [("date", ">=", limit_date_str)], count=True)
    nbr_share_users = False
    nbr_active_share_users = False
    if "share" in pool.get("res.users")._all_columns:
        nbr_share_users = pool.get("res.users").search(cr, uid, [("share", "=", True)], count=True)
        nbr_active_share_users = pool.get("res.users").search(cr, uid, [("share", "=", True), ("date", ">=", limit_date_str)], count=True)
    contractosv = pool.get('publisher_warranty.contract')
    contracts = contractosv.browse(cr, uid, contractosv.search(cr, uid, []))
    user = pool.get("res.users").browse(cr, uid, uid)
    msg = {
        "dbuuid": dbuuid,
        "nbr_users": nbr_users,
        "nbr_active_users": nbr_active_users,
        "nbr_share_users": nbr_share_users,
        "nbr_active_share_users": nbr_active_share_users,
        "dbname": cr.dbname,
        "db_create_date": db_create_date,
        "version": release.version,
        "contracts": [c.name for c in contracts],
        "language": user.context_lang,
    }
    msg.update(pool.get("res.company").read(cr,uid,[1],["name","email","phone"])[0])

    add_arg = {"timeout":30} if sys.version_info >= (2,6) else {}
    arguments = {'arg0': msg, "action": "update",}
    arguments_raw = urllib.urlencode(arguments)
    url = config.get("publisher_warranty_url")
    uo = urllib2.urlopen(url, arguments_raw, **add_arg)
    try:
        submit_result = uo.read()
    finally:
        uo.close()

    if not submit_result:
        raise IOError('Invalid result')

    result = safe_eval(submit_result)

    return result
Exemplo n.º 6
0
def init_principals_redirect():
    """ Some devices like the iPhone will look under /principals/users/xxx for 
    the user's properties. In OpenERP we _cannot_ have a stray /principals/...
    working path, since we have a database path and the /webdav/ component. So,
    the best solution is to redirect the url with 301. Luckily, it does work in
    the device. The trick is that we need to hard-code the database to use, either
    the one centrally defined in the config, or a "forced" one in the webdav
    section.
    """
    dbname = config.get_misc("webdav", "principal_dbname", False)
    if (not dbname) and not config.get_misc("webdav", "no_principals_redirect", False):
        dbname = config.get("db_name", False)
    if dbname:
        PrincipalsRedirect.redirect_paths[""] = "/webdav/%s/principals" % dbname
        reg_http_service("/principals", PrincipalsRedirect)
        _logger.info("Registered HTTP redirect handler for /principals to the %s db.", dbname)
Exemplo n.º 7
0
def init_principals_redirect():
    """ Some devices like the iPhone will look under /principals/users/xxx for 
    the user's properties. In OpenERP we _cannot_ have a stray /principals/...
    working path, since we have a database path and the /webdav/ component. So,
    the best solution is to redirect the url with 301. Luckily, it does work in
    the device. The trick is that we need to hard-code the database to use, either
    the one centrally defined in the config, or a "forced" one in the webdav
    section.
    """
    dbname = config.get_misc('webdav', 'principal_dbname', False)
    if (not dbname) and not config.get_misc('webdav', 'no_principals_redirect', False):
        dbname = config.get('db_name', False)
    if dbname:
        PrincipalsRedirect.redirect_paths[''] = '/webdav/%s/principals' % dbname
        reg_http_service('/principals', PrincipalsRedirect)
        _logger.info(
                "Registered HTTP redirect handler for /principals to the %s db.",
                dbname)
Exemplo n.º 8
0
 def historise(self, cr, uid, ids, message='', context=None, error=False):
     user_obj = self.pool.get('res.users')
     if not context:
         context = {}
     user = user_obj.browse(cr, uid, uid)
     if 'lang' not in context:
         context.update({'lang': user.context_lang})
     for psms_id in ids:
         history = self.read(cr, uid, psms_id, ['history'], context).get(
             'history', '') or ''
         history_limit = config.get('psms_history_limit', 10)
         # Limit history to X lines, then rotate
         if len(history.split('\n')) > history_limit:
             history = '\n'.join(history.split('\n')[1:])
         history_newline = "\n{}: {}".format(
             time.strftime("%Y-%m-%d %H:%M:%S"), tools.ustr(message))
         self.write(cr, uid, psms_id,
                    {'history': (history or '') + history_newline}, context)
Exemplo n.º 9
0
    def historise(self, cr, uid, ids, message='', context=None, error=False):

        user_obj = self.pool.get('res.users')
        if not context:
            context = {}
        user = user_obj.browse(cr, uid, uid)
        if 'lang' not in context:
            context.update({'lang': user.context_lang})
        for pmail_id in ids:
            # Notify the sender errors
            if context.get('notify_errors', False) \
                    and not context.get('bounce', False) \
                    and error:
                mail = self.browse(cr, uid, pmail_id)
                vals = {
                    'folder':
                    'outbox',
                    'history':
                    '',
                    'pem_to':
                    mail.pem_account_id.email_id,
                    'pem_subject':
                    _(u"Error sending email with id {}: {}").format(
                        mail.id, mail.pem_subject)
                }
                bounce_mail_id = self.copy(cr, uid, pmail_id, vals)
                ctx = context.copy()
                ctx.update({'bounce': True})
                self.send_this_mail(cr, uid, [bounce_mail_id], ctx)
                bounce_mail = self.browse(cr, uid, bounce_mail_id)
                # If bounce mail cannot be sent, unlink it
                if bounce_mail.folder != 'sent':
                    bounce_mail.unlink()
            history = self.read(cr, uid, pmail_id, ['history'], context).get(
                'history', '') or ''
            history_limit = config.get('pmail_history_limit', 10)
            # Limit history to X lines, then rotate
            if len(history.split('\n')) > history_limit:
                history = '\n'.join(history.split('\n')[1:])
            history_newline = "\n{}: {}".format(
                time.strftime("%Y-%m-%d %H:%M:%S"), tools.ustr(message))
            self.write(cr, uid, pmail_id,
                       {'history': (history or '') + history_newline}, context)
def get_sys_logs(cr, uid):
    """
    Utility method to send a publisher warranty get logs messages.
    """
    pool = pooler.get_pool(cr.dbname)

    dbuuid = pool.get('ir.config_parameter').get_param(cr, uid,
                                                       'database.uuid')
    db_create_date = pool.get('ir.config_parameter').get_param(
        cr, uid, 'database.create_date')
    nbr_users = pool.get("res.users").search(cr, uid, [], count=True)
    contractosv = pool.get('publisher_warranty.contract')
    contracts = contractosv.browse(cr, uid, contractosv.search(cr, uid, []))
    user = pool.get("res.users").browse(cr, uid, uid)
    msg = {
        "dbuuid": dbuuid,
        "nbr_users": nbr_users,
        "dbname": cr.dbname,
        "db_create_date": db_create_date,
        "version": release.version,
        "contracts": [c.name for c in contracts],
        "language": user.context_lang,
    }

    add_arg = {"timeout": 30} if sys.version_info >= (2, 6) else {}
    arguments = {
        'arg0': msg,
        "action": "update",
    }
    arguments_raw = urllib.urlencode(arguments)
    url = config.get("publisher_warranty_url")
    uo = urllib2.urlopen(url, arguments_raw, **add_arg)
    try:
        submit_result = uo.read()
    finally:
        uo.close()

    result = safe_eval(submit_result) if submit_result else {}

    return result
Exemplo n.º 11
0
_dir = os.path.dirname(server_environment_files.__file__)

# Same dict as RawConfigParser._boolean_states
_boolean_states = {
    "1": True,
    "yes": True,
    "true": True,
    "on": True,
    "0": False,
    "no": False,
    "false": False,
    "off": False,
}

if not system_base_config.get("running_env", False):
    raise Exception(
        (
            "The parameter 'running_env' has not be set neither in base config file option -c or in openerprc.\n"
            "We strongly recommand you not to use the rc file but instead use an explicite config file with this content : \n"
            "[options] \nrunning_env =  dev"
        )
    )

ck_path = os.path.join(_dir, system_base_config["running_env"])

if not os.path.exists(ck_path):
    raise Exception("Provided server environment does not exists please add a folder %s" % s(ck_path))


def setboolean(obj, attr, _bool=_boolean_states):
Exemplo n.º 12
0
def main():
    global LAST_UPDATE_ID
    
    HAIL_SATAN = 0
    logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    # Telegram Bot Authorization Token
    bot = telegram.Bot(config.get('telegram', 'token'))

    # This will be our global variable to keep the latest update_id when requesting
    # for updates. It starts with the latest update_id if available.
    try:
        LAST_UPDATE_ID = bot.getUpdates()[-1].update_id
    except IndexError as TypeError:
        LAST_UPDATE_ID = None

    while True:
        for update in bot.getUpdates(offset=LAST_UPDATE_ID, timeout=20):
            try:
                if update.message:
                    if update.message.text:

                        def post(msg):
                            """Posts a message to Telegram."""
                            bot.sendChatAction(
                                update.message.chat_id,
                                action=telegram.ChatAction.TYPING)
                            bot.sendMessage(update.message.chat_id, msg)

                        def post_random(odds, text):
                            """Has a one in x chance of posting a message to telegram."""
                            if random.randint(1, odds) == odds:
                                post(text)

                        text = update.message.text.encode("utf-8")
                        first_name = update.message.from_user.first_name.encode(
                            "utf-8")

                        # logging for quotable data
                        if update.message.chat.title.encode(
                                "utf-8") == "May Be A Little Late" and text[0] != '/':
                            with open("data/mball.txt", "a") as quote_file:
                                quote_file.write("%s: %s\n" % (first_name, text))
                            quote_file.close()
                        else:
                            with open("data/cmds.txt", "a") as quote_file:
                                quote_file.write("%s: %s\n" % (first_name, text))
                            quote_file.close()

                        if text.startswith("/"):
                            text = text.replace("@originalstatic_bot", "")

                            if text == "/help":
                                post("type '/' into chat, or press the '[/]' button to view all available commands")

                            elif text.lower().startswith("/char"):
                                char_args = text.title().split()
                                if len(char_args) == 4:
                                    post(
                                        ffxiv_char(
                                            char_args[1],
                                            char_args[2],
                                            char_args[3]))
                                else:
                                    post(
                                        "needs 3 arguments. usage: /char [first name] [last name] [server]")

                            elif text.lower() == "/quote" or text.lower() == "/quote ":
                                quote_file = open("data/mball.txt").read().splitlines()
                                post(random.choice(quote_file))
                                
                            elif text.lower().startswith("/quote") and len(text) > 7:
                                names = static_config.get('static', 'names').splitlines()
                                # Pull aliases for names from static_config.ini
                                name_elem = next(name for name in names if text[7:].lower() + ',' in name.lower())
                                name = name_elem[:name_elem.index(':')+1]

                                quote_file = open("data/mball.txt").read().splitlines()
                                random.shuffle(quote_file)
                                post(next(line for line in quote_file if line.startswith(name)))

                            elif text.lower().startswith("/calc"):
                                post(calculate(text, first_name))

                            elif text.lower().startswith("/tweet"):
                                if len(text) < 7:
                                    post("usage: /tweet (some garbage)")
                                elif len(text) >= 140:
                                    post("maybe make your tweet just a teensy bit shorter?")
                                else:
                                    post_tweet(text[7:])
                                    post(random.choice([
                                        "tweet posted. fuccckkkk", "tweet posted. this is a terrible, terrible idea",
                                        "tweet posted. why though? why?", "garbage posted.", "tweet posted.",
                                        "tweet posted. it's a shitty tweet and this is coming from a toilet"
                                    ]) + " (http://twitter.com/raidbot)")

                            elif text.lower().startswith("/youtube") or text.lower().startswith("/yt"):
                                post(youtube(text))

                            elif text.lower() == "/vgm":
                                post(vgm())

                            elif text.lower() == "/alias":
                                post(static_config.get('static', 'alias'))

                            elif text.lower() == "/raid":
                                post(static_config.get('static', 'raid'))

                            elif text.lower().startswith("/weather"):
                                post(get_weather(text))

                            elif text.lower().startswith("/translate"):
                                post(translate(text))

                            elif text.lower() == "/news":
                                results = latest_tweets("ff_xiv_en")
                                if isinstance(results, str):
                                     post(results)
                                else:
                                    for tweet in results:
                                        post("https://twitter.com/ff_xiv_en/status/%s" % (tweet.id_str))

                            elif text.lower() == "/status":
                                post(status("excalibur"))

                            elif text.lower() == "/timers":
                                post(timers())

                            elif text == "/flush":
                                post("aaaah. why thank you, %s. ;)" % (first_name.lower()))

                            elif text.lower() == "/goons":
                                post(random_tweet("Goons_TXT"))
                            elif text.lower() == "/yahoo":
                                post(random_tweet("YahooAnswersTXT"))
                            elif text.lower() == "/meirl":
                                post(random_tweet("itmeirl"))
                            elif text.lower() == "/wikihow":
                                post(random_tweet("WikiHowTXT"))
                            elif text.lower() == "/tumblr":
                                post(random_tweet("TumblrTXT"))
                            elif text.lower() == "/fanfiction":
                                post(random_tweet("fanfiction_txt"))
                            elif text.lower() == "/reddit":
                                post(random_tweet("Reddit_txt"))
                            elif text.lower() == "/catgirl":
                                post(random_tweet("catgirls_bot"))
                            elif text.lower() == "/catboy":
                                post(random_tweet("catboys_bot"))
                            elif text.lower() == "/catperson":
                                post(random_tweet(random.choice(
                                    ["catboys_bot", "catgirls_bot"])))
                            elif text.lower() == "/ff14":
                                account = [
                                    "ff14forums_txt",
                                    "FFXIV_Memes",
                                    "FFXIV_Names",
                                    "FFXIV_PTFinders"]
                                post(random_tweet(random.choice(account)))
                            elif text.lower() == "/oocanime":
                                post(random_tweet("oocanime"))
                            elif text.lower() == "/damothafuckinsharez0ne":
                                post(random_tweet("dasharez0ne"))
                            elif text.lower() == "/dog" or text.lower() == "/doggo":
                                post(random_tweet("dog_rates"))
                            elif text.lower() == "/twitter":
                                account = [
                                    "ff14forums_txt", "FFXIV_Memes", "FFXIV_Names",
                                    "Goons_TXT", "YahooAnswersTXT", "TumblrTXT",
                                    "Reddit_txt", "fanfiction_txt", "WikiHowTXT",
                                    "itmeirl", "oocanime", "damothafuckinsharez0ne",
                                    "dog_rates", "FFXIV_PTFinders"]
                                post(random_tweet(random.choice(account)))

                            elif text.lower() == "/rt":
                                post(retweet())

                            elif text.lower().startswith("/wiki"):
                                post(wiki(text))

                            elif text.lower() == "/heart":
                                post("<3<3<3 hi %s <3<3<3" % (first_name.lower()))
                                
                            elif text.lower() == "/ping" or text.lower() == "ping":
                                post("pong")
                                
                            elif text.lower() == "/bing" or text.lower() == "bing":
                                post("bong")

                            elif text.lower() == "/quoth the raven":
                                post("nevermore")

                            elif text.lower() == "/sleep":
                                post("brb 5 mins")
                                time.sleep(300)
                                
                            elif text.lower() == "/brum":
                                post(random.choice(["https://s-media-cache-ak0.pinimg.com/736x/0c/c1/9a/0cc19aa7d2184fbeb5f4ff57442f7846.jpg",
                                                "http://i3.birminghammail.co.uk/incoming/article4289373.ece/ALTERNATES/s615/Brum1.jpg",
                                                "https://i.ytimg.com/vi/pmBX3461TdU/hqdefault.jpg",
                                                "https://i.ytimg.com/vi/bvnhLdFqo1k/hqdefault.jpg",
                                                "https://abitofculturedotnet.files.wordpress.com/2014/10/img_1133.jpg"]))
                                
                            elif text.lower().startswith("/sleep ") and len(text[7:]) >= 1:
                                try:
                                    sleep_timer = int(text[7:])

                                    if sleep_timer > 300:
                                        post("i can only go to sleep for up to 5 minutes.")
                                    else:
                                        post("brb")
                                        time.sleep(sleep_timer)
                                except ValueError as e:
                                    post("that's not a number, %s." % first_name.lower())

                            else:
                                post(
                                    "that's not a command i recognise, but we can't all be perfect i guess")

                        elif (text.lower().startswith("hey ") or text.lower() == "hey"
                                or text.lower().startswith("hi ") or text.lower() == "hi"
                                or text.lower().startswith("sup ") or text.lower().startswith("hello")
                                or text.lower().startswith("good morning")):
                            post(random.choice(["hi", "hi!", "hey", "yo", "eyyyy", "*flush*", "sup",
                                                "hey %s... *flush* ;)" % (
                                                    first_name.lower()),
                                                "hello %s! *FLUSH*" % (
                                                    first_name.lower()),
                                                "hello %s" % (first_name.lower())]))

                        elif "robot" in text.lower():
                            post_random(2, "robutt")

                        elif "same" == text.lower():
                            post_random(4, "same")

                        elif text.lower().startswith("i "):
                            post_random(20, "same")

                        elif "rip" == text.lower() or "RIP" in text or text.lower().startswith("rip"):
                            post("ded") if random.randint(1, 2) == 1 else post("yeah, rip.")

                        elif "lol" in text.lower():
                            post_random(10, "lol")

                        elif "lmao" in text.lower():
                            post_random(5, "lmbo")

                        elif "f**k" in text.lower() or "shit" in text.lower() or "piss" in text.lower():
                            post_random(20, random.choice(
                                ["RUDE", "rude", "... rude", "rude... but i'll allow it.", ":O"]))

                        elif "hail satan" in text.lower() or "hail santa" in text.lower() or "hail stan" in text.lower():
                            HAIL_SATAN = 3
                            post("hail satan")

                        elif (text.lower() == "thanks" or text.lower() == "ty" or text.lower() == "thank you"):
                            post_random(2, random.choice(
                                ["np", "anytime", "my... *flush* pleasure.", "no problem, now sit on my face"]))

                        elif "k" == text.lower() or "ok" == text.lower():
                            post(random.choice(["... k", "k"]))
                            
                        elif "nice" == text.lower() or "noice" == text.lower():
                            post_random(4, "noice")
                            
                        elif "69" in text.lower() or "420" in text.lower():
                            post("nice")

                        elif "raidbot" in text.lower():
                            post_random(6, random.choice(["WHAT?? i wasn't sleeping i swear",
                                                          "i can hear you fine, %s. you don't need to shout" % (
                                                              first_name.lower()),
                                                          "please redirect all your questions and comments to yoship. thank you",
                                                          "careful now",
                                                          "my /timeplayed is a time so long it cannot be comprehended by a mortal mind",
                                                          "look i'm trying to be a toilet here, stop bothering me",
                                                          "beep boop. *FLUSH*",
                                                          "yoship pls nerf my toilet handle",
                                                          "/unsubscribe",
                                                          "plumber job when?????",
                                                          "switch on that toaster and throw it in me",
                                                          "...",
                                                          "what, you want me to say something witty?"
                                                          "/flush"]))

                        elif "yoship" in text.lower():
                            post_random(2, random.choice(["yoship pls nerf this static group (down my toilet bowl)",
                                                          "spoilers: i'm yoship",
                                                          "yoship is MY waifu and nobody will ever take my darling away from me~",
                                                          "i can't wait for yoship to introduce stat boosting microtransactions",
                                                          "1.0 was better it had more polygons",
                                                          "lvl 60 toilet lfg exdr",
                                                          "they nerfed the catgirl butts i want all my sub money back",
                                                          "imo the relic quests aren't long enough",
                                                          "plumber job when?????",
                                                          "i know a place you can put your live letter"]))

                        elif "civ" in text.lower():
                            post_random(2, "my flushes are backed by NUCLEAR WEAPONS!!!")
                                                          
                        elif random.randint(1, 500) == 1:
                            post("%s: i am a brony, and %s" % (first_name.lower(), text.lower()))
                        
                        if HAIL_SATAN == 3:
                            HAIL_SATAN = 2
                        elif HAIL_SATAN == 2:
                            post("HAIL SATAN")
                            HAIL_SATAN = 1
                        elif HAIL_SATAN == 1:
                            post("hail satan.")
                            HAIL_SATAN = 0

            except Exception as e:
                with open("data/debug.txt", "a") as err_file:
                    err_file.write(
                        "%s - Error %s\n%s\nJSON: \n%s\n" %
                        (str(datetime.now()), str(e), traceback.format_exc(), str(update)))
                err_file.close()
            finally:
                # Updates global offset to get the new updates
                LAST_UPDATE_ID = update.update_id + 1
    def send(self, cr, uid, tb, explanations, remarks=None, issue_name=None):
        """ Method called by the client to send a problem to the publisher warranty server. """

        if not remarks:
            remarks = ""

        valid_contracts = self._get_valid_contracts(cr, uid)
        valid_contract = valid_contracts[0]

        try:
            origin = 'client'
            dbuuid = self.pool.get('ir.config_parameter').get_param(
                cr, uid, 'database.uuid')
            db_create_date = self.pool.get('ir.config_parameter').get_param(
                cr, uid, 'database.create_date')
            user = self.pool.get("res.users").browse(cr, uid, uid)
            user_name = user.name
            email = user.email

            msg = {
                'contract_name': valid_contract.name,
                'tb': tb,
                'explanations': explanations,
                'remarks': remarks,
                'origin': origin,
                'dbname': cr.dbname,
                'dbuuid': dbuuid,
                'db_create_date': db_create_date,
                'issue_name': issue_name,
                'email': email,
                'user_name': user_name,
            }

            add_arg = {"timeout": 30} if sys.version_info >= (2, 6) else {}
            uo = urllib2.urlopen(
                config.get("publisher_warranty_url"),
                urllib.urlencode({
                    'arg0': msg,
                    "action": "send",
                }), **add_arg)
            try:
                submit_result = uo.read()
            finally:
                uo.close()

            result = safe_eval(submit_result)

            crm_case_id = result

            if not crm_case_id:
                return False

        except osv.except_osv:
            raise
        except Exception:
            _logger.warning("Error sending problem report", exc_info=1)
            raise osv.except_osv(
                _("Error"),
                _("Error during communication with the publisher warranty server."
                  ))

        return True
Exemplo n.º 14
0
import server_environment_files
_dir = os.path.dirname(server_environment_files.__file__)

# Same dict as RawConfigParser._boolean_states
_boolean_states = {
    '1': True,
    'yes': True,
    'true': True,
    'on': True,
    '0': False,
    'no': False,
    'false': False,
    'off': False
}

if not system_base_config.get('running_env', False):
    raise Exception((
        "The parameter 'running_env' has not be set neither in base config file option -c or in openerprc.\n"
        "We strongly recommand you not to use the rc file but instead use an explicite config file with this content : \n"
        "[options] \nrunning_env =  dev"))

ck_path = os.path.join(_dir, system_base_config['running_env'])

if not os.path.exists(ck_path):
    raise Exception(
        "Provided server environment does not exists please add a folder %s" %
        s(ck_path))


def setboolean(obj, attr, _bool=_boolean_states):
    """Replace the attribute with a boolean."""
Exemplo n.º 15
0
                    if line[i] and not res:
                        logger.notifyChannel("import", netsvc.LOG_WARNING,
                                _("key '%s' not found in selection field '%s'") % \
                                        (line[i], field[len(prefix)]))
                        warning += [_("Key/value '%s' not found in selection field '%s'") % (line[i], field[len(prefix)])]
                else:
                    res = line[i]

                row[field[len(prefix)]] = res or False

            result = (row, nbrmax, warning, data_res_id, xml_id)
            return result

        fields_def = self.fields_get(cr, uid, context=context)

        if config.get('import_partial', False) and filename:
            data = pickle.load(file(config.get('import_partial')))
            original_value = data.get(filename, 0)

        position = 0
        while position<len(datas):
            res = {}

            (res, position, warning, res_id, xml_id) = \
                    process_liness(self, datas, [], current_module, self._name, fields_def, position=position)
            if len(warning):
                cr.rollback()
                return (-1, res, 'Line ' + str(position) +' : ' + '!\n'.join(warning), '')

            try:
                id = ir_model_data_obj._update(cr, uid, self._name,
Exemplo n.º 16
0
#!/usr/bin/env python
"""Module for handling twitter input and output.

Available functions:
- random_tweet: Get a random recent tweet.
- latest: Get the five most recent tweets.
- get_tweet: Builds a list of tweet URLs.
- post_tweet: Posts a tweet to https://twitter.com/raidbot
- retweet: Retweets raidbot's most recently requested tweet.
"""
import tweepy
import random

from tools.config import config

client_key = config.get('twitter', 'client_key')
client_secret = config.get('twitter', 'client_secret')
access_token = config.get('twitter', 'access_token')
access_secret = config.get('twitter', 'access_secret')

auth = tweepy.OAuthHandler(client_key, client_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)

error = "either the tweet or the account was deleted. or something just went horrendously wrong ¯\_(ツ)_/¯"


def random_tweet(username):
    """Get a random non-reply tweet from the latest 50 tweets of an account.
    
    This function checks to make sure it the latest tweets are not entirely 
def send_mail(email_from, addresses = {}, subject='', body={}, attachments={}, 
              ssl=False, reply_to=False, debug=False, embed_image=False):
    '''
    Send an email directly through SMTP server in config file.

    addresses = {
                'To':['*****@*****.**'], 
                'CC':['*****@*****.**', '*****@*****.**'], 
                'BCC':['*****@*****.**']
                },
    subject = 'My mail subject',
    body = {
            'text': 'My email content',
            'html': '<html><body><h2>Title</h2>My email content</body></html>',
            },
    attachments = [
                  ('filename.pdf', 'File_Content'),
                  ],
    ssl = True
    '''
    if not ssl:
        ssl = config.get('smtp_ssl', False)

    if not email_from and not config['email_from']:
        raise Exception("No Email sender by default, see config file")
    
    if body.get('text', False):
        temp_body_text = body.get('text', '')
        l = len(temp_body_text.replace(' ', '').replace('\r', '').\
                replace('\n', ''))
        if l == 0:
            body['text'] = u'No Mail Message'
    # Attach parts into message container.
    # According to RFC 2046, the last part of a multipart message, in this case
    # the HTML message, is best and preferred.
    body_text = body.get('text', u'No Mail Message')
    body_text = tools.ustr(body_text)
    body_text_mime = MIMEText(body_text.encode("utf-8"), _charset='UTF-8') 
    msg = MIMEMultipart()
    if body.get('html', False):
        # to avoid showing text and html at the same time we should use a 
        # sub-container with subtype 'alternative'
        body_multi = MIMEMultipart('alternative')
        body_multi.attach(body_text_mime)
        html_body = html_compacter(tools.ustr(body['html']))        
        if embed_image:
            mii = mail_image_inliner(html_body) 
            html_body = mii.get_new_html()
            msg = mii.get_container(body_multi)
        else:
            msg.attach(body_multi)
        body_multi.attach(MIMEText(html_body.encode("utf-8"), _subtype='html', 
                            _charset='UTF-8'))
    else:
        msg.attach(body_text_mime)
    #Now add attachments if any
    for (filename, data) in attachments:
        part = MIMEBase('application', "octet-stream")
        part.set_payload(data)
        part.add_header('Content-Disposition', 'attachment', filename=filename)
        Encoders.encode_base64(part)
        msg.attach(part)
    
    msg['Subject'] = Header(tools.ustr(subject), 'utf-8')
    msg['From'] = email_from
    del msg['Reply-To']
    if reply_to:
        msg['Reply-To'] = reply_to
    else:
        msg['Reply-To'] = msg['From']
        
    addresses_l = get_ids_from_dict(addresses)
    if addresses_l['To']:   
        msg['To'] = COMMASPACE.join(addresses_l['To'])
    if addresses_l['CC']:
        msg['Cc'] = COMMASPACE.join(addresses_l['CC'])
    msg['Date'] = formatdate(localtime=True)
    
    class WriteToLogger(object):
        def __init__(self):
            self.logger = netsvc.Logger()

        def write(self, s):
            self.logger.notifyChannel('email_send', netsvc.LOG_DEBUG, s)
    try:
        oldstderr = smtplib.stderr
        s = smtplib.SMTP()
        
        try:
            # in case of debug, the messages are printed to stderr.
            if debug:
                smtplib.stderr = WriteToLogger()

            s.set_debuglevel(int(bool(debug)))  # 0 or 1
            
            s.connect(config['smtp_server'], config['smtp_port'])
            if ssl:
                s.ehlo()
                s.starttls()
                s.ehlo()

            if config['smtp_user'] or config['smtp_password']:
                s.login(config['smtp_user'], config['smtp_password'])

            s.sendmail(email_from, addresses_l['all'], msg.as_string())

        finally:
            s.quit()
            if debug:
                smtplib.stderr = oldstderr

    except Exception, e:
        netsvc.Logger().notifyChannel('email_send', netsvc.LOG_ERROR, e)
        return False
Exemplo n.º 18
0
Available functions:
- random_tweet: Get a random recent tweet.
- latest: Get the five most recent tweets.
- get_tweet: Builds a list of tweet URLs.
- post_tweet: Posts a tweet to https://twitter.com/raidbot
- retweet: Retweets raidbot's most recently requested tweet.
"""
import json
import tweepy
import random
import io

from tools.config import config

client_key = config.get('twitter', 'client_key')
client_secret = config.get('twitter', 'client_secret')
access_token = config.get('twitter', 'access_token')
access_secret = config.get('twitter', 'access_secret')

auth = tweepy.OAuthHandler(client_key, client_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)

error = "either the tweet or the account was deleted. or something just went horrendously wrong ¯\_(ツ)_/¯"


def random_tweet(username):
    """Get a random non-reply tweet from the latest 50 tweets of an account.
    
    This function checks to make sure it the latest tweets are not entirely 
Exemplo n.º 19
0
    def import_data(self, cr, uid, fields, datas, mode='init', current_module='', noupdate=False, context=None, filename=None):
        
        if not context:
            context = {}
        def _replace_field(x):
            x = re.sub('([a-z0-9A-Z_])\\.id$', '\\1/.id', x)
            return x.replace(':id','/id').split('/')
        fields = map(_replace_field, fields)
        logger = netsvc.Logger()
        ir_model_data_obj = self.pool.get('ir.model.data')

        # mode: id (XML id) or .id (database id) or False for name_get
        def _get_id(model_name, id, current_module=False, mode='id'):
            if mode=='.id':
                id = int(id)
                obj_model = self.pool.get(model_name)
                dom = [('id', '=', id)]
                if obj_model._columns.get('active'):
                    dom.append(('active', 'in', ['True','False']))
                ids = obj_model.search(cr, uid, dom, context=context)
                if not len(ids):
                    raise Exception(_("Database ID doesn't exist: %s : %s") %(model_name, id))
            elif mode=='id':
                if '.' in id:
                    module, xml_id = id.rsplit('.', 1)
                else:
                    module, xml_id = current_module, id
                record_id = ir_model_data_obj._get_id(cr, uid, module, xml_id)
                ir_model_data = ir_model_data_obj.read(cr, uid, [record_id], ['res_id'], context=context)
                if not ir_model_data:
                    raise ValueError('No references to %s.%s' % (module, xml_id))
                id = ir_model_data[0]['res_id']
            else:
                obj_model = self.pool.get(model_name)
                ids = obj_model.name_search(cr, uid, id, operator='ilike', context=context)
                if not ids:
                    raise ValueError('No record found for %s' % (id,))
                id = ids[0][0]
            return id

        def process_liness(self, datas, prefix, current_module, model_name, fields_def, position=0, skip=0):
            line = datas[position]
            row = {}
            warning = []
            data_res_id = False
            xml_id = False
            nbrmax = position+1

            done = {}
            for i in range(len(fields)):
                res = False
                if i >= len(line):
                    raise Exception(_('Please check that all your lines have %d columns.') % (len(fields),))

                field = fields[i]
                if field[:len(prefix)] <> prefix:
                    if line[i] and skip:
                        return False
                    continue

                # ID of the record using a XML ID
                if field[len(prefix)]=='id':
                    try:
                        data_res_id = _get_id(model_name, line[i], current_module, 'id')
                    except ValueError, e:
                        pass
                    xml_id = line[i]
                    continue

                # ID of the record using a database ID
                elif field[len(prefix)]=='.id':
                    data_res_id = _get_id(model_name, line[i], current_module, '.id')
                    continue

                # recursive call for getting children and returning [(0,0,{})] or [(1,ID,{})]
                if fields_def[field[len(prefix)]]['type']=='one2many':
                    if field[len(prefix)] in done:
                        continue
                    done[field[len(prefix)]] = True
                    relation_obj = self.pool.get(fields_def[field[len(prefix)]]['relation'])
                    newfd = relation_obj.fields_get(cr, uid, context=context)
                    pos = position
                    res = []
                    first = 0
                    while pos < len(datas):
                        res2 = process_liness(self, datas, prefix + [field[len(prefix)]], current_module, relation_obj._name, newfd, pos, first)
                        if not res2:
                            break
                        (newrow, pos, w2, data_res_id2, xml_id2) = res2
                        nbrmax = max(nbrmax, pos)
                        warning += w2
                        first += 1
                        if (not newrow) or not reduce(lambda x, y: x or y, newrow.values(), 0):
                            break
                        res.append( (data_res_id2 and 1 or 0, data_res_id2 or 0, newrow) )

                elif fields_def[field[len(prefix)]]['type']=='many2one':
                    relation = fields_def[field[len(prefix)]]['relation']
                    if len(field) == len(prefix)+1:
                        mode = False
                    else:
                        mode = field[len(prefix)+1]
                    res = line[i] and _get_id(relation, line[i], current_module, mode) or False

                elif fields_def[field[len(prefix)]]['type']=='many2many':
                    relation = fields_def[field[len(prefix)]]['relation']
                    if len(field) == len(prefix)+1:
                        mode = False
                    else:
                        mode = field[len(prefix)+1]

                    # TODO: improve this by using csv.csv_reader
                    res = []
                    if line[i]:
                        for db_id in line[i].split(config.get('csv_internal_sep')):
                            res.append( _get_id(relation, db_id, current_module, mode) )
                    res = [(6,0,res)]

                elif fields_def[field[len(prefix)]]['type'] == 'integer':
                    res = line[i] and int(line[i]) or 0
                elif fields_def[field[len(prefix)]]['type'] == 'boolean':
                    res = line[i].lower() not in ('0', 'false', 'off')
                elif fields_def[field[len(prefix)]]['type'] == 'float':
                    res = line[i] and float(line[i]) or 0.0
                elif fields_def[field[len(prefix)]]['type'] == 'selection':
                    for key, val in fields_def[field[len(prefix)]]['selection']:
                        if line[i] in [tools.ustr(key), tools.ustr(val)]:
                            res = key
                            break
                    if line[i] and not res:
                        logger.notifyChannel("import", netsvc.LOG_WARNING,
                                _("key '%s' not found in selection field '%s'") % \
                                        (line[i], field[len(prefix)]))
                        warning += [_("Key/value '%s' not found in selection field '%s'") % (line[i], field[len(prefix)])]
                else:
                    res = line[i]

                row[field[len(prefix)]] = res or False
Exemplo n.º 20
0
def main():
    global LAST_UPDATE_ID
    global TRY_AGAIN_MARKOV

    # Telegram Bot Authorization Token
    bot = telegram.Bot(config.get('telegram', 'token'))

    # This will be our global variable to keep the latest update_id when requesting
    # for updates. It starts with the latest update_id if available.
    try:
        LAST_UPDATE_ID = bot.get_updates()[-1].update_id
    except IndexError:
        LAST_UPDATE_ID = None

    TRY_AGAIN_MARKOV = False

    while True:
        for update in bot.get_updates(offset=LAST_UPDATE_ID, timeout=60):
            try:
                if update.message:
                    if update.message.text:

                        def post(msg):
                            """Posts a message to Telegram."""
                            bot.send_chat_action(
                                update.message.chat_id,
                                action=telegram.ChatAction.TYPING)
                            bot.send_message(update.message.chat_id, msg)

                        def post_random(odds, msg):
                            """Has a one in x chance of posting a message to telegram."""
                            if random.randint(1, odds) == odds:
                                post(msg)

                        def append_to_file(filename, msg):
                            """Logs a line of text to a given file"""
                            with open("data/{}".format(filename),
                                      "a") as log_file:
                                log_file.write(msg)
                            log_file.close()

                        text = update.message.text.encode("utf-8")
                        first_name = update.message.from_user.first_name.encode(
                            "utf-8")

                        # logging for quotable data
                        if "group" in update.message.chat.type:
                            if update.message.chat.title.encode(
                                    "utf-8"
                            ) == "May Be A Little Late" and text[0] != '/':
                                append_to_file(
                                    "mball.txt",
                                    "{}: {}\n".format(first_name, text))

                        if text.startswith("/"):
                            text = text.replace("@originalstatic_bot", "")

                            if text.lower() == "/dev":
                                dev_url = "http://xivdb.com/assets/devtracker.json"
                                dev_response = http.request('GET', dev_url)
                                dev_json = json.loads(
                                    dev_response.read().decode())
                                print(str(dev_json))
                                try:
                                    for x in range(0, 5):
                                        username = dev_json[x]['thread'][
                                            'user']['username']
                                        dev_title = dev_json[x]['thread'][
                                            'user']['title']
                                        post_url = dev_json[x]['thread']['url']
                                        post_title = dev_json[x]['thread'][
                                            'title']

                                        post("{} ({}) posted:\n{}\n{}".format(
                                            username, dev_title, post_title,
                                            post_url))

                                except Exception as e:
                                    print(e)

                            if text.lower().startswith(
                                    "/lore") and len(text) > 6:
                                lore_search = text[6:].title()
                                post('placeholder lol')

                            if text.lower().startswith(
                                    "/map") and len(text) > 5:
                                map_search = text[5:].title()
                                try:
                                    map_found = False
                                    maps_url = 'https://api.xivdb.com/maps'
                                    maps_response = http.request(
                                        'GET', maps_url)
                                    maps_json = json.loads(
                                        maps_response.read().decode())

                                    for x in range(len(maps_json)):
                                        for y in range(
                                                len(maps_json[x]
                                                    ['placenames'])):
                                            if map_search == maps_json[x][
                                                    'placenames'][y]['name']:
                                                map_url_list = [
                                                    map_urls for map_urls in
                                                    maps_json[x]['placenames']
                                                    [y]['layers']
                                                ]
                                                map_found = True

                                    if not map_found:
                                        for x in range(len(maps_json)):
                                            for y in range(
                                                    len(maps_json[x]
                                                        ['placenames'])):
                                                map_name = maps_json[x][
                                                    'placenames'][y]['name']
                                                if map_search in map_name:
                                                    map_url_list = [
                                                        map_urls for map_urls
                                                        in maps_json[x]
                                                        ['placenames'][y]
                                                        ['layers']
                                                    ]
                                                    found_map_name = maps_json[
                                                        x]['placenames'][y][
                                                            'name']
                                                    map_found = True

                                except Exception as e:
                                    print(e)

                                if not map_found:
                                    post("couldn't find that map")
                                else:
                                    for map_url in map_url_list:
                                        post("https://api.xivdb.com{0}".format(
                                            map_url))
                                    post("found {0} in a fuzzy search".format(
                                        found_map_name))

                            if text.lower().startswith("/char"):

                                if len(text.title().split()) == 4:
                                    char_args = text.title()
                                    first = char_args.split(' ')[1]
                                    last = char_args.split(' ')[2]
                                    server = char_args.split(' ')[3]
                                    bot.send_chat_action(
                                        update.message.chat_id,
                                        action=telegram.ChatAction.TYPING)
                                    post(ffxiv_char(first, last, server))

                                elif len(text.title().split()) == 1:
                                    try:
                                        bot.send_chat_action(
                                            update.message.chat_id,
                                            action=telegram.ChatAction.TYPING)

                                        char_details = static_config.get(
                                            'static', first_name).split(' ')
                                        first = char_details[0]
                                        last = char_details[1]
                                        server = char_details[2]
                                        post(ffxiv_char(first, last, server))

                                    except Exception as e:
                                        append_to_file(
                                            "debug.txt",
                                            "{} - Error {}\n{}\n{}\n\n\n".
                                            format(str(datetime.now()), str(e),
                                                   traceback.format_exc(),
                                                   str(update)))
                                        post(
                                            "i don't know your character name. "
                                            +
                                            "tell erika or use /char [first name] [last name] [server]"
                                        )
                                else:
                                    post(
                                        "usage: /char; /char [first name] [last name] [server]"
                                    )

                            elif text.lower().startswith("/achievements"):
                                if len(text.title().split()) == 5:
                                    char_args = text.title()
                                    first = char_args.split(' ')[1]
                                    last = char_args.split(' ')[2]
                                    server = char_args.split(' ')[3]
                                    count = char_args.split(' ')[4]
                                    bot.send_chat_action(
                                        update.message.chat_id,
                                        action=telegram.ChatAction.TYPING)
                                    post(
                                        ffxiv_achievements(
                                            first, last, server, count))
                                elif len(text.title().split()) == 2:
                                    try:
                                        bot.send_chat_action(
                                            update.message.chat_id,
                                            action=telegram.ChatAction.TYPING)

                                        char_details = static_config.get(
                                            'static', first_name).split(' ')
                                        first = char_details[0]
                                        last = char_details[1]
                                        server = char_details[2]
                                        count = text.split(' ')[1]

                                        if int(count) > 40 or int(count) < 1:
                                            post("really " + first_name +
                                                 "? i mean... really?")
                                        else:
                                            post(
                                                ffxiv_achievements(
                                                    first, last, server,
                                                    count))
                                    except ValueError:
                                        post(
                                            "you failed at writing a regular number, well done"
                                        )
                                else:
                                    post(
                                        "usage: /achievements [#]; /achievements [firstname] [lastname] [server] [#]"
                                    )

                            elif text.lower().startswith(
                                    "/item ") and len(text) > 6:
                                bot.send_chat_action(
                                    update.message.chat_id,
                                    action=telegram.ChatAction.TYPING)
                                item = ffxiv_item(text[6:])
                                if str(type(item)) == "<type 'str'>":
                                    post(item)
                                else:
                                    post(item[0])
                                    if item[1] != "":
                                        post(item[1])

                            elif text.lower() == "/quote":
                                quote_file = open(
                                    "data/mball.txt").read().splitlines()
                                post(random.choice(quote_file))

                            elif text.lower().startswith(
                                    "/quote") and len(text) > 7:
                                names = static_config.get(
                                    'static', 'names').splitlines()

                                # Pull aliases for names from static_config.ini
                                name_elem = next(name for name in names
                                                 if text[7:].lower() +
                                                 ',' in name.lower())
                                name = name_elem[:name_elem.index(':') + 1]

                                quote_file = open(
                                    "data/mball.txt").read().splitlines()
                                random.shuffle(quote_file)
                                post(
                                    next(line for line in quote_file
                                         if line.startswith(name)))

                            elif text.lower().startswith("/calc"):
                                post(calculate(text, first_name))

                            elif text.lower().startswith("/tweet"):
                                if len(text) < 7:
                                    post("usage: /tweet (some garbage)")
                                elif len(text) >= 140:
                                    post(
                                        "maybe make your tweet just a teensy bit shorter?"
                                    )
                                else:
                                    post_tweet(text[7:])
                                    post(
                                        random.choice([
                                            "tweet posted. fuccckkkk",
                                            "tweet posted. this is a terrible, terrible idea",
                                            "tweet posted. why though? why?",
                                            "garbage posted.", "tweet posted.",
                                            "tweet posted. it's a shitty tweet and this is coming from a toilet"
                                        ]) + " (http://twitter.com/raidbot)")

                            elif text.lower() == "/vgm":
                                post(vgm())

                            elif text.lower().startswith("/guide"):
                                if len(text) > 7:
                                    result = guide(text[7:])
                                    if result:
                                        post(guide(text[7:]))
                                    else:
                                        post("what")
                                else:
                                    post(
                                        "usage: /guide a8 savage; /guide antitower, etc."
                                    )

                            elif text.lower().startswith("/addtwitter"):
                                # /addtwitter bird_twitter bird
                                add_twitter_cmd = text.lower().split()
                                if len(add_twitter_cmd) == 3:
                                    append_to_file(
                                        "twitters.txt", '/{},{}\n'.format(
                                            str(add_twitter_cmd[1]),
                                            str(add_twitter_cmd[2])))

                                    post("done.")
                                else:
                                    post(
                                        "usage: /addtwitter [desired command] [twitter username]"
                                    )

                            elif text.lower().startswith("/deletetwitter"):
                                del_twitter_cmd = text.lower().split()
                                full_list = []
                                found = False

                                if len(del_twitter_cmd) == 2:
                                    cmd = del_twitter_cmd[1]

                                    with open("data/twitters.txt",
                                              "r") as twitter_file:
                                        i = 0
                                        j = 0
                                        for line in twitter_file:
                                            if line.startswith(cmd) or line[
                                                    1:].startswith(cmd):
                                                j = i
                                                found = True
                                            full_list.append(line[:-1] + "\n")
                                            i += 1
                                    twitter_file.close()

                                    if found:
                                        full_list.remove(full_list[j])

                                        with open("data/twitters.txt",
                                                  "w") as twitter_file:
                                            for line in full_list:
                                                twitter_file.write(str(line))
                                        twitter_file.close()
                                        post("done.")
                                    else:
                                        post(
                                            "ummm, that account's not in the list."
                                        )
                                else:
                                    post("usage: /deletetwitter [command]")

                            elif text.lower() == "/usertwitters":
                                twitter_list = "list of saved twitters:\n"
                                with open("data/twitters.txt",
                                          "r") as twitter_file:
                                    for line in twitter_file:
                                        twitter_list += "- {}, @{}\n".format(
                                            line.split(',')[0],
                                            line.split(',')[1][:-1])
                                twitter_file.close()
                                post(twitter_list)

                            elif text.lower() == "/alias":
                                post(static_config.get('static', 'alias'))

                            elif text.lower() == "/raid":
                                post(static_config.get('static', 'raid'))

                            elif text.lower().startswith("/weather"):
                                weather, latitude, longitude = get_weather(
                                    text)
                                bot.send_location(update.message.chat_id,
                                                  latitude, longitude)
                                post(weather)

                            elif text.lower().startswith("/place"):
                                if len(text) <= 7:
                                    post("usage: /place [place name]")
                                else:
                                    place = text.title()[7:]
                                    geolocator = Nominatim()
                                    location = geolocator.geocode(place)
                                    if location:
                                        bot.send_venue(
                                            update.message.chat_id,
                                            title=place,
                                            address=location.address,
                                            latitude=location.latitude,
                                            longitude=location.longitude)
                                    else:
                                        post("couldn't find that place")

                            elif text.lower().startswith("/translate"):
                                post(translate(text))

                            elif text.lower() == "/news":
                                results = latest_tweets("ff_xiv_en")
                                if isinstance(results, str):
                                    post(results)
                                else:
                                    for tweet in results:
                                        post(
                                            "https://twitter.com/ff_xiv_en/status/{}"
                                            .format(tweet.id_str))

                            elif text.lower().startswith("/status"):
                                statuses = arrstatus()

                                if len(text) <= 8:
                                    status_text = "{} status: {}\n".format(
                                        "Excalibur",
                                        str(statuses["Excalibur"]))
                                    status_text += "{} status: {}".format(
                                        "Omega", str(statuses["Omega"]))
                                    status_text += "{} status: {}".format(
                                        "Shiva", str(statuses["Shiva"]))
                                    '''if all(value == "Online" for value in statuses.values()):
                                        status_text = "\nAll servers online"
                                    elif all(value != "Online" for value in statuses.values()):
                                        status_text = "\nall servers down. *flush*"'''
                                else:
                                    server = text.title()[8:]
                                    if server in statuses.keys():
                                        status_text = "{} status: {}".format(
                                            server, str(statuses[server]))
                                    else:
                                        status_text = "that's not a server."

                                post(status_text)

                            elif text.lower() == "/timers":
                                post(timers())

                            elif text == "/flush":
                                post("aaaah. why thank you, {}. ;)".format(
                                    first_name.lower()))

                            elif text.lower() == "/catperson":
                                post(
                                    random_tweet(
                                        random.choice(
                                            ["catboys_bot", "catgirls_bot"])))
                            elif text.lower() == "/ff14":
                                account = [
                                    "ff14forums_txt", "FFXIV_Memes",
                                    "FFXIV_Names", "FFXIV_PTFinders"
                                ]
                                post(random_tweet(random.choice(account)))
                            elif text.lower() == "/twitter":
                                account = [
                                    "ff14forums_txt", "FFXIV_Memes",
                                    "FFXIV_Names", "Goons_TXT",
                                    "YahooAnswersTXT", "TumblrTXT",
                                    "Reddit_txt", "fanfiction_txt",
                                    "WikiHowTXT", "itmeirl", "oocanime",
                                    "damothafuckinsharez0ne", "dog_rates",
                                    "FFXIV_PTFinders"
                                ]
                                post(random_tweet(random.choice(account)))

                            elif text.lower() == "/rt":
                                post(retweet())

                            elif text.lower() == "/heart":
                                post("<3<3<3 hi {} <3<3<3".format(
                                    first_name.lower()))

                            elif text.lower() == "/quoth the raven":
                                post(
                                    "http://data0.eklablog.com/live-your-life-in-books/mod_article46415481_4fb61cb0e0c79.jpg?3835"
                                )

                            elif text.lower() == "/brum":
                                post(
                                    random.choice([
                                        "https://s-media-cache-ak0.pinimg.com/736x/0c/c1/9a/0cc19aa7d2184fbeb5f4ff57442f7846.jpg",
                                        "http://i3.birminghammail.co.uk/incoming/article4289373.ece/ALTERNATES/s615/Brum1.jpg",
                                        "https://i.ytimg.com/vi/pmBX3461TdU/hqdefault.jpg",
                                        "https://i.ytimg.com/vi/bvnhLdFqo1k/hqdefault.jpg",
                                        "https://abitofculturedotnet.files.wordpress.com/2014/10/img_1133.jpg"
                                    ]))

                            else:
                                with open("data/twitters.txt",
                                          "r") as twitter_file:
                                    for line in twitter_file:
                                        cmd = line.split(',')[0]
                                        if text.lower() == cmd:
                                            post(
                                                random_tweet(
                                                    line.split(',')[1][:-1]))
                                twitter_file.close()

                        elif text.lower() == "hey":
                            post(
                                random.choice([
                                    "hi", "hi!", "hey", "yo", "eyyyy",
                                    "*flush*", "sup",
                                    "hey {}... *flush* ;)".format(
                                        first_name.lower()),
                                    "hello {}! *FLUSH*".format(
                                        first_name.lower()),
                                    "hello {}".format(first_name.lower())
                                ]))

                        elif "same" == text.lower():
                            post_random(100, "same")

                        elif text.lower().startswith("i "):
                            post_random(100, "same")

                        elif "rip" == text.lower(
                        ) or "RIP" in text or text.lower().startswith("rip"):
                            roll = random.randint(1, 100)
                            if roll == 1:
                                post("ded")
                            elif roll == 2:
                                post("yeah, rip.")
                            elif roll == 3:
                                post("rip")

                        elif text.lower() == "ping":
                            post("pong")

                        elif text.lower() == "bing":
                            post("bong")

                        elif "lol" in text.lower():
                            post_random(100, "lol")

                        elif "hail satan" in text.lower(
                        ) or "hail santa" in text.lower(
                        ) or "hail stan" in text.lower():
                            post("hail satan")

                        elif ("69" in text.lower() or "420" in text.lower()
                              ) and not text.lower().startswith("http"):
                            post_random(4, "nice")

                        elif "raidbot" in text.lower():
                            post_random(
                                100,
                                random.choice([
                                    "WHAT?? i wasn't sleeping i swear",
                                    "i can hear you fine, {}. you don't need to shout"
                                    .format(first_name.lower()),
                                    "please redirect all your questions and comments to yoship. thank you",
                                    "careful now",
                                    "my /timeplayed is a time so long it cannot be comprehended by a mortal mind",
                                    "look i'm trying to be a toilet here, stop bothering me",
                                    "beep boop. *FLUSH*",
                                    "yoship pls nerf my toilet handle",
                                    "/unsubscribe", "plumber job when?????",
                                    "switch on that toaster and throw it in me",
                                    "...", "go flush yourself",
                                    "what, you want me to say something witty?",
                                    "toilet ex farm no bonus 2 mistakes = kick",
                                    "/flush"
                                ]))

                        elif "yoship" in text.lower():
                            post_random(
                                2,
                                random.choice([
                                    "yoship pls nerf this static group (down my toilet bowl)",
                                    "i can't wait for yoship to introduce stat boosting microtransactions",
                                    "1.0 was better it had more polygons",
                                    "lvl 60 TLT lfg exdr",
                                    "they nerfed the catgirl butts i want all my sub money back",
                                    "plumber job when?????",
                                    "i know a place you can put your live letter"
                                ]))

                        elif random.randint(1, 50) == 1 or TRY_AGAIN_MARKOV:
                            if " " in text:
                                line = text.lower().strip()
                                phrase = line.split(
                                    ' ')[-2] + " " + line.split(' ')[-1]
                                result = markov(phrase)[:-1]

                                if result[:-1].lower() == phrase.lower(
                                ) or result == "" or len(result.split()) < 3:
                                    TRY_AGAIN_MARKOV = True
                                else:
                                    TRY_AGAIN_MARKOV = False
                                    post(result)
                                    update_markov_source()

                                    if len(result) > 277:
                                        result = result[:277]
                                        result = result[:result.rfind(' ')]

                                        post_tweet(result + "...")
                                    else:
                                        post_tweet(result)
                            else:
                                TRY_AGAIN_MARKOV = True

                        # elif random.randint(1, 1000) == 1: your wildest dreams

            except Exception as e:
                append_to_file(
                    "debug.txt", "{} - Error {}\n{}\n{}\n\n\n".format(
                        str(datetime.now()), str(e), traceback.format_exc(),
                        str(update)))
            finally:
                # Updates global offset to get the new updates
                LAST_UPDATE_ID = update.update_id + 1