Esempio n. 1
0
def Main(status, tmp, mode='dm'):
    ans = ''
    IMGfile = ''
    tweetStatus = ''
    filename = ''
    text = status['cleanText']
    status_id = status['id_str']
    screen_name = status['user']['screen_name']
    userinfo, isNewUser = dealSQL.getUserInfo(screen_name)
    now = status['now']

    BOT_ID = tmp['BOT_ID']

    #時間計測(秒)
    try:
        try:
            delta = now - userinfo['time']
        except:  #文字列対策
            print('convert str into datetime')
            delta = now - datetime.strptime(userinfo['time'],
                                            '%Y-%m-%d %H:%M:%S.%f')
        deltasec = delta.total_seconds()
    except Exception as e:
        print(e)
        deltasec = 50

    #返答タイムアウト処理
    if deltasec > 1000:
        userinfo['cnt'] = 0
        userinfo['mode'] = 'dialog'
        if userinfo['mode'] == 'confirm.tag.img':
            src = userinfo['tmpFile']
            drc = DIRIMGundefined
            if os.path.exists(drc) == False:
                os.mkdir(drc)
            shutil.copy(src, drc)

    # 応答
    if 'ping' in text:
        ans = ''.join(['Δsec : ', str(deltasec)])
    elif userinfo['mode'] == 'ignore':
        userinfo['cnt'] = 0
        userinfo['mode'] = 'dialog'
    elif deltasec < 3:
        ans = dealSQL.getPhrase(s_type='tooFreq', n=20)
        userinfo['mode'] = 'ignore'
    elif 'userinfo' in text:
        ans = str(userinfo)
    elif userinfo['mode'] == 'learn.text':
        if status['in_reply_to_screen_name'] in {BOT_ID}:
            text = status['text'].replace('@' + BOT_ID, '')
            text = re.sub(r'(@[^\s ]+)', '{ID}', text)
            if 'end' in text:
                userinfo['mode'] = 'dialog'
                userinfo['tmp'] = ''
                ans = 'learningモードをクローズしました。この結果は開発にフィードバックされます。ご協力感謝します。'
            else:
                labelstatus = userinfo['tmp']
                userinfo['cnt'] = 0
                dealSQL.savePhrase(phrase=text,
                                   author=screen_name,
                                   status=labelstatus,
                                   s_type='UserLearn')
                ans = '[learning]saved!!... 続けて覚えさせるテキストをリプライしてください。\nendと入力するまでモードは続きます。'
        else:
            ans = 'learningモードの途中です。覚えさせるテキストをリプライしてください。\nendと入力するまでモードは続きます。'
    elif userinfo['mode'] == 'sleeping' and deltasec > 3600:
        ans = dealSQL.getPhrase(s_type='goodmorning', n=1)
        ans += '\n' + dealSQL.getPhrase(s_type='sleep.span', n=1).format(
            utiltools.sec2HMSstr(deltasec))
        userinfo['mode'] = 'dialog'

    elif 'media' in status['entities'] and status[
            'in_reply_to_screen_name'] in {BOT_ID}:
        userinfo['cnt'] = 0
        fileID = now.strftime("%Y%m%d%H%M%S")
        if status['entities']['hashtags'] != []:
            imgtag = status['entities']['hashtags'][0]['text']
            try:
                filenames = utiltools.saveMedias(status,
                                                 ID=fileID,
                                                 DIR='/'.join(
                                                     [DIRIMGfeedback, imgtag]))
                ans = dealSQL.getPhrase(s_type='appreciate.giveme.img',
                                        n=1).format(imgtag)
            except Exception as e:
                print(e)
                ans = dealSQL.getPhrase(s_type='err.get.img', n=1)
        else:
            try:
                filenames = utiltools.saveMedias(status,
                                                 ID=fileID,
                                                 DIR=DIRIMGtmp)
                filename = filenames[0]
                label, FACEflag, IMGfile = NNimg.predictAns(filename=filename,
                                                            isShow=False,
                                                            model=modelNNimg,
                                                            workDIR='')
                if FACEflag == False:
                    ans = dealSQL.getPhrase(s_type='confirm.detect.img.noface',
                                            n=1).format(label)
                else:
                    ans = dealSQL.getPhrase(s_type='confirm.detect.img',
                                            n=1).format(label)

                drc = '/'.join([DIRIMGfeedback, label])
                if os.path.exists(drc) == False:
                    os.mkdir(drc)
                shutil.copy(filename, drc)

                userinfo['mode'] = 'confirm.tag.img'
                print('/'.join([drc, filename.split('/')[-1]]))
                userinfo['tmpFile'] = '/'.join([drc, filename.split('/')[-1]])
                filename = IMGfile
            except Exception as e:
                print(e)
                ans = dealSQL.getPhrase(s_type='err.get.img', n=1)

    elif userinfo['mode'] == 'confirm.tag.img':
        userinfo['cnt'] = 0
        if status['entities']['hashtags'] != []:
            imgtag = status['entities']['hashtags'][0]['text']
            isMoveDIR = True
        elif not 'ない' in text and ('正解' in text or '正し' in text):
            ans = dealSQL.getPhrase(s_type='success.detect.img', n=1)
            userinfo['mode'] = 'dialog'
            isMoveDIR = False
        else:
            try:
                imgtag = TFIDF.calcKWs(text, length=1, needs={'固有名詞',
                                                              '名詞'})[0][0]
            except Exception as e:
                print(e)
                imgtag = 'undefined'
            isMoveDIR = True
        if isMoveDIR:
            src = userinfo['tmpFile']
            drc = '/'.join([DIRIMGfeedback, imgtag])
            if os.path.exists(drc) == False:
                os.mkdir(drc)
            shutil.copy(src, drc)
            if imgtag != 'undefined':
                ans = dealSQL.getPhrase(s_type='appreciate.feedback.img',
                                        n=1).format(imgtag)
                userinfo['mode'] = 'dialog'
            else:
                ans = dealSQL.getPhrase(s_type='ask.feedback.img', n=1)
    elif userinfo['cnt'] > 6:
        ans = dealSQL.getPhrase(s_type='cntOver', n=20)
        userinfo['mode'] = 'ignore'
    elif '海未face' in text and status['in_reply_to_screen_name'] in {BOT_ID}:
        umipicDIR = '/Users/xxxx'
        filename = utiltools.getRandIMG(umipicDIR)
        ans = '...'
    elif 'timer' in text and status['in_reply_to_screen_name'] in {BOT_ID}:
        cmds = text.split(' ')
        try:
            timersec = cmds[1]
        except:
            timersec = 300
        try:
            tmptext = cmds[2]
        except:
            tmptext = ''
        setTime = datetime.utcnow() + timedelta(
            hours=0, minutes=0, seconds=int(timersec))
        dealSQL.saveTask(
            taskdict={
                'who': screen_name,
                'what': 'timer',
                'to_whom': screen_name,
                'when': setTime,
                'tmptext': tmptext
            })
        setTimeJ = setTime + timedelta(hours=9)
        ans = datetime.strftime(setTimeJ,
                                '%m月%d日 %H時%M分%S秒') + 'にタイマーをセットしました。'
    elif 'learn' in text and status['in_reply_to_screen_name'] in {BOT_ID}:
        userinfo['mode'] = 'learn.text'
        cmds = text.split(' ')
        tmplabel = cmds[1]
        userinfo['tmp'] = tmplabel
        userinfo['cnt'] = 0
        ans = '[Learningモード]\n' + tmplabel + 'として覚えさせるテキストをリプライしてください。\nendと入力するまでモードは続きます。'

    elif 'respon' in text and status['in_reply_to_screen_name'] in {BOT_ID}:
        if 'clear' in text:
            try:
                tmp['responseWord'] = {}
                ans = '全てのTL監視を停止しました。by @' + screen_name + '\n 監視ワードを追加するには半角スペース区切りで、\n response [監視ワード] [応答文]'
                screen_name = ''
            except:
                ans = '設定失敗。半角スペースで区切ってオーダーしてください。'
        else:
            try:
                cmds = text.split(' ')
                tgword = cmds[1]
                response = cmds[2]
                if len(tgword) > 3:
                    tmp['responseWord'][tgword] = response
                    ans = '「' + tgword + '」を監視して\n「' + response + '」と5分間反応します。by @' + screen_name + '\n 監視ワードを追加するには半角スペース区切りで、\n response [監視ワード] [応答文]'
                    setTime = datetime.utcnow() + timedelta(hours=0, minutes=5)
                    dealSQL.saveTask(
                        taskdict={
                            'who': screen_name,
                            'what': 'erase.tmp.responseWord',
                            'to_whom': screen_name,
                            'when': setTime,
                            'tmptext': tgword
                        })
                    screen_name = ''
                else:
                    ans = '監視ワードは4文字以上である必要があります。'
            except:
                ans = '設定失敗。半角スペースで区切ってオーダーしてください。'
    elif 'kusoripu' in text and status['in_reply_to_screen_name'] in {BOT_ID}:
        try:
            cmds = text.split(' ')
            tgname = cmds[1]
            user = twtr.get_user(screen_name=tgname)._json
            isFollowing = user['following']
            if isFollowing:
                screen_name = ''
                status_id = ''
                ans = getKusoripu(tg1=tgname)
            else:
                ans = 'そのユーザーはFF外です。クソリプは制限されます。'
        except:
            ans = 'クソリプ失敗。半角スペースで区切ってオーダーしてください。送信先はアットマークなしで記述してください。'

    elif 'su modsys' in text and status['in_reply_to_screen_name'] in {BOT_ID}:
        cmds = text.split(' ')
        tmp[cmds[2]] = cmds[3]
        ans = 'mod ' + cmds[2] + ' into ' + cmds[3]

    elif tmp['imitating'] != '' and 'default' in text:
        if twf.defaultProfile():
            ans = 'デフォルトに戻りました'
            tmp['imitating'] = ''
        else:
            ans = 'デフォルトに戻るのに失敗 @_apkX'

    elif 'imitat' in text and status['in_reply_to_screen_name'] in {BOT_ID}:
        try:
            cmds = text.split(' ')
            tgname = cmds[1].replace('@', '').replace('.', '')
            ans = 'imitateErr'
            print(cmds, tgname)
            # imitation中
            print(tmp['imitating'])
            ##TODO check whether ff or not
            if imitate(tgname):
                ans = tgname + 'さんのまねっこ5分間開始 defaultリプで元に戻ります。'
                mode = 'open'
                tmp['imitating'] = tgname
                # tmp['clocks']['imitationLimit'] = now + timedelta(hours=0, minutes=30)
                # tmp['clocks']['imitationTimer'] = now + timedelta(hours=0, minutes=5)
                setTime = now + timedelta(hours=0, minutes=5)
                dealSQL.saveTask(
                    taskdict={
                        'who': BOT_ID,
                        'what': 'imitate.default',
                        'to_whom': screen_name,
                        'when': setTime,
                        'tmptext': ''
                    })
            else:
                ans = tgname + 'さんのまねっこ失敗 FF外の場合はまねっこできません。'
        except Exception as e:
            print('[ERR][Main.imitation]')
            print(e)
            ans = 'まねっこがどこか失敗です...'

    elif 'しりとり' in text or userinfo['mode'] == 'srtr':
        userinfo['mode'] = 'srtr'
        ans = myGame.SRTR(text, screen_name)
        if '\END' in ans:
            ans = ans.replace('\END', '')
            userinfo['mode'] = 'dialog'
        if '\MISS' in ans:
            ans = ans.replace('\MISS', '')
            if userinfo['cnt'] > 3:
                ans = dealSQL.getPhrase(s_type='shiritori.end', n=1)
                userinfo['mode'] = 'dialog'
                userinfo['cnt'] = 0
        else:
            userinfo['cnt'] = 0

    elif 'おてもん' in text or userinfo['mode'] == 'mon':
        userinfo['mode'] = 'mon'
        userinfo['cnt'] = 0
        try:
            ans = GAME_MON.Main(text, screen_name, 'アルパカさん')
            if '\END' in ans:
                ans = ans.replace('\END', '')
                userinfo['mode'] = 'dialog'
            if '\MISS' in ans:
                ans = ans.replace('\MISS', '')
        except:
            ans = '工事中...'
            userinfo['mode'] = 'dialog'
    elif 'おみくじ' in text or '占い' in text:
        ans = dealSQL.getPhrase(s_type='おみくじ', n=20)
    elif 'おはよ' in text and status['in_reply_to_screen_name'] in set(
        [None, BOT_ID]):
        ans = dealSQL.getPhrase(s_type='goodmorning', n=1)
    elif 'おやすみ' in text and status['in_reply_to_screen_name'] in set(
        [None, BOT_ID]):
        ans = dealSQL.getPhrase(s_type='goodnight', n=1)
        userinfo['mode'] = 'sleeping'
    elif 'トレンドワード' in text:
        ans = '\n- '.join(['[現在のトレンドワード]'] + tmp['trendwordsList'][:10])
    elif deltasec > 600000:  #3日
        ans = dealSQL.getPhrase(s_type='longtimenosee', n=1)
    else:
        ans = trigramMC.dialog(text,
                               isRandMetaS=True,
                               isPrint=True,
                               isLearn=False,
                               n=5,
                               tryCnt=10,
                               needs=set(['名詞', '固有名詞'
                                          ])).replace('<人名>',
                                                      status['user']['name'])
        ans = charconv(ans, BOT_ID)

    # if isNewUser:
    # 	ans = dealSQL.getPhrase(s_type = 'welcomeNewUser', n = 20)

    if ans != '':
        tweetStatus, tmp = twf.send(ans,
                                    screen_name=screen_name,
                                    imgfile=filename,
                                    status_id=status_id,
                                    mode=mode,
                                    tmp=tmp)
    userinfo['time'] = now
    userinfo['cnt'] += 1
    dealSQL.saveUserInfo(userinfo)
    return tweetStatus, tmp
