-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdisc.py
More file actions
415 lines (382 loc) · 19.6 KB
/
Copy pathdisc.py
File metadata and controls
415 lines (382 loc) · 19.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
import mojihocori
import random
import re
import sys
import threading
import time
if sys.argv[1]:
cronThread = threading.Thread(target=mojihocori.initialize, args=(sys.argv[1], "discord"), daemon=True)
cronThread.start()
else:
cronThread = threading.Thread(target=mojihocori.initialize, args=("main", "discord"), daemon=True)
cronThread.start()
time.sleep(1)
people = [[mojihocori.DATA.settings["myname"], 0]]
channel = None
lastMessage = None
lastUsername = "誰か"
messages = []
pin = False
yukou = False
import datetime
dt = datetime.datetime.now()
from discord.ext import tasks
import discord
import asyncio
helpMessage = f"""==mojihocoriAIヘルプ==
このbotはユーザーのメッセージに自分の意思で返信するAIです。
話している人数に応じて返信頻度を下げます。
botの名前を呼ぶとそのチャンネルに来てくれます。
メンションでは呼べません。
=学習方法=
チャットのメッセージからも学習しますが、コマンドでの学習のほうが便利です。
```
ぬんへっへ!===下品だよ!
```
=強化学習=
「!bad」とメッセージを送ると、「このメッセージは悪い」と教えることができます。
「!good」とメッセージを送ると、「このメッセージは良い」と教えることができます。
=配慮コマンドについて=
botに「通常モード」というと「通常モード」になり、メッセージにbotの名前が含まれてなくても人数に応じて頻度を変えて返信します。また、沈黙が続いたときにメッセージを送信します。
botに「寡黙モード」というと「寡黙モード」になり、沈黙が続いたときにメッセージを送信しなくなります。
botに「沈黙モード」というと「沈黙モード」になり、呼ばれたときにしかメッセージを送信しなくなります。
botに「ピン」というと、チャンネルを動かなくなります。
botに「アンピン」というと、チャンネルを動けるようになります。
これらのコマンドのタイミングも学習します。"""
# 自分のBotのアクセストークンに置き換えてください
TOKEN = mojihocori.DATA.settings["discToken"]
# 接続に必要なオブジェクトを生成
intents = discord.Intents.all()
client = discord.Client(intents=intents)
mode = mojihocori.DATA.settings["defaultMode"]
print("mode: {}".format(mode))
print("sentences: {}".format(len(mojihocori.DATA.data["sentence"])))
def setMode(x):
global mode, channel
mode = x
print("mode: {}".format(mode))
kaisu = 0
async def speak(result):
global channel, people, mode, pin, lastMessage, messages, kaisu, dt, add, i, yukou
try:
if not add:
i = 0
add = True
mojihocori.MEMORY.learnSentence(result, "!")
print("{}: {}".format(mojihocori.DATA.settings["myname"], result))
#result = re.sub(r'@(everyone|here|[!&]?[0-9]{17,21})', '@\u200b\\1', result)
pattern = re.compile(r"^!command")
print("users: {}".format(people))
results = result.split("\n")
Message = ""
for result in results:
if bool(pattern.search(result)):
nxt = mojihocori.nextSpeak()
com = result.split(" ")
if com[1] == "discMove":
if not pin:
if client.get_channel(int(com[2])) != None:
channel = client.get_channel(int(com[2]))
try:
print("チャンネルを移動しました: {}".format(channel.name))
mojihocori.receive("チャンネルを移動しました: {}".format(channel.name), "!system", add=add)
people = [[mojihocori.DATA.settings["myname"], 0]]
messages.append(["チャンネルを移動しました: {}".format(channel.name), "!system"])
except:
print("チャンネルを移動しました: DM")
mojihocori.receive("チャンネルを移動しました: DM", "!system", add=add)
people = [[mojihocori.DATA.settings["myname"], 0]]
messages.append(["チャンネルを移動しました: DM", "!system"])
else:
print("チャンネルが存在しません")
mojihocori.receive("チャンネルが存在しません", "!system", add=add)
messages.append(["チャンネルが存在しません", "!system"])
else:
print("エラー: あなたは固定されています。")
mojihocori.receive("エラー: あなたは固定されています。", "!system", add=add)
messages.append(["エラー: あなたは固定されています。", "!system"])
elif com[1] == "ignore":
pass
elif com[1] == "setMode":
setMode(int(com[2]))
elif com[1] == "saveMyData":
mojihocori.MEMORY.saveData()
elif com[1] == "pin":
pin = True
elif com[1] == "unpin":
pin = False
elif com[1] == "saveMyData":
mojihocori.MEMORY.saveData()
"""
elif com[1] == "confirmClock":
dt = datetime.datetime.now()
i = 0
add = True
mojihocori.receive(dt.strftime('只今の日付と時刻は、 %Y年 %m月 %d日 %H時 %M分 %S秒 です。'), "!clock", add=add)
lastMessage = [dt.strftime('只今の日付と時刻は、 %Y年 %m月 %d日 %H時 %M分 %S秒 です。'), "!clock"]
messages.append([dt.strftime('只今の日付と時刻は、 %Y年 %m月 %d日 %H時 %M分 %S秒 です。'), "!clock"])
"""
else:
Message += result + "\n"
Message = Message[:-1]
if Message != "":
async with channel.typing():
yukou = True
if len(Message) / 6 / mode >= 1:
if len(Message) / 6 / mode >= 5:
await asyncio.sleep(5)
else:
await asyncio.sleep(len(Message) / 6 / mode)
else:
await asyncio.sleep(1)
if yukou:
await channel.send(Message)
mojihocori.record()
nxt = mojihocori.nextSpeak()
if nxt:
print("続きを返信します")
await speak(nxt)
except:
mojihocori.receive("エラー: チャンネルがNoneか、このチャンネルに入る権限がありません", "!system", add=add)
#messages.append(["エラー: チャンネルがNoneか、このチャンネルに入る権限がありません", "!system"])
print("エラー: チャンネルがNoneか、このチャンネルに入る権限がありません")
# 起動時に動作する処理
@client.event
async def on_ready():
# 起動したらターミナルにログイン通知が表示される
global lastMessage, messages
print('ログインしました')
cron.start()
mojihocori.receive("通知: 貴方は目を覚ましました。", "!system", add=add, reply=True)
lastMessage = ["通知: 貴方は目を覚ましました。", "!system"]
messages.append(["通知: 貴方は目を覚ましました。", "!system"])
dt_now = datetime.datetime.now()
mojihocori.receive(dt_now.strftime('%Y / %m / %d %H : %M : %S'), "!systemClock")
lastMessage = [dt_now.strftime('%Y / %m / %d %H : %M : %S'), "!systemClock"]
messages.append([dt_now.strftime('%Y / %m / %d %H : %M : %S'), "!systemClock"])
ii = 0
i = 0
add = True
# メッセージ受信時に動作する処理
@client.event
async def on_message(message):
global pin, channel, people, lastMessage, messages, helpMessage, lastUsername, ii, mode, i, add, dt, yukou
if bool(re.search("休んで(良い|いい)(わ|よ|わよ)|終了して|exit bot", message.content)) and "モジホコリ、" in message.content:
exit()
return
if message.channel == channel or bool(re.search(mojihocori.DATA.settings["mynames"], message.content)) or isinstance(message.channel, discord.DMChannel):
username = message.author.display_name.split("#")[0]
if message.channel != channel:
try:
print("チャンネルを移動しました: {}".format(message.channel.name))
mojihocori.receive("!command discMove {} | チャンネル名: {}, カテゴリー: {}, トピック: {}".format(message.channel.id, message.channel.name, message.channel.category, message.channel.topic).replace("\n", " "), username)
except:
print("チャンネルを移動しました: {}のDM".format(username))
mojihocori.receive("!command discMove {} | 誰のDMか: {}".format(message.channel.id, username).replace("\n", " "), username)
channel = message.channel
people = [[mojihocori.DATA.settings["myname"], 0]]
if message.author == client.user:
return
ff = False
parts = message.content.split("\n")
taisho = ""
if bool(re.search("(.*?)--", parts[0])):
taisho = parts[0].split("--")[0]
ff = True
for part in parts:
if bool(re.search("(.*?)===(.*?)", part)):
if taisho == "" or taisho in mojihocori.DATA.settings["mynames"]:
if part.split("===")[0] == "":
mojihocori.MEMORY.learnSentence(lastMessage[0], "!input", directLearning=True)
mojihocori.MEMORY.learnSentence(part.split("===")[1], "!output", directLearning=True)
else:
mojihocori.MEMORY.learnSentence(part.split("===")[0], "!input", directLearning=True)
mojihocori.MEMORY.learnSentence(part.split("===")[1], "!output", directLearning=True)
ff = True
if bool(re.search("(.*?)\n==>\n(.*?)", message.content)):
if taisho == "" or taisho in mojihocori.DATA.settings["mynames"]:
mojihocori.MEMORY.learnSentence(message.content.split("\n==>\n")[0], "!input", directLearning=True)
mojihocori.MEMORY.learnSentence(message.content.split("\n==>\n")[1], "!output", directLearning=True)
ff = True
if ff:
mojihocori.MEMORY.learnSentence("!good", "!system", directLearning=True)
return
ff = False
xx = message.content.split("\n")
for x in xx:
if bool(re.search("(.+):- (.+)", x)):
mojihocori.MEMORY.learnSentence(x.split(":- ")[1], x.split(":- ")[0], directLearning=True)
ff = True
if ff:
mojihocori.MEMORY.learnSentence("!good", "!system", directLearning=True)
return
pss = []
for ps in people:
pss.append(ps[0])
if username not in pss:
people.append([username, 0])
if message.content == "" and message.attachments == []:
return
if message.content == None:
return
additional = ""
for attachment in message.attachments:
additional += "\n" + attachment.url
print(attachment.url)
message.content += additional
if bool(re.search("沈黙モード|黙|だま", message.content)) and bool(re.search(mojihocori.DATA.settings["mynames"]+"|モジホコリ、", message.content)):
mojihocori.receive("!command setMode 0", username)
setMode(0)
return
if bool(re.search("寡黙モード|静かに|しずかに", message.content)) and bool(re.search(mojihocori.DATA.settings["mynames"]+"|モジホコリ、", message.content)):
mojihocori.receive("!command setMode 1", username)
setMode(1)
return
if bool(re.search("通常モード|喋って|話して|しゃべって|はなして", message.content)) and bool(re.search(mojihocori.DATA.settings["mynames"]+"|モジホコリ、", message.content)):
mojihocori.receive("!command setMode 2", username)
setMode(2)
return
if bool(re.search("饒舌モード", message.content)) and bool(re.search(mojihocori.DATA.settings["mynames"]+"|モジホコリ、", message.content)):
mojihocori.receive("!command setMode 3", username)
setMode(3)
return
if bool(re.search("ピン|じっとしてて", message.content)) and bool(re.search(mojihocori.DATA.settings["mynames"]+"|モジホコリ、", message.content)):
pin = True
return
if bool(re.search("アンピン|動いていい", message.content)) and bool(re.search(mojihocori.DATA.settings["mynames"]+"|モジホコリ、", message.content)):
pin = False
return
elif bool(re.search("ヘルプを表示|ヘルプ表示|show help", message.content)) and bool(re.search(mojihocori.DATA.settings["mynames"]+"|モジホコリ、", message.content)):
await channel.send(helpMessage)
return
if bool(re.search("セーブして", message.content)) and bool(re.search(mojihocori.DATA.settings["mynames"]+"|モジホコリ、", message.content)):
mojihocori.receive("!command saveMyData", username)
print("セーブします")
mojihocori.MEMORY.saveData()
print("完了")
return
print("受信: {}, from {}".format(message.content, username))
yukou = False
if len(people) <= 2 or isinstance(message.channel, discord.DMChannel):
mojihocori.receive(message.content, username, force=True)
else:
mojihocori.receive(message.content, username, force=True)
lastMessage = [message.content, username]
lastUsername = username
i = 0
add = True
messages.append([message.content, username])
dt = datetime.datetime.now()
done_zhihou = False
zhihou_span = 0
@tasks.loop(seconds=4)
async def cron():
global people, lastMessage, messages, mode, channel, i, add, dt, done_zhihou, zhihou_span
try:
dt_now = datetime.datetime.now()
if not done_zhihou and zhihou_span <= 0:
pattern = re.compile(r"(0|3)0 : [0-9][0-9]$")
if bool(pattern.search(dt_now.strftime('%Y/%m/%d %H:%M:%S'))):
mojihocori.receive(dt_now.strftime('%Y/%m/%d %H:%M:%S'), "!systemClock")
done_zhihou = True
zhihou_span = 90
if zhihou_span > 0:
zhihou_span -= 1
a = []
for person in people:
if person[1] < (60*10)/4:
a.append([person[0], person[1]+1])
people = a
pss = []
for ps in people:
pss.append(ps[0])
if mojihocori.DATA.settings["myname"] not in pss:
people.append([mojihocori.DATA.settings["myname"], 0])
if mode == 1:
if len(messages) != 0:
if mojihocori.DATA.myVoice != None:
if bool(re.search(mojihocori.DATA.settings["mynames"], lastMessage[0])) or isinstance(channel, discord.channel.DMChannel):
result = mojihocori.speakFreely(add=add)
if result == None:
pass
else:
await speak(result)
messages = []
if random.randint(0, 60*25) == 0 and mojihocori.DATA.myVoice != None:
result = mojihocori.speakFreely(add=add)
if result == None:
pass
else:
await speak(result)
elif mode == 2:
if len(messages) != 0:
pss = []
for ps in people:
pss.append(ps[0])
aaa = ""
for person in pss:
if person == mojihocori.DATA.settings["myname"]:
pass
else:
aaa = aaa + person + "|"
aaa = aaa[0:-1]
if len(people)-1 <= 0:
denominator = 0
else:
denominator = len(people)-1
if bool(re.search(mojihocori.DATA.settings["mynames"], lastMessage[0])) or isinstance(channel, discord.channel.DMChannel) or ((not bool(re.search(aaa, lastMessage[0])) or aaa == "") and random.randint(0, denominator) == 0 and mojihocori.DATA.myVoice != None):
result = mojihocori.speakFreely(add=add)
if result == None:
pass
else:
await speak(result)
messages = []
elif mode == 3:
if len(messages) != 0:
pss = []
for ps in people:
pss.append(ps[0])
aaa = ""
for person in pss:
if person == mojihocori.DATA.settings["myname"]:
pass
else:
aaa = aaa + person + "|"
aaa = aaa[0:-1]
if len(people)-2 <= 0:
denominator = 0
else:
denominator = len(people)-2
if bool(re.search(mojihocori.DATA.settings["mynames"], lastMessage[0])) or isinstance(channel, discord.channel.DMChannel) or ((not bool(re.search(aaa, lastMessage[0])) or aaa == "") and random.randint(0, denominator) == 0 and mojihocori.DATA.myVoice != None):
result = mojihocori.speakFreely(add=add)
if result == None:
pass
else:
await speak(result)
messages = []
if dt_now - dt >= datetime.timedelta(seconds=20):
if i > -2:
i -= 1
add = True
if i <= -2:
add = False
dt = datetime.datetime.now()
mojihocori.receive("!command ignore", mojihocori.DATA.lastUser, add=add)
pattern = re.compile(r"(0|3)0 : [0-9][0-9]$")
if bool(pattern.search(dt_now.strftime('%Y/%m/%d %H:%M:%S'))):
mojihocori.receive(dt_now.strftime('%Y/%m/%d %H:%M:%S'), "!systemClock", add=add)
print("沈黙を検知")
if len(people)-2 <= 0:
denominator = 0
else:
denominator = len(people)-2
if mode == 2 and random.randint(0, denominator) == 0:
result = mojihocori.speakFreely(add=add)
if result == None:
pass
else:
await speak(result)
except:
import traceback
traceback.print_exc()
client.run(TOKEN)