Exemplo n.º 1
0
    def __init__(self):
        # logger.info(f"{self.__class__.__name__} ({inspect.currentframe().f_code.co_name})")
        if self.db_file.is_file():
            logger.debug(f"Database file exists... {self.db_file}")
        else:
            logger.debug(
                f"Database file does not exist... creating {self.db_file}")
            self.db_file.touch()

        try:
            self.connection = sqlite3.connect(self.db_file)
            self.cursor = self.connection.cursor()
            logger.debug(sqlite3.version)
        except Error as e:
            logger.error(e)

        if self.key_file.is_file():
            logger.debug(f"Key file exists... {self.key_file}")
        else:
            logger.debug(
                f"Key file does not exist... creating {self.key_file}")
            kdf = PBKDF2HMAC(
                algorithm=hashes.SHA256(),
                iterations=100000,
                length=32,
                salt=os.urandom(16),
            )
            passphrase = os.environ.get("JIBOT_CRYPTO_PASS_PHRASE",
                                        "").encode('utf-8')
            key = base64.urlsafe_b64encode(kdf.derive(passphrase))
            fernet: Fernet = Fernet(key).generate_key()
            self.key_file.write_bytes(fernet)
        self.cipher = Fernet(open(self.key_file, "rb").read())
Exemplo n.º 2
0
Arquivo: slack.py Projeto: Joi/jibot3
 def slack_api_error(self, error: SlackApiError):
     error_name = error.response['error']
     assert (error_name)
     if error_name == 'missing_scope':
         missing_scope = error.response['needed']
         message = f"The bot is missing proper oauth scope!({missing_scope}). Scopes are added to your bot at https://api.slack.com/apps."
         logger.error(message)
     logger.error(error)
Exemplo n.º 3
0
Arquivo: slack.py Projeto: Joi/jibot3
 def test_slack_client_connection(self):
     logger.info("Testing slack client connectivity...")
     try:
         self.bolt.client.api_test().get("ok")
         logger.info("Slack client OK.")
     except SlackApiError as e:
         logger.error("Unable to establish a slack web client connection!")
         self.slack_api_error(e)
Exemplo n.º 4
0
def sendtelegram(chatid, msg):
    #    try:
    splitted_text = telebot.util.split_string(msg, 4096)
    for text in splitted_text:
        try:
            bot.send_message(chatid, text, parse_mode="markdown")
        except telebot.apihelper.ApiHTTPException as e:
            logger.warning(
                "ConnectionError - Sending again after 5 seconds!!!")
            logger.warning("HTTP Error Code: {}".format(e.result))
            sleep(5)
            bot.send_message(chatid, text, parse_mode="markdown")
        except:
            logger.error(
                "ERROR IN SENDING TELEGRAM MESSAGE TO {}".format(chatid))
            logger.error("Error: {}".format(sys.exc_info()[0]))
Exemplo n.º 5
0
def user_ok(bot, connection, allowmode, tggroup, chat_id):
    cursor = connection.cursor()

    # check if user is blocked
    cursor.execute("select count(*) from userblock where chatid = '%s'" %
                   (chat_id))
    if cursor.fetchone()[0] == 1:
        return False

    if not allowmode:
        return True

    # check if user is in allow Table
    cursor.execute("select count(*) from userallow where chatid = '%s'" %
                   (chat_id))
    if cursor.fetchone()[0] == 1:
        return True

    # check TGGroup
    if tggroup:
        try:
            if chat_id in tg_cache:
                time_delta = datetime.now() - tg_cache[chat_id]
                if time_delta.total_seconds() / 60 < tg_cache_timeout:
                    return True
                else:
                    tg_cache.pop(chat_id)

            result = bot.get_chat_member(tggroup, chat_id)
            if result.status in is_member:
                tg_cache[chat_id] = datetime.now()
                return True
        except telebot.apihelper.ApiHTTPException as e:
            logger.warning("HTTP Error Code: {}".format(e.result))
        except:
            logger.error(
                "ERROR IN GETTING MEMBER FROM GROUP {}".format(tggroup))
            logger.error("Error: {}".format(sys.exc_info()[0]))

    return False
