示例#1
0
文件: Main.py 项目: u3paka/umi_bot
def monitorTL(status, tmp):
    text = status['cleanText']
    screen_name = status['user']['screen_name']
    if status['user']['screen_name'] == 'eewbot':
        eew, tmp = utiltools.eew(csv=text, standard=0, tmp=tmp)
        if eew != '':
            ans = eew + '\n(通知実験中: データは本物です。)'
    elif tmp['stats']["tweet_cnt_hour"] > 100:
        ans = ''
    elif status['entities']['urls'] != []:
        ans = ''
    elif status['user']['screen_name'] in tmp['BOTset']:
        ans = ''
    elif 'ぬるぽ' in text:
        ans = dealSQL.getPhrase(s_type='ぬるぽ', n=1)
    elif 'なんでも' in text:
        ans = dealSQL.getPhrase(s_type='なんでもって', n=1)
        #テスト機能
    elif iscalledBOT(text):
        ans = dealSQL.getPhrase(s_type='よびだし', n=1)
    elif 'ヌベヂョン' in text:
        ans = getKusoripu(tg1=status['user']['screen_name'])
        screen_name = ''
    elif text in set(tmp['tweetPool']['pool']):
        ans = ''.join(['\n', text, '(パクツイ便乗)'])
        if len(ans) > 140:
            ans = text
    elif 'respon' in text:
        return False
    else:
        respSP = utiltools.crowlDic(text=text, dic=tmp["responseWord"])
        if respSP != '':
            ans = respSP
        else:
            text = utiltools.cleanText2(text)
            mas = [w for w in NLP.MA.getMeCabList(text) if w[0] != '。']
            ans = Haiku.Haiku(mas)
    #ツイート
    if ans != '':
        try:
            return twf.tweet(ans,
                             screen_name,
                             status_id=status['id_str'],
                             imgfile='',
                             tmp=tmp)[0]
        except Exception as e:
            print(e)
            return False
    else:
        return False
def loop(task):
	tmp = utiltools.getJSON()
	print(task)
	taskid = task['id']
	todo = task['what']
	screen_name = task['to_whom']
	filename = task['tmpfile']
	status_id = task['tmpid']
	setTime = task['when']
	setTimeJ = setTime + timedelta(hours=9)
	if todo == 'timer':
		ans = datetime.strftime(setTimeJ, '%m月%d日 %H時%M分%S秒') + 'です。タイマーの時刻を経過しました。\n' + task['tmptext']
	elif todo == 'teiki.trendword':
		trendwords = twf.getTrendwords()
		trendword = np.random.choice(trendwords)
		ans = dealSQL.getPhrase(s_type = 'trendword', n = 2).format(trendword)
		post30min = setTime + timedelta(hours=0, minutes=30)
		dealSQL.saveTask(taskdict = {'who':BOT_ID, 'what': todo, 'to_whom': '', 'when':post30min})
		tmp['trendwordsList'] = trendwords
	elif todo == 'imitate.default':
		if twf.defaultProfile():
			ans = 'デフォルトに戻りました'
			screen_name = ''
			tmp['imitating'] = ''
		else:
			ans = 'デフォルトに戻るのに失敗 @_apkX'
	if ans != '':
		twf.send(ans, screen_name = screen_name, imgfile = filename, status_id = status_id, mode = 'tweet')
	dealSQL.updateTask(taskid = taskid, taskdict = {'status': 'end'})
	utiltools.saveJSON(tmp)
	return True
示例#3
0
文件: Main.py 项目: masaMikam/Umi_bot
def getKusoripu(tg1):
	ans = dealSQL.getPhrase(status = 'kusoripu', n = 20)
	if '{ID}' in ans:
		ans = ans.format(ID= ''.join(['@', tg1]))
	else:
		ans = ''.join(['@', tg1, ans])
	return ans
示例#4
0
文件: Main.py 项目: u3paka/umi_bot
def getKusoripu(tg1):
    ans = dealSQL.getPhrase(status='kusoripu', n=20)
    if '{ID}' in ans:
        ans = ans.format(ID=''.join(['@', tg1]))
    else:
        ans = ''.join(['@', tg1, ans])
    return ans
def loop(task):
    tmp = utiltools.getJSON()
    print(task)
    taskid = task["id"]
    todo = task["what"]
    screen_name = task["to_whom"]
    filename = task["tmpfile"]
    status_id = task["tmpid"]
    setTime = task["when"]
    setTimeJ = setTime + timedelta(hours=9)
    if todo == "timer":
        ans = datetime.strftime(setTimeJ, "%m月%d日 %H時%M分%S秒") + "です。タイマーの時刻を経過しました。\n" + task["tmptext"]
    elif todo == "teiki.trendword":
        trendwords = twf.getTrendwords()
        trendword = np.random.choice(trendwords)
        ans = dealSQL.getPhrase(s_type="trendword", n=2).format(trendword)
        post30min = setTime + timedelta(hours=0, minutes=30)
        dealSQL.saveTask(taskdict={"who": BOT_ID, "what": todo, "to_whom": "", "when": post30min})
        tmp["trendwordsList"] = trendwords
    elif todo == "imitate.default":
        if twf.defaultProfile():
            ans = "デフォルトに戻りました"
            screen_name = ""
            tmp["imitating"] = ""
        else:
            ans = "デフォルトに戻るのに失敗 @_apkX"
    if ans != "":
        twf.send(ans, screen_name=screen_name, imgfile=filename, status_id=status_id, mode="tweet")
    dealSQL.updateTask(taskid=taskid, taskdict={"status": "end"})
    utiltools.saveJSON(tmp)
    return True
