示例#1
0
def load_log():
    if config.first_running == 'True' or config.debug_mode:
        # if not debug_mode:
        obj = Log()
        obj.set_log('first running')
        obj.set_position('messenger first running')
        db.add_log(obj)
        config.first_running = 'False'

    try:
        conn = sqlite3.connect(config.db_log)
        cursor = conn.cursor()
        values = cursor.execute('select * from log where status=?',
                                (0, )).fetchall()

        for v in values:
            if post_log(v):
                timestamp = v[0]
                # print(timestamp)
                cursor.execute(
                    "UPDATE log SET status = 1 WHERE timestamp = '{}'".format(
                        timestamp))
                conn.commit()

        cursor.close()
        conn.close()

    except Exception as e:
        # 数据库连接,操作异常
        print(e)
        pass

    return True
示例#2
0
文件: api.py 项目: MirRaonaq/AIB
def stream(data):
    global running_threads
    try:
        data = json.loads(data)
        username = data['username']
        business = data['business']
        base64_image = data['image']
        temperature = data['temperature']
        air_pressure = data['air_pressure']
        altitude = data['altitude']
        img_str = base64_image
        print(img_str)
        if const.REALTIME_RECOG:
            converted_image = BytesIO(
                base64.b64decode(
                    re.sub("data:image/jpeg;base64", '', base64_image)))
            img_str = base64_image
            try:
                processed_image, labels = image.process_image(converted_image)

                weather = requests.get(
                    'https://api.weather.gov/alerts/active/area/NY').json()
                alert = weather['features'][0]['properties'][
                    'event'] + ' Air Pressure: ' + str(
                        air_pressure) + ' Altitude' + str(altitude)

                buffered = BytesIO()
                processed_image.save(buffered, format="JPEG")
                img_str = base64.b64encode(buffered.getvalue())
                log = {
                    'time': datetime.datetime.now(),
                    'temperature': temperature,
                    'alert': alert,
                    'labels': labels,
                    'images': [img_str],
                    'air_pressure': air_pressure,
                    'altitude': altitude
                }
                db.add_log(username, business, log)
                emit('log', log)
            except:
                pass
        elif const.MSFT_API:
            if running_threads < const.MSFT_API_THREADS:
                thread = Thread(target=process_image,
                                args=(base64_image, temperature, air_pressure,
                                      altitude, username, business))
                thread.start()
                running_threads += 1
        emit('stream', {
            'image': img_str,
            'temperature': temperature,
            'air_pressure': air_pressure,
            'altitude': altitude
        },
             broadcast=True,
             include_self=False)
    except Exception as e:
        return {'status': False, 'message': str(e)}
示例#3
0
文件: api.py 项目: MirRaonaq/AIB
def process_image(base64_image, temperature, air_pressure, altitude, username,
                  business):
    global running_threads
    global is_done
    converted_image = BytesIO(
        base64.b64decode(re.sub("data:image/jpeg;base64", '', base64_image)))
    try:
        result = image.ms_api(converted_image)
        if result is not None:
            processed_image, labels = result
            print(labels)
            current_time = str(datetime.datetime.now())
            img_str = ''

            alert = ' Air Pressure: ' + str(
                air_pressure) + ' Altitude: ' + str(altitude)

            if is_done % 3 == 0:
                send_sms('AIB Alert on ' + current_time + ': ' +
                         " ".join(labels) + ' Damage ' + alert)
                is_done = True

            is_done += 1

            try:
                weather = requests.get(
                    'https://api.weather.gov/alerts/active/area/NY').json()
                alert = weather['features'][0]['properties']['event'] + alert
            except Exception as e:
                print("WEATHER ERROR: " + str(e))

            try:
                buffered = BytesIO()
                processed_image.save(buffered, format="JPEG")
                img_str = base64.b64encode(buffered.getvalue())
            except:
                pass

            log = {
                'time': current_time,
                'temperature': temperature,
                'alert': alert,
                'labels': labels,
                'images': [img_str]
            }
            socketio.emit('log', log, broadcast=True, include_self=False)
            db.add_log(username, business, log)
    except Exception as e:
        print("ERROR: " + str(e))
    running_threads -= 1
示例#4
0
def check_version():
    sess = requests.Session()
    try:
        r = sess.get(url=config.api_version)
        if r.status_code == 200:
            server_version = r.text
            if utils.find_new_version(config.version, server_version):
                # print('find new version')
                obj = Log()
                obj.set_log('find new version')
                obj.set_position('OTA check version')
                db.add_log(obj)
                if download_files():
                    msg.load_log()
                    config.version = r.text.strip()
                    config.first_running = 'True'

        else:
            print('internet connect error')
    except Exception as e:
        print(e)
        pass