Esempio n. 2
0
def Main(status, bot_status):
	text = status['cleanText']
	status_id = status['id_str']
	screen_name = status['user']['screen_name']
	userinfo, isNewUser = dealSQL.getUserInfo(screen_name)
	now = datetime.utcnow()
	if isNewUser:
		welcomeTweet = 'はじめまして。よろしくお願いしますね。\n[新規ユーザー名検出...ユーザー情報登録完了]'
		tweetStatus, Altbot_status =  tweet(welcomeTweet, screen_name = screen_name, status_id = status_id, bot_status = bot_status)
	try:
		delta = now - datetime.strptime(userinfo['time'], '%Y-%m-%d %H:%M:%S.%f')
		deltasec = delta.total_seconds()
	except:
		deltasec = 50

	if deltasec > 1000:
		userinfo['cnt'] = 0
		userinfo['mode'] = 'dialog'
		if userinfo['mode'] == 'confirm.tag.img':
			src = userinfo['tmpFile']
			drc = ''.join(['/Users/xxxx'])
			if os.path.exists(drc) == False:
				os.mkdir(drc)
			shutil.copy(src, drc)

	if userinfo['mode'] == 'ignore':
		userinfo['cnt'] = 0
		userinfo['mode'] = 'dialog'
		Altbot_status = bot_status
		tweetStatus = False
	elif deltasec < 3:
		ans = dealSQL.getPhrase(s_type = 'tooFreq', n = 20)
		userinfo['mode'] = 'ignore'
		tweetStatus, Altbot_status =  tweet(ans, screen_name = screen_name, status_id = status_id, bot_status = bot_status)
	elif 'userinfo' in text:
		ans = str(userinfo)
		tweetStatus, Altbot_status =  tweet(ans, screen_name = screen_name, status_id = status_id, bot_status = bot_status)
	elif userinfo['cnt'] > 5:
		ans = dealSQL.getPhrase(s_type = 'cntOver', n = 20)
		userinfo['mode'] = 'ignore'
		tweetStatus, Altbot_status =  tweet(ans, screen_name = screen_name, status_id = status_id, bot_status = bot_status)
	elif 'media' in status['entities']:
		userinfo['cnt'] = 0
		fileID = now.strftime("%Y%m%d%H%M%S")
		if status['entities']['hashtags'] != []:
			imgtag = status['entities']['hashtags'][0]['text']
			try:
				filenames = saveMedias(status, ID = fileID, DIR = '/Users/xxxx' + imgtag)
				ans = ''.join(['画像を「', imgtag, '」として学習対象に登録しました。ご協力ありがとうございます。'])
			except Exception as e:
				print(e)
				ans = '画像を読み取れませんでした。'
			tweetStatus, Altbot_status =  tweet(ans, screen_name = screen_name, status_id = status_id, bot_status = bot_status)
		else:
			try:
				filenames = saveMedias(status, ID = fileID, DIR = '/Users/xxxx')
				filename = filenames[0]
				label, FACEflag, altfilename = NNimg.predictAns(filename  = filename, isShow = False, model = "/Users/xxxx')
				if FACEflag == False:
					ans = '顔認識に失敗しています。 精度は下がりますが...\n' + label + 'ですか?正しかったら、「正解」と言ってください。'
				else:
					ans = label + 'ですか?正しかったら、「正解」と言ってください。'
				tweetStatus, Altbot_status =  tweet(ans, screen_name = screen_name, status_id = status_id, imgfile = altfilename, bot_status = bot_status)
				drc = ''.join(['/Users/xxxx', label])
				if os.path.exists(drc) == False:
					os.mkdir(drc)
				shutil.copy(filename, drc)

				userinfo['mode'] = 'confirm.tag.img'
				print('/'.join([drc, filename.split('/')[-1]]))
				userinfo['tmpFile'] = '/'.join([drc, filename.split('/')[-1]])
			except Exception as e:
				print(e)
				ans = '画像を読み取れませんでした。'
				tweetStatus, Altbot_status = tweet(ans, screen_name = screen_name, status_id = status_id, bot_status = bot_status)
Esempio n. 3
0
def Main(status, tmp, mode = 'dm'):
	ans = ''
	IMGfile = ''
	tweetStatus = ''
	filename = ''
	text = status['cleanText']
	status_id = status['id_str']
	screen_name = status['user']['screen_name']
	userinfo, isNewUser = dealSQL.getUserInfo(screen_name)
	now = status['now']

	BOT_ID = tmp['BOT_ID']

	#時間計測(秒)
	try:
		try:
			delta = now - userinfo['time']
		except: #文字列対策
			print('convert str into datetime')
			delta = now - datetime.strptime(userinfo['time'], '%Y-%m-%d %H:%M:%S.%f')
		deltasec = delta.total_seconds()
	except Exception as e:
		print(e)
		deltasec = 50

	#返答タイムアウト処理
	if deltasec > 1000:
		userinfo['cnt'] = 0
		userinfo['mode'] = 'dialog'
		if userinfo['mode'] == 'confirm.tag.img':
			src = userinfo['tmpFile']
			drc = DIRIMGundefined
			if os.path.exists(drc) == False:
				os.mkdir(drc)
			shutil.copy(src, drc)

	# 応答
	if 'ping' in text:
		ans = ''.join(['Δsec : ', str(deltasec)])
	elif userinfo['mode'] == 'ignore':
		userinfo['cnt'] = 0
		userinfo['mode'] = 'dialog'
	elif deltasec < 3:
		ans = dealSQL.getPhrase(s_type = 'tooFreq', n = 20)
		userinfo['mode'] = 'ignore'
	elif 'userinfo' in text:
		ans = str(userinfo)
	elif userinfo['mode'] == 'learn.text':
		if status['in_reply_to_screen_name'] in {BOT_ID}:
			text = status['text'].replace('@'+BOT_ID, '')
			text = re.sub(r'(@[^\s ]+)', '{ID}', text)
			if 'end' in text:
				userinfo['mode'] = 'dialog'
				userinfo['tmp'] = ''
				ans = 'learningモードをクローズしました。この結果は開発にフィードバックされます。ご協力感謝します。'
			else:
				labelstatus = userinfo['tmp']
				userinfo['cnt'] = 0
				dealSQL.savePhrase(phrase = text, author = screen_name, status = labelstatus, s_type = 'UserLearn')
				ans = '[learning]saved!!... 続けて覚えさせるテキストをリプライしてください。\nendと入力するまでモードは続きます。'
		else:
			ans = 'learningモードの途中です。覚えさせるテキストをリプライしてください。\nendと入力するまでモードは続きます。'
	elif userinfo['mode'] == 'sleeping' and deltasec > 3600:
		ans = dealSQL.getPhrase(s_type = 'goodmorning', n = 1)
		ans += '\n' + dealSQL.getPhrase(s_type = 'sleep.span', n = 1).format(utiltools.sec2HMSstr(deltasec))
		userinfo['mode'] = 'dialog'

	elif 'media' in status['entities'] and status['in_reply_to_screen_name'] in {BOT_ID}:
		userinfo['cnt'] = 0
		fileID = now.strftime("%Y%m%d%H%M%S")
		if status['entities']['hashtags'] != []:
			imgtag = status['entities']['hashtags'][0]['text']
			try:
				filenames = utiltools.saveMedias(status, ID = fileID, DIR = '/'.join([DIRIMGfeedback, imgtag]))
				ans = dealSQL.getPhrase(s_type = 'appreciate.giveme.img', n = 1).format(imgtag)
			except Exception as e:
				print(e)
				ans = dealSQL.getPhrase(s_type = 'err.get.img', n = 1)
		else:
			try:
				filenames = utiltools.saveMedias(status, ID = fileID, DIR = DIRIMGtmp)
				filename = filenames[0]
				label, FACEflag, IMGfile = NNimg.predictAns(filename  = filename, isShow = False, model = modelNNimg, workDIR = '')
				if FACEflag == False:
					ans = dealSQL.getPhrase(s_type = 'confirm.detect.img.noface', n = 1).format(label)
				else:
					ans = dealSQL.getPhrase(s_type = 'confirm.detect.img', n = 1).format(label)

				drc = '/'.join([DIRIMGfeedback, label])
				if os.path.exists(drc) == False:
					os.mkdir(drc)
				shutil.copy(filename, drc)

				userinfo['mode'] = 'confirm.tag.img'
				print('/'.join([drc, filename.split('/')[-1]]))
				userinfo['tmpFile'] = '/'.join([drc, filename.split('/')[-1]])
				filename = IMGfile
			except Exception as e:
				print(e)
				ans = dealSQL.getPhrase(s_type = 'err.get.img', n = 1)

	elif userinfo['mode'] == 'confirm.tag.img':
		userinfo['cnt'] = 0
		if status['entities']['hashtags'] != []:
			imgtag = status['entities']['hashtags'][0]['text']
			isMoveDIR = True
		elif not 'ない' in text and ('正解' in text or '正し' in text):
			ans = dealSQL.getPhrase(s_type = 'success.detect.img', n = 1)
			userinfo['mode'] = 'dialog'
			isMoveDIR = False
		else:
			try:
				imgtag = TFIDF.calcKWs(text, length = 1, needs = {'固有名詞', '名詞'})[0][0]
			except Exception as e:
				print(e)
				imgtag = 'undefined'
			isMoveDIR = True
		if isMoveDIR:
			src = userinfo['tmpFile']
			drc = '/'.join([DIRIMGfeedback, imgtag])
			if os.path.exists(drc) == False:
				os.mkdir(drc)
			shutil.copy(src, drc)
			if imgtag != 'undefined':
				ans = dealSQL.getPhrase(s_type = 'appreciate.feedback.img', n = 1).format(imgtag)
				userinfo['mode'] = 'dialog'
			else:
				ans = dealSQL.getPhrase(s_type = 'ask.feedback.img', n = 1)
	elif userinfo['cnt'] > 6:
		ans = dealSQL.getPhrase(s_type = 'cntOver', n = 20)
		userinfo['mode'] = 'ignore'
	elif '海未face' in text and status['in_reply_to_screen_name'] in {BOT_ID}:
		umipicDIR = '/Users/masaMikam/Dropbox/Project/IAs/Data/imgs/海未'
		filename = utiltools.getRandIMG(umipicDIR)
		ans = '...'
	elif 'timer' in text and status['in_reply_to_screen_name'] in {BOT_ID}:
		cmds = text.split(' ')
		try:
			timersec = cmds[1]
		except:
			timersec = 300
		try:
			tmptext = cmds[2]
		except:
			tmptext = ''
		setTime = datetime.utcnow() + timedelta(hours=0, minutes=0, seconds = int(timersec))
		dealSQL.saveTask(taskdict = {'who':screen_name, 'what': 'timer', 'to_whom': screen_name, 'when':setTime, 'tmptext': tmptext})
		setTimeJ = setTime + timedelta(hours=9)
		ans = datetime.strftime(setTimeJ, '%m月%d日 %H時%M分%S秒') + 'にタイマーをセットしました。'
	elif 'learn' in text and status['in_reply_to_screen_name'] in {BOT_ID}:
		userinfo['mode'] = 'learn.text'
		cmds = text.split(' ')
		tmplabel = cmds[1]
		userinfo['tmp'] = tmplabel
		userinfo['cnt'] = 0
		ans = '[Learningモード]\n' + tmplabel+ 'として覚えさせるテキストをリプライしてください。\nendと入力するまでモードは続きます。'

	elif 'respon' in text and status['in_reply_to_screen_name'] in {BOT_ID}:
		if 'clear' in text:
			try:
				tmp['responseWord'] = {}
				ans = '全てのTL監視を停止しました。by @' + screen_name + '\n 監視ワードを追加するには半角スペース区切りで、\n response [監視ワード] [応答文]'
				screen_name = ''
			except:
				ans = '設定失敗。半角スペースで区切ってオーダーしてください。'
		else:
			try:
				cmds = text.split(' ')
				tgword = cmds[1]
				response = cmds[2]
				if len(tgword) > 3:
					tmp['responseWord'][tgword] = response
					ans = '「' + tgword + '」を監視して\n「' + response + '」と5分間反応します。by @' + screen_name + '\n 監視ワードを追加するには半角スペース区切りで、\n response [監視ワード] [応答文]'
					setTime = datetime.utcnow() + timedelta(hours=0, minutes=5)
					dealSQL.saveTask(taskdict = {'who':screen_name, 'what': 'erase.tmp.responseWord', 'to_whom': screen_name, 'when':setTime, 'tmptext': tgword})
					screen_name = ''
				else:
					ans = '監視ワードは4文字以上である必要があります。'
			except:
				ans = '設定失敗。半角スペースで区切ってオーダーしてください。'
	elif 'kusoripu' in text and status['in_reply_to_screen_name'] in {BOT_ID}:
		try:
			cmds = text.split(' ')
			tgname = cmds[1]
			user = twtr.get_user(screen_name = tgname)._json
			isFollowing = user['following']
			if isFollowing:
				screen_name = ''
				status_id = ''
				ans = getKusoripu(tg1 = tgname)
			else:
				ans = 'そのユーザーはFF外です。クソリプは制限されます。'
		except:
			ans = 'クソリプ失敗。半角スペースで区切ってオーダーしてください。送信先はアットマークなしで記述してください。'

	elif 'su modsys'  in text and status['in_reply_to_screen_name'] in {BOT_ID}:
		cmds = text.split(' ')
		tmp[cmds[2]] = cmds[3]
		ans = 'mod '+ cmds[2] + ' into ' + cmds[3]

	elif tmp['imitating'] != '' and 'default' in text:
		if twf.defaultProfile():
			ans = 'デフォルトに戻りました'
			tmp['imitating'] = ''
		else:
			ans = 'デフォルトに戻るのに失敗 @_apkX'

	elif 'imitat' in text and status['in_reply_to_screen_name'] in {BOT_ID}:
		try:
			cmds = text.split(' ')
			tgname = cmds[1].replace('@', '').replace('.', '')
			ans = 'imitateErr'
			print(cmds, tgname)
			# imitation中
			print(tmp['imitating'])
			##TODO check whether ff or not
			if imitate(tgname):
				ans = tgname + 'さんのまねっこ5分間開始 defaultリプで元に戻ります。'
				mode = 'open'
				tmp['imitating'] = tgname
				# tmp['clocks']['imitationLimit'] = now + timedelta(hours=0, minutes=30)
				# tmp['clocks']['imitationTimer'] = now + timedelta(hours=0, minutes=5)
				setTime = now + timedelta(hours=0, minutes=5)
				dealSQL.saveTask(taskdict = {'who':BOT_ID, 'what': 'imitate.default', 'to_whom':screen_name, 'when':setTime, 'tmptext': ''})
			else:
				ans = tgname + 'さんのまねっこ失敗 FF外の場合はまねっこできません。'
		except Exception as e:
			print('[ERR][Main.imitation]')
			print(e)
			ans = 'まねっこがどこか失敗です...'

	elif 'しりとり' in text or userinfo['mode'] == 'srtr':
		userinfo['mode'] = 'srtr'
		ans = myGame.SRTR(text, screen_name)
		if '\END' in ans:
			ans = ans.replace('\END', '')
			userinfo['mode'] = 'dialog'
		if '\MISS' in ans:
			ans = ans.replace('\MISS', '')
			if userinfo['cnt'] > 3:
				ans = dealSQL.getPhrase(s_type = 'shiritori.end', n = 1)
				userinfo['mode'] = 'dialog'
				userinfo['cnt'] = 0
		else:
			userinfo['cnt'] = 0

	elif 'おてもん' in text or userinfo['mode'] == 'mon':
		userinfo['mode'] = 'mon'
		userinfo['cnt'] = 0
		try:
			ans = GAME_MON.Main(text, screen_name, 'アルパカさん')
			if '\END' in ans:
				ans = ans.replace('\END', '')
				userinfo['mode'] = 'dialog'
			if '\MISS' in ans:
				ans = ans.replace('\MISS', '')
		except:
			ans = '工事中...'
			userinfo['mode'] = 'dialog'
	elif 'おみくじ' in text or '占い' in text:
		ans = dealSQL.getPhrase(s_type = 'おみくじ', n = 20)
	elif 'おはよ' in text and status['in_reply_to_screen_name'] in set([None, BOT_ID]):
		ans = dealSQL.getPhrase(s_type = 'goodmorning', n = 1)
	elif 'おやすみ' in text and status['in_reply_to_screen_name'] in set([None, BOT_ID]):
		ans = dealSQL.getPhrase(s_type = 'goodnight', n = 1)
		userinfo['mode'] = 'sleeping'
	elif 'トレンドワード' in text:
		ans = '\n- '.join(['[現在のトレンドワード]']+tmp['trendwordsList'][:10])
	elif deltasec > 600000: #3日
		ans = dealSQL.getPhrase(s_type = 'longtimenosee', n = 1)
	else:
		ans = trigramMC.dialog(text, isRandMetaS = True, isPrint = True, isLearn = False, n =5, tryCnt = 10, needs = set(['名詞', '固有名詞'])).replace('<人名>', status['user']['name'])
		ans = charconv(ans, BOT_ID)

	# if isNewUser:
	# 	ans = dealSQL.getPhrase(s_type = 'welcomeNewUser', n = 20)

	if ans != '':
		tweetStatus, tmp = twf.send(ans, screen_name = screen_name, imgfile = filename, status_id = status_id, mode = mode, tmp = tmp)
	userinfo['time'] = now
	userinfo['cnt'] += 1
	dealSQL.saveUserInfo(userinfo)
	return tweetStatus, tmp
Esempio n. 4
0
def Main(status, bot_status):
    text = status["cleanText"]
    status_id = status["id_str"]
    screen_name = status["user"]["screen_name"]
    userinfo, isNewUser = dealSQL.getUserInfo(screen_name)
    now = datetime.utcnow()
    if isNewUser:
        welcomeTweet = "はじめまして。よろしくお願いしますね。\n[新規ユーザー名検出...ユーザー情報登録完了]"
        tweetStatus, Altbot_status = tweet(
            welcomeTweet, screen_name=screen_name, status_id=status_id, bot_status=bot_status
        )
    try:
        delta = now - datetime.strptime(userinfo["time"], "%Y-%m-%d %H:%M:%S.%f")
        deltasec = delta.total_seconds()
    except:
        deltasec = 50

    if deltasec > 1000:
        userinfo["cnt"] = 0
        userinfo["mode"] = "dialog"
        if userinfo["mode"] == "confirm.tag.img":
            src = userinfo["tmpFile"]
            drc = "".join(["/Users/masaMikam/Dropbox/Project/umiA/Data/imgsfeedback/undefined"])
            if os.path.exists(drc) == False:
                os.mkdir(drc)
            shutil.copy(src, drc)

    if userinfo["mode"] == "ignore":
        userinfo["cnt"] = 0
        userinfo["mode"] = "dialog"
        Altbot_status = bot_status
        tweetStatus = False
    elif deltasec < 3:
        ans = dealSQL.getPhrase(s_type="tooFreq", n=20)
        userinfo["mode"] = "ignore"
        tweetStatus, Altbot_status = tweet(ans, screen_name=screen_name, status_id=status_id, bot_status=bot_status)
    elif "userinfo" in text:
        ans = str(userinfo)
        tweetStatus, Altbot_status = tweet(ans, screen_name=screen_name, status_id=status_id, bot_status=bot_status)
    elif userinfo["cnt"] > 5:
        ans = dealSQL.getPhrase(s_type="cntOver", n=20)
        userinfo["mode"] = "ignore"
        tweetStatus, Altbot_status = tweet(ans, screen_name=screen_name, status_id=status_id, bot_status=bot_status)
    elif "media" in status["entities"]:
        userinfo["cnt"] = 0
        fileID = now.strftime("%Y%m%d%H%M%S")
        if status["entities"]["hashtags"] != []:
            imgtag = status["entities"]["hashtags"][0]["text"]
            try:
                filenames = saveMedias(
                    status, ID=fileID, DIR="/Users/masaMikam/Dropbox/Project/umiA/Data/imgsfeedback/" + imgtag
                )
                ans = "".join(["画像を「", imgtag, "」として学習対象に登録しました。ご協力ありがとうございます。"])
            except Exception as e:
                print(e)
                ans = "画像を読み取れませんでした。"
            tweetStatus, Altbot_status = tweet(ans, screen_name=screen_name, status_id=status_id, bot_status=bot_status)
        else:
            try:
                filenames = saveMedias(status, ID=fileID, DIR="/Users/masaMikam/Dropbox/Project/umiA/Data/twimgs")
                filename = filenames[0]
                label, FACEflag, altfilename = NNimg.predictAns(
                    filename=filename,
                    isShow=False,
                    model="/Users/masaMikam/Dropbox/Project/umiA/Data/ML_Brain/DNN_skf",
                    workDIR="",
                )
                if FACEflag == False:
                    ans = "顔認識に失敗しています。 精度は下がりますが...\n" + label + "ですか?正しかったら、「正解」と言ってください。"
                else:
                    ans = label + "ですか?正しかったら、「正解」と言ってください。"
                tweetStatus, Altbot_status = tweet(
                    ans, screen_name=screen_name, status_id=status_id, imgfile=altfilename, bot_status=bot_status
                )
                drc = "".join(["/Users/masaMikam/Dropbox/Project/umiA/Data/imgsfeedback/", label])
                if os.path.exists(drc) == False:
                    os.mkdir(drc)
                shutil.copy(filename, drc)

                userinfo["mode"] = "confirm.tag.img"
                print("/".join([drc, filename.split("/")[-1]]))
                userinfo["tmpFile"] = "/".join([drc, filename.split("/")[-1]])
            except Exception as e:
                print(e)
                ans = "画像を読み取れませんでした。"
                tweetStatus, Altbot_status = tweet(
                    ans, screen_name=screen_name, status_id=status_id, bot_status=bot_status
                )
    elif userinfo["mode"] == "confirm.tag.img":
        userinfo["cnt"] = 0
        if status["entities"]["hashtags"] != []:
            imgtag = status["entities"]["hashtags"][0]["text"]
            isMoveDIR = True
        elif not "ない" in text and ("正解" in text or "正し" in text):
            ans = "やりました!正解ですね。"
            userinfo["mode"] = "dialog"
            isMoveDIR = False
        else:
            try:
                imgtag = TFIDF.calcKWs(text, length=1, needs=set(["固有名詞", "名詞"]))[0][0]
            except Exception as e:
                print(e)
                imgtag = "undefined"
            isMoveDIR = True
        if isMoveDIR:
            src = userinfo["tmpFile"]
            drc = "".join(["/Users/masaMikam/Dropbox/Project/umiA/Data/imgsfeedback/", imgtag])
            if os.path.exists(drc) == False:
                os.mkdir(drc)
            shutil.copy(src, drc)
            if imgtag != "undefined":
                ans = "".join(["...成る程...「", imgtag, "」なのですね。ありがとうございます。\n(フィードバックしました。学習反映にまでは時間がかかります。)"])
                userinfo["mode"] = "dialog"
            else:
                ans = "...一体、これは何なのですか?(好奇心)"
                ##送信
        tweetStatus, Altbot_status = tweet(ans, screen_name=screen_name, status_id=status_id, bot_status=bot_status)
    elif "しりとり" in text or userinfo["mode"] == "srtr":
        userinfo["mode"] = "srtr"
        ans = myGame.SRTR(text, screen_name)
        if "\END" in ans:
            ans = ans.replace("\END", "")
            userinfo["mode"] = "dialog"
        if "\MISS" in ans:
            ans = ans.replace("\MISS", "")
            if userinfo["cnt"] > 3:
                ans = "しりとりは終わりにしましょう"
                userinfo["mode"] = "dialog"
                userinfo["cnt"] = 0
        else:
            userinfo["cnt"] = 0
        tweetStatus, Altbot_status = tweet(ans, screen_name=screen_name, status_id=status_id, bot_status=bot_status)
    elif "おみくじ" in text or "占い" in text:
        ans = dealSQL.getPhrase(s_type="おみくじ", n=20)
        tweetStatus, Altbot_status = tweet(ans, screen_name=screen_name, status_id=status_id, bot_status=bot_status)
    elif deltasec > 259200:  # 3日
        ans = "ご無沙汰しております...おかえりなさい。"
        tweetStatus, Altbot_status = tweet(ans, screen_name=screen_name, status_id=status_id, bot_status=bot_status)
    else:
        ans = trigramMC2.dialog(
            text, isRandMetaS=True, isPrint=True, isLearn=False, n=5, tryCnt=10, needs=set(["名詞", "固有名詞", "動詞", "形容詞"])
        )
        ans = ans.replace("<人名>", status["user"]["name"])
        tweetStatus, Altbot_status = tweet(ans, screen_name=screen_name, status_id=status_id, bot_status=bot_status)

    userinfo["time"] = now
    userinfo["cnt"] += 1
    dealSQL.saveUserInfo(userinfo)
    return tweetStatus, Altbot_status