示例#6
0
文件: Main.py 项目: masaMikam/Umi_bot
def monitorTL(status, tmp):
	text = status['cleanText']
	screen_name = status['user']['screen_name']
	if status['user']['screen_name'] == 'eewbot':
		eew, tmp = utiltools.eew(csv = text, standard = 0, tmp = tmp)
		if eew != '':
			ans = eew + '\n(通知実験中: データは本物です。)'
	elif tmp['stats']["tweet_cnt_hour"] > 100:
		ans = ''
	elif status['entities']['urls'] != []:
		ans = ''
	elif status['user']['screen_name'] in tmp['BOTset']:
		ans = ''
	elif 'ぬるぽ' in text:
		ans = dealSQL.getPhrase(s_type = 'ぬるぽ', n = 1)
	elif 'なんでも' in text:
		ans = dealSQL.getPhrase(s_type = 'なんでもって', n = 1)
		#テスト機能
	elif iscalledBOT(text):
		ans = dealSQL.getPhrase(s_type = 'よびだし', n = 1)
	elif 'ヌベヂョン' in text:
		ans = getKusoripu(tg1 = status['user']['screen_name'])
		screen_name = ''
	elif text in set(tmp['tweetPool']['pool']):
		ans = ''.join(['\n', text,'(パクツイ便乗)'])
		if len(ans) > 140:
			ans = text
	elif 'respon' in text:
		return False
	else:
		respSP = utiltools.crowlDic(text = text, dic = tmp["responseWord"])
		if respSP != '':
			ans = respSP
		else:
			text = utiltools.cleanText2(text)
			mas = [w for w in NLP.MA.getMeCabList(text) if w[0] != '。']
			ans = Haiku.Haiku(mas)
	#ツイート
	if ans != '':
		try:
			return twf.tweet(ans, screen_name, status_id = status['id_str'], imgfile = '', tmp = tmp)[0]
		except Exception as e:
			print(e)
			return False
	else:
		return False
示例#7
0
def loopMain(task):
	ans = ''
	tmp = utiltools.getJSON()
	print(task)
	taskid = task['id']
	todo = task['what']
	screen_name = task['to_whom']
	filename = task['tmpfile']
	status_id = task['tmpid']
	setTime = task['when']
	setTimeJ = setTime + timedelta(hours=9)
	trycnt = 0
	if todo == 'timer':
		ans = datetime.strftime(setTimeJ, '%m月%d日 %H時%M分%S秒') + 'です。タイマーの時刻を経過しました。\n' + task['tmptext']
	elif todo == 'teiki.trendword':
		trendwords = twf.getTrendwords()
		trendword = np.random.choice(trendwords)
		ans = dealSQL.getPhrase(s_type = 'trendword', n = 2).format(trendword)
		post30min = setTime + timedelta(hours=0, minutes=30)
		dealSQL.saveTask(taskdict = {'who':BOT_ID, 'what': todo, 'to_whom': '', 'when':post30min})
		tmp['trendwordsList'] = trendwords
	elif todo == 'imitate.default':
		if twf.defaultProfile():
			ans = 'デフォルトに戻りました'
			screen_name = ''
			tmp['imitating'] = ''
		else:
			ans = 'デフォルトに戻るのに失敗 サポートにお問い合わせください。'
	elif todo == 'erase.tmp.responseWord':
		try:
			del tmp['responseWord'][task['tmptext']]
		except:
			print('del err')
	elif todo == 'erase.tmp.stats.tweet_cnt_hour':
		tmp['stats']['tweet_cnt_hour'] = 0
		post1hour = setTime + timedelta(hours=1)
		dealSQL.saveTask(taskdict = {'who':BOT_ID, 'what': todo, 'to_whom': '', 'when':post1hour})

	elif todo == 'tweet':
		ans = task['tmptext']
		trycnt = task['tmpcnt']

	if ans != '':
		twf.send(ans, screen_name = screen_name, imgfile = filename, status_id = status_id, mode = 'tweet', tmp = tmp, trycnt = trycnt)
	dealSQL.updateTask(taskid = taskid, taskdict = {'status': 'end'})
	utiltools.saveJSON(tmp)
	return True