Exemplo n.º 6
0
def send_range(chatid):

    cursor.execute(
        "select lat,lon,dist from user where chatid = '%s' and botid = '%s'" %
        (chatid, botid))
    result = cursor.fetchone()

    data = io.StringIO(
        '<html>\n<head>\n<title>Your location</title>\n<script src="http://www.openlayers.org/api/OpenLayers.js"></script>\n\
</head>\n<body>\n<div id="mapdiv"></div>\n<script>\nmap = new OpenLayers.Map("mapdiv");\nmap.addLayer(new OpenLayers.Layer.OSM());\n\
epsg4326 = new OpenLayers.Projection("EPSG:4326");\nprojectTo = map.getProjectionObject();\n\
var lonLat = new OpenLayers.LonLat({},{}).transform(epsg4326, projectTo);\nvar zoom = 14;\nmap.setCenter(lonLat, zoom);\n\
var vectorLayer = new OpenLayers.Layer.Vector("Overlay");\nvar point = new OpenLayers.Geometry.Point(lonLat.lon, lonLat.lat);\n\
var mycircle = OpenLayers.Geometry.Polygon.createRegularPolygon\n(point,{},30,0);\nvar featurecircle = new OpenLayers.Feature.Vector(mycircle);\n\
var featurePoint = new OpenLayers.Feature.Vector(point);\nvectorLayer.addFeatures([featurePoint, featurecircle]);\n\
map.addLayer(vectorLayer);</script></body></html>'.format(
            result[1], result[0], result[2] * 1609))

    data.name = 'your_range.html'

    try:
        bot.send_document(chatid, data)
    except telebot.apihelper.ApiHTTPException as e:
        logger.error("ERROR IN SENDING TELEGRAM MESSAGE TO {}".format(chatid))
        logger.warning("HTTP Error Code: {}".format(e.result))
    except:
        logger.error("ERROR IN SENDING TELEGRAM MESSAGE TO {}".format(chatid))
        logger.error("Error: {}".format(sys.exc_info()[0]))
