3年前くらい前にコピペで作成したものを掘り起こして遊びたいと思ったものの
discordbot.py
1import discord 2import os, re, json, random 3from janome.tokenizer import Tokenizer 4 5 6 7 8dict_file = "chatbot-data.json" 9dic = {} 10tokenizer = Tokenizer() 11 12if os.path.exists(dict_file): 13 dic = json.load(open(dict_file, "r")) 14 15def register_dic(words): 16 global dic 17 if len(words) == 0: return 18 tmp = ["@"] 19 for i in words: 20 word = i.surface 21 if word == "" or word == "\r\n" or word == "\n": continue 22 tmp.append(word) 23 if len(tmp) < 3: continue 24 if len(tmp) > 3: tmp = tmp[1:] 25 set_word3(dic, tmp) 26 if word == "。" or word == "?": 27 tmp = ["@"] 28 continue 29 #辞書更新毎にファイル保存 30 f = open(dict_file, "w", encoding="utf-8") 31 json.dump(dic, f) 32 33def set_word3(dic, s3): 34 w1, w2, w3 = s3 35 if not w1 in dic: dic[w1] = {} 36 if not w2 in dic[w1]: dic[w1][w2] = {} 37 if not w3 in dic[w1][w2]: dic[w1][w2][w3] = 0 38 dic[w1][w2][w3] += 1 39 40 41def make_sentence(head): 42 if not head in dic: return "" 43 ret = [] 44 if head != "@": ret.append(head) 45 top = dic[head] 46 w1 = word_choice(top) 47 w2 = word_choice(top[w1]) 48 ret.append(w1) 49 ret.append(w2) 50 while True: 51 if w1 in dic and w2 in dic[w1]: 52 w3 = word_choice(dic[w1][w2]) 53 else: 54 w3 = "" 55 ret.append(w3) 56 if w3 == "。" or w3 == "?" or w3 == "": break 57 w1, w2 = w2, w3 58 return "".join(ret) 59 60 61def word_choice(sel): 62 keys = sel.keys() 63 return random.choice(list(keys)) 64 65 66 67# botに返答させる 68def make_reply(text): 69 # まず単語を学習する 70 if text[-1] != "。": text += "。" 71 words = tokenizer.tokenize(text) 72 register_dic(words) 73 # 辞書に単語があれば、そこから話す 74 for w in words: 75 face = w.surface 76 ps = w.part_of_speech.split(',')[0] 77 if ps == "感動詞": 78 return face + "。" 79 if ps == "名詞" or ps == "形容詞": 80 if face in dic: return make_sentence(face) 81 return make_sentence("@") 82 83#ここからメッセージ取得&返信 84 85# 86# 87#以下、discord処理 88# 89# 90 91client = discord.Client() 92 93 94 95@client.event 96async def on_ready(): 97 print('Logged in as') 98 print(client.user.name) 99 print(client.user.id) 100 print('------') 101 102 103 104 105@client.event 106 107async def on_message(message): 108 if message.attachments: 109 pass 110 111 elif client.user != message.author: 112 text = message.content 113 res = make_reply(text) 114 await client.send_message(message.channel, res) 115 116 117client.run('#DISCORDTOKEN#')
error
1 2------ 3Ignoring exception in on_message 4Traceback (most recent call last): 5 File "/home/hage/.local/lib/python3.9/site-packages/discord/client.py", line 343, in _run_event 6 await coro(*args, **kwargs) 7 File "/home/hage/github/discordbot/discordbot.py", line 113, in on_message 8 res = make_reply(text) 9 File "/home/hage/github/discordbot/discordbot.py", line 72, in make_reply 10 register_dic(words) 11 File "/home/hage/github/discordbot/discordbot.py", line 17, in register_dic 12 if len(words) == 0: return 13TypeError: object of type 'generator' has no len()
エラーが出てお手上げ状態です。
すみませんがご教授願います。