コード例 #1
0
ファイル: profile.py プロジェクト: rlee287/serious-business
    def __init__(self, user):
        self.profiledir = _datadir+"profiles"

        if type(user) is PesterProfile:
            self.chat = user
            self.userprofile = {"handle":user.handle,
                                "color": str(user.color.name()),
                                "quirks": [],
                                "theme": "pesterchum"}
            self.theme = pesterTheme("pesterchum")
            self.chat.mood = Mood(self.theme["main/defaultmood"])
            self.lastmood = self.chat.mood.value()
            self.quirks = pesterQuirks([])
            self.randoms = False
            initials = self.chat.initials()
            if len(initials) >= 2:
                initials = (initials, "%s%s" % (initials[0].lower(), initials[1]), "%s%s" % (initials[0], initials[1].lower()))
                self.mentions = [r"\b(%s)\b" % ("|".join(initials))]
            else:
                self.mentions = []
            self.autojoins = []
        else:
            fp = open("%s/%s.js" % (self.profiledir, user))
            self.userprofile = json.load(fp)
            fp.close()
            try:
                self.theme = pesterTheme(self.userprofile["theme"])
            except ValueError as e:
                self.theme = pesterTheme("pesterchum")
            self.lastmood = self.userprofile.get('lastmood', self.theme["main/defaultmood"])
            self.chat = PesterProfile(self.userprofile["handle"],
                                      QtGui.QColor(self.userprofile["color"]),
                                      Mood(self.lastmood))
            self.quirks = pesterQuirks(self.userprofile["quirks"])
            if "randoms" not in self.userprofile:
                self.userprofile["randoms"] = False
            self.randoms = self.userprofile["randoms"]
            if "mentions" not in self.userprofile:
                initials = self.chat.initials()
                if len(initials) >= 2:
                    initials = (initials, "%s%s" % (initials[0].lower(), initials[1]), "%s%s" % (initials[0], initials[1].lower()))
                    self.userprofile["mentions"] = [r"\b(%s)\b" % ("|".join(initials))]
                else:
                    self.userprofile["mentions"] = []
            self.mentions = self.userprofile["mentions"]
            if "autojoins" not in self.userprofile:
                self.userprofile["autojoins"] = []
            self.autojoins = self.userprofile["autojoins"]

        try:
            with open(_datadir+"passwd.js") as fp:
                self.passwd = json.load(fp)
        except Exception as e:
            self.passwd = {}
        self.autoidentify = False
        self.nickservpass = ""
        if self.chat.handle in self.passwd:
            self.autoidentify = self.passwd[self.chat.handle]["auto"]
            self.nickservpass = self.passwd[self.chat.handle]["pw"]
コード例 #2
0
ファイル: irc.py プロジェクト: beloisehuffstutler/pesterchum
    def privmsg(self, nick, chan, msg):
        try:
            msg = msg.decode('utf-8')
        except UnicodeDecodeError:
            msg = msg.decode('iso-8859-1', 'ignore')
        # display msg, do other stuff
        if len(msg) == 0:
            return
        # silently ignore CTCP
        if msg[0] == '\x01':
            handle = nick[0:nick.find("!")]
            logging.warning("---> recv \"CTCP %s :%s\"" % (handle, msg[1:-1]))
            if msg[1:-1] == "VERSION":
                helpers.ctcp_reply(self.parent.cli, handle, "VERSION",
                                   "Pesterchum %s" % (_pcVersion))
            elif msg[1:-1].startswith("NOQUIRKS") and chan[0] == "#":
                op = nick[0:nick.find("!")]
                self.parent.quirkDisable.emit(chan, msg[10:-1], op)
            return
        handle = nick[0:nick.find("!")]

        if chan != "#pesterchum":
            # We don't need anywhere near that much spam.
            logging.info("---> recv \"PRIVMSG %s :%s\"" % (handle, msg))

        if chan == "#pesterchum":
            # follow instructions
            if msg[0:6] == "MOOD >":
                try:
                    mood = Mood(int(msg[6:]))
                except ValueError:
                    mood = Mood(0)
                self.parent.moodUpdated.emit(handle, mood)
            elif msg[0:7] == "GETMOOD":
                mychumhandle = self.mainwindow.profile().handle
                mymood = self.mainwindow.profile().mood.value()
                if msg.find(mychumhandle, 8) != -1:
                    helpers.msg(self.client, "#pesterchum",
                                "MOOD >%d" % (mymood))
        elif chan[0] == '#':
            if msg[0:16] == "PESTERCHUM:TIME>":
                self.parent.timeCommand.emit(chan, handle, msg[16:])
            else:
                self.parent.memoReceived.emit(chan, handle, msg)
        else:
            # private message
            # silently ignore messages to yourself.
            if handle == self.mainwindow.profile().handle:
                return
            if msg[0:7] == "COLOR >":
                colors = msg[7:].split(",")
                try:
                    colors = [int(d) for d in colors]
                except ValueError:
                    colors = [0, 0, 0]
                color = QtGui.QColor(*colors)
                self.parent.colorUpdated.emit(handle, color)
            else:
                self.parent.messageReceived.emit(handle, msg)