示例#5
0
async def logUser(m, state):
    # Attempt to generate user object
    userid = ul.parse_mention(m)
    if userid == None:
        if state == LogTypes.NOTE:
            await m.channel.send("I wasn't able to understand that message: `$note USER`")
        else:
            await m.channel.send("I wasn't able to understand that message: `$log USER`")
        return

    # Calculate value for 'num' category in database
    # For warns, it's the newest number of warns, otherwise it's a special value
    if state == LogTypes.WARN:
        count = db.get_warn_count(userid)
    else:
        count = state.value
    currentTime = datetime.datetime.utcnow()

    # Attempt to fetch the username for the user
    username = ul.fetch_username(m.guild, userid)
    if username == None:
        username = "******" + str(userid)
        await m.channel.send("I wasn't able to find a username for that user, but whatever, I'll do it anyway.")

    # Generate log message, adding URLs of any attachments
    content = utils.combineMessage(m)
    mes = utils.parseMessage(content, username)

    # If they didn't give a message, abort
    if mes == "":
        await m.channel.send("Please give a reason for why you want to log them.")
        return

    # Update records for graphing
    import visualize
    if state == LogTypes.BAN:
        visualize.updateCache(m.author.name, (1, 0), utils.formatTime(currentTime))
    elif state == LogTypes.WARN:
        visualize.updateCache(m.author.name, (0, 1), utils.formatTime(currentTime))
    elif state == LogTypes.UNBAN:
        await m.channel.send("Removing all old logs for unbanning")
        db.clear_user_logs(userid)

    # Generate message for log channel
    globalcount = db.get_dbid()
    new_log = db.UserLogEntry(globalcount + 1, userid, username, count, currentTime, mes, m.author.name, None)
    logMessage = str(new_log)
    await m.channel.send(logMessage)

    # Send ban recommendation, if needed
    if (state == LogTypes.WARN and count >= config.WARN_THRESHOLD):
        await m.channel.send("This user has received {} warnings or more. It is recommended that they be banned.".format(config.WARN_THRESHOLD))

    logMesID = 0
    # If we aren't noting, need to also write to log channel
    if state != LogTypes.NOTE:
        # Post to channel, keep track of message ID
        try:
            chan = discord.utils.get(m.guild.channels, id=config.LOG_CHAN)
            logMes = await chan.send(logMessage)
            logMesID = logMes.id
        except discord.errors.InvalidArgument:
            await m.channel.send("The logging channel has not been set up in `config.json`. In order to have a visual record, please specify a channel ID.")

        try:
            # Send a DM to the user
            u = ul.fetch_user(m.guild, userid)
            if u != None:
                DMchan = u.dm_channel
                # If first time DMing, need to create channel
                if DMchan == None:
                    DMchan = await u.create_dm()

                # Only send DM when specified in configs
                if state == LogTypes.BAN and config.DM_BAN:
                    await DMchan.send("Hi there! You've been banned from the Stardew Valley Discord for violating the rules: `{}`. If you have any questions, you can send a message to the moderators via the sidebar at <https://www.reddit.com/r/StardewValley>, and they'll forward it to us.".format(mes))
                elif state == LogTypes.WARN and config.DM_WARN:
                    await DMchan.send("Hi there! You received warning #{} in the Stardew Valley Discord for violating the rules: `{}`. Please review <#445729591533764620> and <#445729663885639680> for more info. If you have any questions, you can reply directly to this message to contact the staff.".format(count, mes))
                elif state == LogTypes.KICK and config.DM_BAN:
                    await DMchan.send("Hi there! You've been kicked from the Stardew Valley Discord for violating the following reason: `{}`. If you have any questions, you can send a message to the moderators via the sidebar at <https://www.reddit.com/r/StardewValley>, and they'll forward it to us.".format(mes))

        # Exception handling
        except discord.errors.HTTPException as e:
            await m.channel.send("ERROR: While attempting to DM, there was an unexpected error. Tell aquova this: {}".format(e))
        except Exception as e:
            await m.channel.send( "ERROR: An unexpected error has occurred. Tell aquova this: {}".format(e))

    # Update database
    new_log.message_url = logMesID
    db.add_log(new_log)
示例#6
0
async def removeError(m, edit):
    userid = ul.parse_mention(m)
    if userid == None:
        if edit:
            await m.channel.send("I wasn't able to understand that message: `$remove USER [num] new_message`")
        else:
            await m.channel.send("I wasn't able to understand that message: `$remove USER [num]`")
        return

    username = ul.fetch_username(m.guild, userid)
    if username == None:
        username = str(userid)

    # If editing, and no message specified, abort.
    mes = utils.parseMessage(m.content, username)
    if mes == "":
        if edit:
            await m.channel.send("You need to specify an edit message")
            return
        else:
            mes = "0"

    try:
        index = int(mes.split()[0]) - 1
        mes = utils.strip(mes)
    except (IndexError, ValueError):
        index = -1

    # Find most recent entry in database for specified user
    search_results = db.search(userid)
    # If no results in database found, can't modify
    if search_results == []:
        await m.channel.send("I couldn't find that user in the database")
    # If invalid index given, yell
    elif (index > len(search_results) - 1) or index < -1:
        await m.channel.send("I can't modify item number {}, there aren't that many for this user".format(index + 1))
    else:
        item = search_results[index]
        import visualize
        if edit:
            if item.log_type == LogTypes.NOTE.value:
                currentTime = datetime.datetime.utcnow()
                item.timestamp = currentTime
                item.log_message = mes
                item.staff = m.author.name
                db.add_log(item)
                out = "The log now reads as follows:\n{}\n".format(str(item))
                await m.channel.send(out)

                return
            else:
                await m.channel.send("You can only edit notes for now")
                return

        # Everything after here is deletion
        db.remove_log(item.dbid)
        out = "The following log was deleted:\n"
        out += str(item)

        if item.log_type == LogTypes.BAN:
            visualize.updateCache(item.staff, (-1, 0), utils.formatTime(item.timestamp))
        elif item.log_type == LogTypes.WARN:
            visualize.updateCache(item.staff, (0, -1), utils.formatTime(item.timestamp))
        await m.channel.send(out)

        # Search logging channel for matching post, and remove it
        try:
            if item.message_url != 0:
                chan = discord.utils.get(m.guild.channels, id=config.LOG_CHAN)
                m = await chan.fetch_message(item.message_url)
                await m.delete()
        # Print message if unable to find message to delete, but don't stop
        except discord.errors.HTTPException as e:
            print("Unable to find message to delete: {}", str(e))