示例#8
0
def loopMain(task):
	ans = ''
	tmp = utiltools.getJSON()
	print(task)
	taskid = task['id']
	todo = task['what']
	screen_name = task['to_whom']
	filename = task['tmpfile']
	status_id = task['tmpid']
	setTime = task['when']
	setTimeJ = setTime + timedelta(hours=9)
	trycnt = 0
	if todo == 'timer':
		ans = datetime.strftime(setTimeJ, '%m月%d日 %H時%M分%S秒') + 'です。タイマーの時刻を経過しました。\n' + task['tmptext']
	elif todo == 'teiki.trendword':
		trendwords = twf.getTrendwords()
		trendword = np.random.choice(trendwords)
		ans = dealSQL.getPhrase(s_type = 'trendword', n = 2).format(trendword)
		post30min = setTime + timedelta(hours=0, minutes=30)
		dealSQL.saveTask(taskdict = {'who':BOT_ID, 'what': todo, 'to_whom': '', 'when':post30min})
		tmp['trendwordsList'] = trendwords
	elif todo == 'imitate.default':
		if twf.defaultProfile():
			ans = 'デフォルトに戻りました'
			screen_name = ''
			tmp['imitating'] = ''
		else:
			ans = 'デフォルトに戻るのに失敗 サポートにお問い合わせください。'
	elif todo == 'erase.tmp.responseWord':
		try:
			del tmp['responseWord'][task['tmptext']]
		except:
			print('del err')
	elif todo == 'erase.tmp.stats.tweet_cnt_hour':
		tmp['stats']['tweet_cnt_hour'] = 0
		post1hour = setTime + timedelta(hours=1)
		dealSQL.saveTask(taskdict = {'who':BOT_ID, 'what': todo, 'to_whom': '', 'when':post1hour})

	elif todo == 'tweet':
		ans = task['tmptext']
		trycnt = task['tmpcnt']

	if ans != '':
		twf.send(ans, screen_name = screen_name, imgfile = filename, status_id = status_id, mode = 'tweet', tmp = tmp, trycnt = trycnt)
	dealSQL.updateTask(taskid = taskid, taskdict = {'status': 'end'})
	utiltools.saveJSON(tmp)
	return True
示例#9
0
def dialog(s,
           isRandMetaS=True,
           isPrint=True,
           isLearn=False,
           n=5,
           tryCnt=10,
           needs=set(['名詞', '固有名詞', '動詞', '形容詞'])):
    keys = TFIDF.getKWs(s,
                        threshold=50,
                        n=n,
                        length=1,
                        isPrint=isPrint,
                        needs=needs,
                        RandNum=5)
    isAssociate = False
    if keys[0] == '':
        try:
            return dealSQL.getPhrase(status='nod', n=20)
        except:
            return '...そうなんですね'
    if isAssociate:
        BA = associateAns(keys[0])
    else:
        # wordset = getSimilarWords(w = keys[0], cnt = tryCnt)
        BA = formTrigram(word=keys[0], isRandMetaS=isRandMetaS)
        # ansSims = {ans: TFIDF.cosSimilarity(ans, s) for ans in ANSs}
        # BA = sorted(ansSims.items(), reverse = True, key=lambda x:x[1])[0]

    if isLearn:
        TrigramCore(s, isLearn=True, isDebug=False)
    if isPrint:
        print('=> 自動生成した応答文は以下のとおりです。')
        print(BA)
    randnum = np.random.randint(10)
    BA = BA.replace('<接尾>', 'さん').replace('<地域>',
                                          'アキバ').replace('<数>', str(randnum))
    return BA
示例#10
0
def dialog(s, isRandMetaS = True, isPrint = True, isLearn = False, n =5, tryCnt = 10, needs = set(['名詞', '固有名詞', '動詞', '形容詞'])):
  keys = TFIDF.getKWs(s, threshold = 50, n = n, length = 1, isPrint = isPrint, needs = needs, RandNum = 5)
  isAssociate = False
  if keys[0] == '':
    try:
      return dealSQL.getPhrase(status = 'nod', n = 20)
    except:
      return '...そうなんですね'
  if isAssociate:
    BA = associateAns(keys[0])
  else:
    # wordset = getSimilarWords(w = keys[0], cnt = tryCnt)
    BA = formTrigram(word = keys[0], isRandMetaS = isRandMetaS)
    # ansSims = {ans: TFIDF.cosSimilarity(ans, s) for ans in ANSs}
    # BA = sorted(ansSims.items(), reverse = True, key=lambda x:x[1])[0]

  if isLearn:
    TrigramCore(s, isLearn = True, isDebug = False)
  if isPrint:
    print('=> 自動生成した応答文は以下のとおりです。')
    print(BA)
  randnum = np.random.randint(10)
  BA = BA.replace('<接尾>', 'さん').replace('<地域>', 'アキバ').replace('<数>', str(randnum))
  return BA
示例#11
0
文件: Main.py 项目: u3paka/umi_bot
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
示例#12
0
文件: Main.py 项目: masaMikam/Umi_bot
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
示例#13
0
文件: umiA.py 项目: u3paka/umi_bot
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)
示例#14
0
文件: umiA.py 项目: u3paka/umi_bot
		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

示例#15
0
文件: umiA.py 项目: masaMikam/Umi_bot
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