コード例 #3
0
ファイル: profile.py プロジェクト: Dpeta/pesterchum
    def __init__(self):
        self.logpath = _datadir + "logs"

        if not os.path.exists(self.logpath):
            os.makedirs(self.logpath)
        try:
            with open("%s/chums.js" % (self.logpath), 'r') as fp:
                chumdict = json.load(fp)
        except (IOError, ValueError):
            # karxi: This code feels awfully familiar....
            chumdict = {}
            with open("%s/chums.js" % (self.logpath), 'w') as fp:
                json.dump(chumdict, fp)

        u = []
        for (handle, c) in chumdict.iteritems():
            options = dict()
            if 'group' in c:
                options['group'] = c['group']
            if 'notes' in c:
                options['notes'] = c['notes']
            if 'color' not in c:
                c['color'] = "#000000"
            if 'mood' not in c:
                c['mood'] = "offline"
            u.append((handle,
                      PesterProfile(handle,
                                    color=QtGui.QColor(c['color']),
                                    mood=Mood(c['mood']),
                                    **options)))
        converted = dict(u)
        self.update(converted)
コード例 #4
0
 def join(self, nick, channel):
     handle = nick[0:nick.find("!")]
     logging.info("---> recv \"JOIN %s: %s\"" % (handle, channel))
     self.parent.userPresentUpdate.emit(handle, channel, "join")
     if channel == "#pesterchum":
         if handle == self.parent.mainwindow.randhandler.randNick:
             self.parent.mainwindow.randhandler.setRunning(True)
         self.parent.moodUpdated.emit(handle, Mood("chummy"))
コード例 #5
0
ファイル: irc.py プロジェクト: rlee287/serious-business
 def part(self, nick, channel, reason="nanchos"):
     nick = nick.decode('utf-8')
     channel = channel.decode('utf-8')
     handle = nick[0:nick.find("!")]
     logging.info("---> recv \"PART %s: %s\"" % (handle, channel))
     self.parent.userPresentUpdate.emit(handle, channel, "left")
     if channel == "#pesterchum":
         self.parent.moodUpdated.emit(handle, Mood("offline"))
コード例 #6
0
 def to_mood(self):
     """
     Convert the emotion to PAD space
     http://infoscience.epfl.ch/record/199429/files/510.pdf
     pg. 25
     """
     p, a, d = self._to_pad()
     mood = Mood(p*self.amount, a*self.amount, d*self.amount)
     return mood
コード例 #7
0
 def ison(self, server, nick, nicks):
     nicklist = nicks.split(" ")
     getglub = "GETMOOD "
     logging.info("---> recv \"ISON :%s\"" % nicks)
     for nick_it in nicklist:
         self.parent.moodUpdated.emit(nick_it, Mood(0))
         if nick_it in self.parent.mainwindow.namesdb["#pesterchum"]:
            getglub += nick_it
     if getglub != "GETMOOD ":
         helpers.msg(self.client, "#pesterchum", getglub)
コード例 #8
0
 def get_mood(sender_id, text):
     user = User.query.filter_by(messenger_id=sender_id).first()
     message_mood = Mood().get(text)
     if user:
         next_mood = Mood.get_next(user.mood, message_mood)
         user.mood = next_mood
     else:
         user = User(messenger_id=sender_id, mood=message_mood)
         db.session.add(user)
     db.session.commit()
     return user.mood