示例#7
0
async def logUser(m: discord.Message, state: LogTypes):
    # Attempt to generate user object
    userid = ul.parse_id(m)
    if not userid:
        if state == LogTypes.NOTE:
            await m.channel.send(f"I wasn't able to understand that message: `{CMD_PREFIX}note USER`")
        else:
            await m.channel.send(f"I wasn't able to understand that message: `{CMD_PREFIX}log USER`")
        return

    # Calculate value for 'num' category in database
    # For warns, it's the newest number of warns, otherwise it's a special value
    if state == LogTypes.WARN:
        count = db.get_warn_count(userid)
    else:
        count = state.value
    currentTime = datetime.now(timezone.utc)

    # Attempt to fetch the username for the user
    username = lookup_username(userid)
    if not username:
        username = "******" + str(userid)
        await m.channel.send("I wasn't able to find a username for that user, but whatever, I'll do it anyway.")

    # Generate log message, adding URLs of any attachments
    content = commonbot.utils.combine_message(m)
    mes = commonbot.utils.parse_message(content, username)

    if state == LogTypes.SCAM:
        mes = "Banned for sending scam in chat."

    # If they didn't give a message, abort
    if mes == "":
        await m.channel.send("Please give a reason for why you want to log them.")
        return

    # Update records for graphing
    import visualize
    if state == LogTypes.BAN or state == LogTypes.SCAM:
        visualize.update_cache(m.author.name, (1, 0), commonbot.utils.format_time(currentTime))
    elif state == LogTypes.WARN:
        visualize.update_cache(m.author.name, (0, 1), commonbot.utils.format_time(currentTime))
    elif state == LogTypes.UNBAN:
        await m.channel.send("Removing all old logs for unbanning")
        db.clear_user_logs(userid)

    # Generate message for log channel
    globalcount = db.get_dbid()
    new_log = db.UserLogEntry(globalcount + 1, userid, username, count, currentTime, mes, m.author.name, None)
    logMessage = str(new_log)
    await m.channel.send(logMessage)

    # Send ban recommendation, if needed
    if (state == LogTypes.WARN and count >= config.WARN_THRESHOLD):
        await m.channel.send(f"This user has received {config.WARN_THRESHOLD} warnings or more. It is recommended that they be banned.")

    logMesID = 0
    # If we aren't noting, need to also write to log channel
    if state != LogTypes.NOTE:
        # Post to channel, keep track of message ID
        try:
            chan = discord.utils.get(m.guild.channels, id=config.LOG_CHAN)
            logMes = await chan.send(logMessage)
            logMesID = logMes.id
        except discord.errors.InvalidArgument:
            await m.channel.send("The logging channel has not been set up in `config.json`. In order to have a visual record, please specify a channel ID.")

        try:
            # Send a DM to the user
            u = client.get_user(userid)
            if u:
                DMchan = u.dm_channel
                # If first time DMing, need to create channel
                if not DMchan:
                    DMchan = await u.create_dm()

                # Only send DM when specified in configs
                if state == LogTypes.BAN and config.DM_BAN:
                    await DMchan.send(BAN_KICK_MES.format(type="banned", mes=mes))
                elif state == LogTypes.WARN and config.DM_WARN:
                    await DMchan.send(WARN_MES.format(count=count, mes=mes))
                elif state == LogTypes.KICK and config.DM_BAN:
                    await DMchan.send(BAN_KICK_MES.format(type="kicked", mes=mes))
                elif state == LogTypes.SCAM and config.DM_BAN:
                    await DMchan.send(SCAM_MES)
        # Exception handling
        except discord.errors.HTTPException as e:
            if e.code == 50007:
                await m.channel.send(f"Cannot send messages to this user. It is likely they have DM closed or I am blocked.")
            else:
                await m.channel.send(f"ERROR: While attempting to DM, there was an unexpected error. Tell aquova this: {e}")
        except Exception as e:
            await m.channel.send(f"ERROR: An unexpected error has occurred. Tell aquova this: {e}")

    # Update database
    new_log.message_id = logMesID
    db.add_log(new_log)