Почему (TypeError: объект 'str' не может быть интерпретирован как целое число) появляется в моей системе напоминаний

После долгой работы над моим мини-помощником я наткнулся на большую ошибку, которую не могу исправить в системе напоминаний. Где после запроса напоминания вылетает. Он предназначен для хранения его в переменной и файле блокнота, который будет использоваться после истечения времени (установленного в минутах). Извините за перепутанный код и показ всего кода, я не могу точно определить, где код идет не так. Код для python 3.4

Код

#import win32com.client as wincl
import webbrowser, os, datetime, time, re
#speak = wincl.Dispatch("SAPI.SpVoice")
global speech
speech=1
print("I am Squeep Bot, my current purpose is to have meaningless conversations with you or search the internet, like siri, cortana, or bonzi buddy")
reminderTime=[]
reminderMessage=[]

def writeFile(timestamp,message):
    f=open("reminders.txt","a")
    f.write(str(timestamp))
    f.write(",")
    f.write(message)
    f.write(",")
    f.close()

def loadFile():
    f=open("reminders.txt","r")
    f=f.read()
    timestamp=""
    for i in range (len(f)):
        if f[i]==",":
            if timestamp.isdigit()==True:
                reminderTime.append(int(timestamp))
                timestamp=""
            else:
                reminderMessage.append(timestamp)
                timestamp=""
        else:
            timestamp=timestamp+f[i]
    print(timestamp)

loadFile()
def unixToTime(UnixTime):
    return datetime.datetime.fromtimestamp(int(UnixTime)).strftime('%Y-%m-%d %H:%M:%S')

def readReminders(reminderTime,reminderMessage):
    for i in range (len(reminderTime)):
        if reminderTime[i]<time.time():
            print("Im reminding you that: ",reminderMessage[i], " at ",unixToTime(reminderTime[i]))
            reminderTime.pop(i)
            reminderMessage.pop(i)

def analyse(user_input):
    global speech
    ui_lower = user_input.lower()
    #conversation
    if ui_lower in ["hi", "hello"]:
        r = "Hello"
elif all(x in ui_lower for x in ("who", "you")):
    r = "I am Squeep Bot, my current purpose is to have meaningless conversations with you or search the internet, like siri, cortana, or... bonzi buddy"

elif all(x in ui_lower for x in ("how","are","you")):
    r = "I'm Ok"

elif all(x in ui_lower for x in ("what","favorite","color")):
    r = "I like Green"

elif all(x in ui_lower for x in ("what","favorite","food")):
    r = "I am a computer program, I do not eat"

elif all(x in ui_lower for x in ("are","we","friend")):
    r = "Yes, we are friends"

elif all(x in ui_lower for x in ("we","are","friend")):
    r = "why thank you"

elif all(x in ui_lower for x in ("you","not","friend")):
    r = "Gasp how could you"

elif all(x in ui_lower for x in ("i","dont","hate","you")):
    r = "ok umm thanks"

elif all(x in ui_lower for x in ("cortana", "better")):
    r = "that is true"

elif all(x in ui_lower for x in ("i","hate","you")):
    r = "Why must you be so cruel"

#functions
elif all(x in ui_lower for x in ("speech","off")):
    speech=0
    r = "ok"

elif all(x in ui_lower for x in ("speech","on")):
    speech=1
    r = "ok"


elif all(x in ui_lower for x in ("search")):
    url="https://www.google.co.uk/search?safe=strict&site=&source=hp&q="+ui_lower[6:]+"&oq=test+search&gs_l=hp.3..0l10.46616.51804.0.52437.23.17.4.2.2.0.148.1449.13j3.16.0....0...1c.1.64.hp..1.19.1245.0..35i39k1j0i131k1j0i67k1j0i20k1j0i10i67k1.WktWginLj04"
    webbrowser.open_new(url)
    r = "ok"

elif all(x in ui_lower for x in ("open")):
    os.system("start "+str(ui_lower)[5:])
    r = "Opening"

#Reminders
elif all(x in ui_lower for x in ("remind")):
    mins=str(re.findall(r' +[0-9]+ ', ui_lower))[3:-3]
    message=ui_lower[8+len(mins):]
    reminderMessage.append(message)
    reminderTime.append(round(time.time()+(int(mins)*60)))
    #print(reminder)
    mins = str(mins)
    writeFile(round(time.time()+(int(mins)*60),message))
    r = "reminder saved"
else:
    r = "I'm unable to comply"

if speech==1:
    #speak.Speak(r)
    return r
running=1
while running==1:
    user_input=[""]
    user_input[0] = input(">>> ")
    for s in (user_input):
        if user_input[0].lower()=="end":
            print("A: Goodbye")
            running=0
            break
        readReminders(reminderTime,reminderMessage)
        print("Q: {}".format(s))
        print("{}".format(analyse(s)))

Переводчик

    I am Squeep Bot, my current purpose is to have meaningless conversations with you or search the internet, like siri, cortana, or bonzi buddy

>>> remind 1 hi
Im reminding you that:  test  at  2017-05-26 13:58:31
Q: remind 1 hi
Traceback (most recent call last):
  File "U:\My Documents\py scripter\Squeepbot\Squeepbot.py", line 127, in <module>
    print("{}".format(analyse(s)))
  File "U:\My Documents\py scripter\Squeepbot\Squeepbot.py", line 108, in analyse
    writeFile(round(time.time()+(int(mins)*60),message))
TypeError: 'str' object cannot be interpreted as an integer
>>> 

Любые ответы будут полезны, даже с версткой кода


person Squidsheep    schedule 06.06.2017    source источник
comment
Вы пытаетесь использовать message в качестве второго параметра для round(), а message — это строка. Вы передаете его не той функции - переместите его за пределы вызова round().   -  person zwer    schedule 06.06.2017
comment
Эти проблемы легче обнаружить при правильном стиле кодирования ([Python]: PEP 8 - - Руководство по стилю для кода Python) (например, writeFile(round(time.time() + (int(mins) * 60), message)), упрощающее подсчет фигурных скобок.   -  person CristiFati    schedule 06.06.2017


Ответы (1)


person    schedule
comment
Спасибо! Это действительно помогает! - person Squidsheep; 06.06.2017