コード例 #9
0
def mood_from_row(row, mood_tags):
    date_string = row[0]
    try:
        d = datetime.strptime(date_string, '%d %B %Y')
    except ValueError as e:
        return None
    active_tags = [int(i) for i in row[7:]]
    active_indices = [i for (i, t) in enumerate(active_tags) if t == 1]
    tags = set([mood_tags[i] for i in active_indices])
    normalized_level = int(row[4]) // 2
    return Mood(date=d, level=normalized_level, comment=row[6], tags=tags)
コード例 #10
0
ファイル: daylio.py プロジェクト: jjst/exist-mood-import
def mood_from_row(row):
    year = row[0]
    day_and_month = row[1]
    date_string = f'{day_and_month} {year}'
    try:
        d = datetime.strptime(date_string, '%d %B %Y')
    except ValueError as e:
        return None
    level = mood_levels[row[4].strip()]
    tags = set(
        [t.strip().replace(' ', '_') for t in row[5].strip().split(' | ')])
    return Mood(date=d, level=level, comment=row[6], tags=tags)
コード例 #11
0
ファイル: app.py プロジェクト: saopayne/tone_messenger_bot
def webhook():
    # endpoint for processing incoming messaging events
    db = DBHelper()
    mood = Mood()
    data = request.get_json()
    logger(data, status=StatusType.INFO)
    mood_items = db.get_items()
    current_mood = ''
    if mood in mood_items:
        current_mood = mood_items[0]
    else:
        db.add_item(mood.TONE_NEUTRAL)
        current_mood = mood.TONE_NEUTRAL
    default_reply = mood.CONST_DEFAULT_REPLY
    if data["object"] == "page":
        for entry in data["entry"]:
            for messaging_event in entry["messaging"]:
                if messaging_event.get("message"):  # someone sent us a message
                    # the facebook ID of the person sending the bot the message
                    sender_id = messaging_event["sender"]["id"]
                    # the message sent by the user
                    if messaging_event["message"]["text"]:
                        message_text = messaging_event["message"]["text"]
                        # if can be an image or attachment ?
                        message_text = message_text.lower()
                        if message_text == mood.CONST_MOOD:
                            mood_items = db.get_items()
                            if mood in mood_items:
                                current_mood = mood
                                db.delete_item(mood)
                            else:
                                pass
                            send_message(sender_id, current_mood)
                        elif message_text in mood.default_messages:
                            send_message(sender_id, default_reply)
                        else:
                            send_response(mood=mood,
                                          message_text=message_text,
                                          sender_id=sender_id)
                    else:
                        logger(
                            "Can't process the message as it is not a text, it can either "
                            "be an attachment or something :) ",
                            StatusType.INFO)
                if messaging_event.get("delivery"):  # delivery confirmation
                    pass
                if messaging_event.get("optin"):  # optin confirmation
                    pass
                if messaging_event.get(
                        "postback"
                ):  # user clicked/tapped "postback" button in earlier message
                    pass
    return "OK", 200
コード例 #12
0
 def quit(self, nick, reason):
     handle = nick[0:nick.find("!")]
     logging.info("---> recv \"QUIT %s: %s\"" % (handle, reason))
     if handle == self.parent.mainwindow.randhandler.randNick:
         self.parent.mainwindow.randhandler.setRunning(False)
     server = self.parent.mainwindow.config.server()
     baseserver = server[server.rfind(".", 0, server.rfind(".")):]
     if reason.count(baseserver) == 2:
         self.parent.userPresentUpdate.emit(handle, "", "netsplit")
     else:
         self.parent.userPresentUpdate.emit(handle, "", "quit")
     self.parent.moodUpdated.emit(handle, Mood("offline"))