Exemplo n.º 7
0
def sendmonster(bot, config, connection, pkmn_loc, geoprovider, geofences,
                allowmode):
    cursor = connection.cursor()

    botid = bot.get_me().id
    venuetitle = config['venuetitle']
    venuemsg = str(config['venuemsg'])
    ivmsg = str(config['ivmsg'])
    tggroup = config.get('tggroup', '')

    while True:
        message = pkmn_queue.get()

        pkmn_id = (message['pokemon_id'])

        # set monster info
        #
        try:
            pkmn_name = pkmn_loc[str(pkmn_id)]["name"]
        except:
            pkmn_name = "{} NOTFOUND".format(str(pkmn_id))
            logger.warning("{} not found in monster.json".format(str(pkmn_id)))

        # check if in geofence
        #
        if geofences:
            inside = False
            for geofence in geofences.keys():
                mypath = mplPath.Path(geofences[geofence])
                if mypath.contains_points(
                    [tuple((message['latitude'], message['longitude']))]):
                    inside = True
                    break
            if not inside:
                logger.info("{}({}) outside geofence".format(
                    pkmn_name, pkmn_id))
                continue

        pkmn_despawn = datetime.datetime.fromtimestamp(
            int(message['disappear_time'])).strftime('%H:%M:%S')
        logger.info("{}({}) until {} @ {},{}".format(pkmn_name, pkmn_id,
                                                     pkmn_despawn,
                                                     message['latitude'],
                                                     message['longitude']))

        # calculate IV if encounting
        #
        try:
            pkmn_iv = float((
                (message['individual_attack'] + message['individual_defense'] +
                 message['individual_stamina']) * 100 / 45)).__round__(2)
            logger.info(
                "IV:{:.2f} CP:{:4d} ATT:{:2d} DEF:{:2d} STA:{:2d}".format(
                    pkmn_iv, message['cp'], message['individual_attack'],
                    message['individual_defense'],
                    message['individual_stamina']))
        except:
            pkmn_iv = "None"
            message['individual_attack'] = "??"
            message['individual_defense'] = "??"
            message['individual_stamina'] = "??"
            message['cp'] = "??"
            message['pokemon_level'] = "??"

        if not 'boosted_weather' in message:
            message['boosted_weather'] = 0

        # add missing data to message
        message['iv'] = pkmn_iv
        message['name'] = pkmn_name
        message['despawn'] = pkmn_despawn
        message['geo_ok'] = False

        # get all chatids for the monster
        # no blocked chat id
        #
        connection.ping(reconnect=True)
        cursor.execute(
            "select chatid,iv,level from userassign where pkmnid = '%s' and \
                        chatid in (select chatid from user where botid = '%s')"
            % (pkmn_id, botid))
        result_pkmn = cursor.fetchall()

        if len(result_pkmn) > 0:

            # send monster message to all
            #
            for chat_id, iv, level in result_pkmn:

                if not user_ok(bot, connection, allowmode, tggroup, chat_id):
                    logger.info(
                        "ChatID {} not allowed for this Bot but has assignments"
                        .format(chat_id))
                    continue

                # get the user details
                cursor.execute(
                    "select lat,lon,dist from user where chatid = '%s'" %
                    (chat_id))
                latlon = cursor.fetchone()
                lat = float(latlon[0])
                lon = float(latlon[1])
                dist = float(latlon[2])

                # check distance
                dist_ok = True
                if dist > 0:
                    pkmn_dist = distance.distance(
                        (lat, lon),
                        (message['latitude'], message['longitude'])).kilometers
                    if pkmn_dist > dist:
                        dist_ok = False
                        logger.info(
                            "{} long distance: dist: {}  pkmn_dist: {}".format(
                                chat_id, dist, pkmn_dist))

                # check level
                if message['pokemon_level'] == '??':
                    level_ok = True
                elif int(message['pokemon_level']) >= level:
                    level_ok = True
                else:
                    level_ok = False

                if not (dist_ok and level_ok):
                    continue

                if message['iv'] == "None":
                    if iv == -1:
                        # get geo only if not set
                        if not message['geo_ok']:
                            geo = geo_reverse(geoprovider, message['latitude'],
                                              message['longitude'])
                            message['road'] = "{} {}".format(geo[0], geo[1])
                            message['postcode'] = geo[2]
                            message['town'] = geo[3]
                            message['geo_ok'] = True

                        venuetitle1 = textsub(venuetitle, message)
                        venuemsg1 = textsub(venuemsg, message)
                        try:
                            bot.send_venue(chat_id, message['latitude'],
                                           message['longitude'], venuetitle1,
                                           venuemsg1)
                            logger.info(
                                "Send Telegram message to {} Monster {}({})".
                                format(chat_id, pkmn_name, pkmn_id))
                        except telebot.apihelper.ApiTelegramException as e:
                            if e.result_json['error_code'] == 403:
                                bot_was_blocked(connection, botid, chat_id)
                        except telebot.apihelper.ApiHTTPException as e:
                            logger.error("Connection Error")
                            logger.error("HTTP Error Code: {}".format(
                                e.result))
                        except:
                            logger.error(
                                "ERROR IN SENDING TELEGRAM MESSAGE TO {}".
                                format(chat_id))
                            logger.error("Error: {}".format(sys.exc_info()[0]))
                    else:
                        logger.info(
                            "No message send to {}. SearchIV set but Monster {}({}) not encountered"
                            .format(chat_id, pkmn_name, pkmn_id))
                elif message['iv'] >= iv:
                    try:
                        # get geo only if not set
                        if not message['geo_ok']:
                            geo = geo_reverse(geoprovider, message['latitude'],
                                              message['longitude'])
                            message['road'] = "{} {}".format(geo[0], geo[1])
                            message['postcode'] = geo[2]
                            message['town'] = geo[3]
                            message['geo_ok'] = True

                        ivmsg1 = textsub(ivmsg, message)

                        bot.send_message(chat_id, ivmsg1)
                        bot.send_location(chat_id, message['latitude'],
                                          message['longitude'])
                        logger.info(
                            "Send Telegram IV message to {} Monster {}({})".
                            format(chat_id, pkmn_name, pkmn_id))
                    except telebot.apihelper.ApiTelegramException as e:
                        if e.result_json['error_code'] == 403:
                            bot_was_blocked(connection, botid, chat_id)
                    except telebot.apihelper.ApiHTTPException as e:
                        logger.error("Connection Error")
                        logger.error("HTTP Error Code: {}".format(e.result))
                    except:
                        logger.error(
                            "ERROR IN SENDING TELEGRAM MESSAGE TO {}".format(
                                chat_id))
                        logger.error("Error: {}".format(sys.exc_info()[0]))
                else:
                    logger.info(
                        "No message send to {}. SearchIV to low for Monster {}({})"
                        .format(chat_id, pkmn_name, pkmn_id))
