-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot3.py
165 lines (150 loc) · 5.7 KB
/
bot3.py
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
# Japanese TTS bot
# You should install discord and pynacl package with pip
import discord
from discord.ext.commands import Bot
from urllib import request, parse
from time import sleep
import json
from datetime import datetime
import os
import hashlib
import re
intents = discord.Intents.default()
intents.voice_states = True
intents.members = True
intents.guilds = True
bot = Bot(command_prefix='!', intents=intents)
global settings
with open('settings.json', 'r') as file:
settings = json.load(file)
print(json.dumps(settings))
def sanitizeChat(chat):
# print(f'sanitizing chat: {chat}')
regex = r"<a*:\w+:\d+>" # replace Discord emoji
chat = re.sub(regex, "イモジ", chat, flags=(re.I|re.M))
regex = r"<@!\d+>"
chat = re.sub(regex, "あの,", chat, flags=(re.I|re.M))
# replace URL
regex = r'''(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))'''
chat = re.sub(regex, "ユーアルエル", chat, flags=(re.I|re.M))
# replace Japanese quote mark and whitespaces
regex = r"「|」"
chat = re.sub(regex, "", chat, flags=(re.I|re.M))
chat = chat.replace(' ', '')
chat = chat.replace(' ', '')
return chat
class TTSSession:
def __init__(self, voice_channel, text_channel):
date = datetime.now()
timestamp = date.strftime("%Y-%b-%d-%H-%M-%S-%f")
self.voice_channel = voice_channel
self.text_channel = text_channel
print(f'tc: {str(text_channel.id)}')
enc = hashlib.md5()
enc.update(repr(text_channel.id).encode())
ustr = f'{enc.hexdigest()}_{timestamp}'
print(f'ustr: {ustr}')
self.guid = ustr
print(f'uid created: {self.guid}')
self.isTTSEnabled = False
global ttsSessions
ttsSessions = dict()
def find_sessionKey(ctx):
sessionKey = None
for key in ttsSessions:
text_channel = ttsSessions[key].text_channel
if (text_channel.id == ctx.channel.id):
sessionKey = key
return sessionKey
@bot.event
async def on_ready():
print(f'logged in to {bot.user}')
@bot.command()
async def say(ctx, arg):
encoded = parse.quote(str(arg))
endpoint = settings['tts_api_endpoint']
url = f'{endpoint}{encoded}'
sessionKey = find_sessionKey(ctx)
if (sessionKey != None):
session : TTSSession = ttsSessions[sessionKey]
filepath = f'{session.guid}.wav'
# try:
request.urlretrieve(url, filepath)
session.voice_channel.play(discord.FFmpegPCMAudio(source=filepath))
# except Exception as e:
# await ctx.send(f'声が出ない! 助けて ;^;')
else:
await ctx.send(f'Can\'t find session for {ctx.author.name}')
@bot.command()
async def tts3(ctx):
session : TTSSession = find_sessionKey(ctx)
if(session == None):
# Join voice chat
try:
print('Joining voice chat')
voice_channel = ctx.author.voice.channel
if voice_channel != None:
# Create TTSSession
print('Creating new session')
session = TTSSession(voice_channel, ctx.channel)
ttsSessions[session.guid] = session
print(ttsSessions)
vc = await voice_channel.connect()
session.isTTSEnabled = True
session.voice_channel = vc
else:
await ctx.send(f'VCに入ってくださいね~!')
await ctx.send(f'やっほ~ >_<)9')
except AttributeError as e:
print(e)
await ctx.send(f'VCに入ってくださいね~!')
else:
# Remove TTSSession
sessionKey = find_sessionKey(ctx)
try:
voice_channel = ctx.author.voice.channel
if voice_channel != None:
if(sessionKey != None):
# Leave voice chat
session : TTSSession = ttsSessions[sessionKey]
await session.voice_channel.disconnect()
wavpath = f'{session.guid}.wav'
if (os.path.exists(wavpath)):
os.remove(wavpath)
else:
print(f'Cannot remove the file {wavpath}')
session.isTTSEnabled = False
del ttsSessions[sessionKey]
print(ttsSessions)
await ctx.send(f'またね~!')
else:
await ctx.send(f'VCに入ってくださいね~!')
except AttributeError as e:
print(e)
await ctx.send(f'VCに入ってくださいね~!')
@bot.event
async def on_message(message):
chat = message.content
print(f'author: {message.author}, chat: {chat}')
msgclient = message.guild.voice_client
if message.content.startswith('!'):
await bot.process_commands(message)
else:
if message.guild.voice_client:
print(message.content)
ctx = await bot.get_context(message)
sessionKey = find_sessionKey(ctx)
if(sessionKey != None):
session = ttsSessions[sessionKey]
if(session.isTTSEnabled):
# message.content = f'!sayf {chat}'
chat = sanitizeChat(chat)
message.content = f'!say {chat}'
await bot.process_commands(message)
@bot.event
async def on_voice_state_update(member, before, after):
voice_state = member.guild.voice_client
if voice_state is not None and len(voice_state.channel.members) == 1:
await voice_state.disconnect()
apikey = settings['bot3_api_token']
bot.run(apikey)