コード例 #13
0
 def nick(self, oldnick, newnick):
     oldhandle = oldnick[0:oldnick.find("!")]
     if oldhandle == self.mainwindow.profile().handle:
         self.parent.myHandleChanged.emit(newnick)
     newchum = PesterProfile(newnick, chumdb=self.mainwindow.chumdb)
     self.parent.moodUpdated.emit(oldhandle, Mood("offline"))
     self.parent.userPresentUpdate.emit("%s:%s" % (oldhandle, newnick), "", "nick")
     if newnick in self.mainwindow.chumList.chums:
         self.getMood(newchum)
     if oldhandle == self.parent.mainwindow.randhandler.randNick:
             self.parent.mainwindow.randhandler.setRunning(False)
     elif newnick == self.parent.mainwindow.randhandler.randNick:
             self.parent.mainwindow.randhandler.setRunning(True)
コード例 #14
0
 def __init__(self, handle, color=None, mood=Mood("offline"), group=None, notes="", chumdb=None):
     self.handle = handle
     if color is None:
         if chumdb:
             color = chumdb.getColor(handle, QtGui.QColor("black"))
         else:
             color = QtGui.QColor("black")
     self.color = color
     self.mood = mood
     if group is None:
         if chumdb:
             group = chumdb.getGroup(handle, "Chums")
         else:
             group = "Chums"
     self.group = group
     self.notes = notes
コード例 #15
0
ファイル: profile.py プロジェクト: timelyNoire/pesterchum
    def __init__(self):
        self.logpath = _datadir + "logs"

        if not os.path.exists(self.logpath):
            os.makedirs(self.logpath)
        try:
            fp = open("%s/chums.js" % (self.logpath), 'r')
            chumdict = json.load(fp)
            fp.close()
        except IOError:
            chumdict = {}
            fp = open("%s/chums.js" % (self.logpath), 'w')
            json.dump(chumdict, fp)
            fp.close()
        except ValueError:
            chumdict = {}
            fp = open("%s/chums.js" % (self.logpath), 'w')
            json.dump(chumdict, fp)
            fp.close()

        u = []
        for (handle, c) in chumdict.iteritems():
            options = dict()
            if 'group' in c:
                options['group'] = c['group']
            if 'notes' in c:
                options['notes'] = c['notes']
            if 'color' not in c:
                c['color'] = "#000000"
            if 'mood' not in c:
                c['mood'] = "offline"
            u.append((handle,
                      PesterProfile(handle,
                                    color=QtGui.QColor(c['color']),
                                    mood=Mood(c['mood']),
                                    **options)))
        converted = dict(u)
        self.update(converted)
コード例 #16
0
ファイル: prog.py プロジェクト: alinamuntean/ChatBotEmmaB3
table = cur.fetchall()
cur.execute("SELECT * FROM questions")
questions = cur.fetchall()

db.close()

rnd = RandomAnswer()
sessionId = 12345
# Create the kernel and learn AIML files
kernel = aiml.Kernel()
kernel.learn("std-startup.xml")
kernel.respond("load aiml b")

initialize_bot(kernel, sessionId)

botMood = Mood()

attr = getPeopleAttributes()
iKnowOp = 2

start = 0


# Press CTRL-C to break this loop
@app.route('/<question>')
def main(question):
    stop = timeit.default_timer()
    global attr
    global iKnowOp
    global start
    print botMood.get_current_mood(question)
コード例 #17
0
	def makeMood(self, moodString):
		# TODO: Temporary for testing
		return Mood(moodString, self._xLen, self._yLen, self._zLen)
コード例 #18
0
def get_streak():
    user_id = user.check_auth(request.headers.get('key'))
    if not request.headers.get('key') or not user_id:
        abort(401)
    # return current streak for this user
    streak = mood.get_streak(user_id)
    if streak is not False:
        return make_response(jsonify({'streak': streak or 0}))
    else:
        abort(500)


@mood_app.route(Urls.percentile, methods=['GET'])
def get_percentile():
    user_id = user.check_auth(request.headers.get('key'))
    if not request.headers.get('key') or not user_id:
        abort(401)
    # return current streak for this user
    percentile = mood.get_max_streak_percentile(user_id)
    if percentile is not False:
        return make_response(jsonify({'percentile': percentile or 0}))
    else:
        abort(500)


if __name__ == '__main__':
    db = DBConn()
    user = User()
    mood = Mood()
    mood_app.run(debug=True, host='0.0.0.0')