Exemplo n.º 8
0
        logger.info("Dryrun")
except:
    pass

# read inifile
#
try:
    config = ConfigObj(args.configfile)
    db = config['dbname']
    dbhost = config['dbhost']
    dbport = config.get('dbport', '3306')
    dbuser = config['dbuser']
    dbpassword = config['dbpassword']
    reorgdays = int((config.get('reorgdays', '180')))
except:
    logger.error("Inifile not given or missing parameter")
    quit()

# connect to database
#
try:
    connection = pymysql.connect(host=dbhost,
                                 user=dbuser,
                                 password=dbpassword,
                                 db=db,
                                 port=int(dbport),
                                 charset='utf8mb4',
                                 autocommit='True')
    cursor = connection.cursor()
except:
    logger.error("can not connect to database")
Exemplo n.º 9
0
def geo_reverse(geolocator, lat, lon):
    if not geolocator:
        return ['', '', '', '']

    try:
        location = geolocator.reverse('%s, %s' % (lat, lon), timeout=10)
    except geopy.exc.ConfigurationError as e:
        logger.error("something wrong in the geo configuration")
        logger.error("{}".format(e))
        return ['', '', '', '']
    except geopy.exc.GeocoderAuthenticationFailure as e:
        logger.error("Authentication Failure with the geolocation service")
        logger.error("{}".format(e))
        return ['', '', '', '']
    except geopy.exc.GeocoderServiceError as e:
        logger.error("something wrong with the geolocation service")
        logger.error("{}".format(e))
        return ['', '', '', '']

    if geolocator.__class__.__name__ == 'Nominatim':
        detail = location.raw.get('address')
        return [
            detail.get('road', ''),
            detail.get('house_number', ''),
            detail.get('postcode', ''),
            detail.get('town', '')
        ]
    elif geolocator.__class__.__name__ == 'GoogleV3':
        detail = {}
        for item in location.raw.get('address_components'):
            for category in item['types']:
                detail[category] = item['short_name']
        return [
            detail.get('route', ''),
            detail.get('street_number', ''),
            detail.get('postal_code', ''),
            detail.get('locality', detail.get('postal_town', ''))
        ]
Exemplo n.º 10
0
    dbport = config.get('dbport', '3306')
    dbuser = config['dbuser']
    dbpassword = config['dbpassword']
    locale = config.get('locale', 'de')
    whport = int(config.get('port', '6000'))
    invstartmsg = config.get('startmsg', "locales/startmsg_" + locale + ".txt")
    nominatim = config.as_bool('nominatim')
    nominatim_scheme = config.get('nominatim_scheme', 'https')
    nominatim_url = config.get('nominatim_url', 'nominatim.openstreetmap.org')
    gmaps = config.as_bool('gmaps')
    gmaps_apikey = config.get('gmaps_apikey', False)
    geofencefile = config.get('geofile', False)
    allowmode = config.as_bool('allowmode')
    tggroup = config.get('tggroup', '')
except:
    logger.error("Error in config.ini")
    raise

##################
# check some parameters
if nominatim and gmaps:
    logger.error("please use only one geo provider")
    quit()
if gmaps and not gmaps_apikey:
    logger.error("please set your gmaps API Key")
    quit()

##################
# connect to database
try:
    connection = pymysql.connect(host=dbhost,