コード例 #19
0
ファイル: personality.py プロジェクト: GeorgeNagel/emotion-ai
 def to_mood(self):
     p, a, d = self._to_pad()
     mood = Mood(p, a, d)
     return mood
コード例 #20
0
ファイル: profile.py プロジェクト: Daosp/pesterchum-Dpeta-rus
    def __init__(self, user):
        self.profiledir = _datadir+"profiles"

        if type(user) is PesterProfile:
            self.chat = user
            self.userprofile = {"handle":user.handle,
                                "color": str(user.color.name()),
                                "quirks": [],
                                "theme": "pesterchum"}
            self.theme = pesterTheme("pesterchum")
            self.chat.mood = Mood(self.theme["main/defaultmood"])
            self.lastmood = self.chat.mood.value()
            self.quirks = pesterQuirks([])
            self.randoms = False
            initials = self.chat.initials()
            if len(initials) >= 2:
                initials = (initials, "%s%s" % (initials[0].lower(), initials[1]), "%s%s" % (initials[0], initials[1].lower()))
                self.mentions = [r"\b(%s)\b" % ("|".join(initials))]
            else:
                self.mentions = []
            self.autojoins = []
        else:
            # Trying to fix:
            #     IOError: [Errno 2]
            #     No such file or directory:
            #     u'XXX\\AppData\\Local\\pesterchum/profiles/XXX.js'
            # Part 3 :(
            try:
                with open("%s/%s.js" % (self.profiledir, user)) as fp:
                    self.userprofile = json.load(fp)
            except:
                
                msgBox = QtWidgets.QMessageBox()
                msgBox.setIcon(QtWidgets.QMessageBox.Information)
                msgBox.setWindowTitle(":(")
                self.filename = _datadir+"pesterchum.js"
                msgBox.setText("Failed to open \"" + \
                               ("%s/%s.js" % (self.profiledir, user)) + \
                               "\n You should switch to a different profile and set it as the default.")
                               #"\" if pesterchum acts oddly you might want to try backing up and then deleting \"" + \
                               #_datadir+"pesterchum.js" + \
                               #"\"")
                msgBox.exec_()

                
                
            try:
                self.theme = pesterTheme(self.userprofile["theme"])
            except ValueError:
                self.theme = pesterTheme("pesterchum")
            self.lastmood = self.userprofile.get('lastmood', self.theme["main/defaultmood"])
            self.chat = PesterProfile(self.userprofile["handle"],
                                      QtGui.QColor(self.userprofile["color"]),
                                      Mood(self.lastmood))
            self.quirks = pesterQuirks(self.userprofile["quirks"])
            if "randoms" not in self.userprofile:
                self.userprofile["randoms"] = False
            self.randoms = self.userprofile["randoms"]
            if "mentions" not in self.userprofile:
                initials = self.chat.initials()
                if len(initials) >= 2:
                    initials = (initials, "%s%s" % (initials[0].lower(), initials[1]), "%s%s" % (initials[0], initials[1].lower()))
                    self.userprofile["mentions"] = [r"\b(%s)\b" % ("|".join(initials))]
                else:
                    self.userprofile["mentions"] = []
            self.mentions = self.userprofile["mentions"]
            if "autojoins" not in self.userprofile:
                self.userprofile["autojoins"] = []
            self.autojoins = self.userprofile["autojoins"]

        try:
            with open(_datadir+"passwd.js") as fp:
                self.passwd = json.load(fp)
        except:
            self.passwd = {}
        self.autoidentify = False
        self.nickservpass = ""
        if self.chat.handle in self.passwd:
            # Fix for:
                # Traceback (most recent call last):
                # File "pesterchum.py", line 2944, in nickCollision
                #   File "pesterchum.py", line 1692, in changeProfile
                #   File "XXX\menus.py", line 795, in init
                #   File "XXX\profile.py", line 350, in availableProfiles
                #   File "XXX\profile.py", line 432, in init
                # KeyError: 'pw'
            if "auto" in self.passwd[self.chat.handle]:
                self.autoidentify = self.passwd[self.chat.handle]["auto"]
            if "pw" in self.passwd[self.chat.handle]:
                self.nickservpass = self.passwd[self.chat.handle]["pw"]