Skip to content

Commit

Permalink
修复了大量bug,添加了配置初始化
Browse files Browse the repository at this point in the history
  • Loading branch information
NekoRabi committed Sep 8, 2022
1 parent 462b0bd commit fd20fb5
Show file tree
Hide file tree
Showing 9 changed files with 166 additions and 88 deletions.
19 changes: 4 additions & 15 deletions core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
config = {}
replydata = {}
_syskey = {'admin', 'whitelist', 'blacklist', 'settings', 'welcomeinfo', 'alarmclockgroup', 'commandpre', 'botconfig',
'silencegroup', 'repeatconfig', 'norepeatgroup', 'nudgeconfig', 'loglevel', 'master',
'voicesetting', 'mutegrouplist', 'welcomeinfo', 'replyimgpath'}
'silencegroup', 'repeatconfig', 'norepeatgroup', 'nudgeconfig', 'loglevel', 'master', 'mutegrouplist',
'welcomeinfo', 'replyimgpath'}


def load_config() -> dict:
Expand Down Expand Up @@ -92,11 +92,8 @@ def create_init_config():
repeatQ=20, repeatmsg=1, interruptQ=0.5, interruptQQ=0.1, autoreply=True, kwreply=True),
adapter=dict(verify_key='NekoRabi',
host='localhost', port=17280),
settings=dict(autogetpaipu=True, autowelcome=True, help=True, r18talk=True, nudgereply=True,
silence=False, norepeat=False, voice=False, saveflashimg=True),
voicesetting=dict(codec='mp3', volumn=1, speed=0.85, voicetype=1002, private=True,
secretId='',
secretKey=''))
settings=dict(autowelcome=True, help=True, r18talk=True, nudgereply=True,
silence=False, norepeat=False, saveflashimg=True))
w_cfg_to_file(sys_config, r'./config/config.yml')


Expand All @@ -119,18 +116,10 @@ def create_init_config():
_welcomeinfo = config.get('welcomeinfo', [])
_botconfig = config['botconfig']
_botname = _botconfig['botname']
_voicesetting = config['voicesetting']
master = config.get('master', 0)
replydata['replyimgpath'] = config['replyimgpath']
if master == 0:
print('请输入机器人主人 ( master )')
if _settings.get('voice', None):
if _voicesetting['secretId'].strip() == '' or _voicesetting['secretKey'] == '':
print('请在填写语音设置后,再开启语音功能 现已将语音功能关闭')
_settings['voice'] = False
w_cfg_to_file(content=config, path=r'./config/config.yml')
else:
_settings['voice'] = False
if len(_welcomeinfo) == 0:
print("入群欢迎文本不存在,该功能将关闭")
config['settings']['autowelcome'] = False
Expand Down
58 changes: 46 additions & 12 deletions plugin/AutoReply/autoreply.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
admin = config['admin']
black_list = dict(user=config['blacklist'], group=config['mutegrouplist'])

__all__ = ['duideduide', 'randominterrupt', 'diyreply', 'config_group_repeat', 'sendgroupat', 'sendmsgtogroup']
__all__ = ['duideduide', 'randominterrupt', 'diyreply', 'config_group_repeat', 'sendgroupat', 'sendmsgtogroup',
'fabing', 'crazy_thursday']


@bot.on(GroupMessage)
Expand Down Expand Up @@ -83,8 +84,8 @@ async def randominterrupt(event: GroupMessage):
elif count < repeatconfig['repeatmsg']:
msg_component_type_list = []
for component in event.message_chain:
msg_component_type_list.append(component.type)
if msg_component_type_list == ['Plain']:
msg_component_type_list.append(type(component))
if msg_component_type_list == [Plain]:
print(f"在{event.group.name}群,复读一次{msg}")
return await bot.send(event, event.message_chain)
return
Expand All @@ -100,15 +101,6 @@ async def diyreply(event: GroupMessage):
if not settings['silence'] and repeatconfig['autoreply']:
if event.group.id not in silencegroup:
msg = "".join(map(str, event.message_chain[Plain]))
m = re.match(fr"^{commandpre}{commands_map['reply']['jida']}", msg.strip())
if m:
return await bot.send(event,
f"{m.group(1)}说,他有五个鸡,我说,立直鸡,副露鸡,默听鸡,自摸鸡,放铳鸡\n{m.group(1)}还说,他有四个鸡,我说,坐东鸡,坐西鸡,坐南鸡,坐北鸡\n{m.group(1)}又说,他有三个鸡,我说,上一打鸡,这一打鸡,下一打鸡\n{m.group(1)}又说,他有两个鸡,我说,子家鸡 亲家鸡\n{m.group(1)}最后说,他有一个鸡,我说,{m.group(1)}就是鸡")
m1 = re.match(fr"^{commandpre}{commands_map['reply']['wochao']}", msg.strip())
if m1:
return await bot.send(event,
f"考试中 {event.sender.member_name}想抄{m1.group(1)}的答案🥵{m1.group(1)}一直挡着说 不要抄了 不要抄了🥵当时{m1.group(1)}的眼泪都流下来了🥵可是{event.sender.member_name}还是没听{m1.group(1)}说的🥺一直在抄{m1.group(1)}🥵呜呜呜呜🥺 因为卷子是正反面 说亲自动手 趁监考老师不注意的时候把{m1.group(1)}翻到反面 翻来覆去抄{m1.group(1)}🥵抄完前面抄后面🥵🥵🥵")

senderid = event.sender.id
if botname == "":
return
Expand Down Expand Up @@ -139,6 +131,28 @@ async def diyreply(event: GroupMessage):
rndimg=True))


@bot.on(GroupMessage)
async def fabing(event: GroupMessage):
"""
发病文
很多发病文斗太恶心了
:param event:
:return:
"""
if not settings['silence'] and repeatconfig['autoreply']:
if event.group.id not in silencegroup:
msg = "".join(map(str, event.message_chain[Plain]))
m = re.match(fr"^{commandpre}{commands_map['reply']['jida']}", msg.strip())
if m:
return await bot.send(event,
f"{m.group(1)}说,他有五个鸡,我说,立直鸡,副露鸡,默听鸡,自摸鸡,放铳鸡\n{m.group(1)}还说,他有四个鸡,我说,坐东鸡,坐西鸡,坐南鸡,坐北鸡\n{m.group(1)}又说,他有三个鸡,我说,上一打鸡,这一打鸡,下一打鸡\n{m.group(1)}又说,他有两个鸡,我说,子家鸡 亲家鸡\n{m.group(1)}最后说,他有一个鸡,我说,{m.group(1)}就是鸡")
m1 = re.match(fr"^{commandpre}{commands_map['reply']['wochao']}", msg.strip())
if m1:
return await bot.send(event,
f"考试中 {event.sender.member_name}想抄{m1.group(1)}的答案🥵{m1.group(1)}一直挡着说 不要抄了 不要抄了🥵当时{m1.group(1)}的眼泪都流下来了🥵可是{event.sender.member_name}还是没听{m1.group(1)}说的🥺一直在抄{m1.group(1)}🥵呜呜呜呜🥺 因为卷子是正反面 说亲自动手 趁监考老师不注意的时候把{m1.group(1)}翻到反面 翻来覆去抄{m1.group(1)}🥵抄完前面抄后面🥵🥵🥵")


@bot.on(GroupMessage)
async def config_group_repeat(event: GroupMessage):
"""
Expand All @@ -164,6 +178,26 @@ async def config_group_repeat(event: GroupMessage):
w_cfg_to_file(content=config, path=r'./config/config.yml')


@bot.on(GroupMessage)
async def crazy_thursday(event: GroupMessage):
"""
疯狂星期四
Args:
event:
Returns:
我也不知道返回说明好
"""

if not settings['silence'] and repeatconfig['autoreply']:
if event.group.id not in silencegroup:
msg = "".join(map(str, event.message_chain[Plain]))
m = re.match('[vV]我?(50|五十)', msg.strip())
if m:
return await bot.send(event, messagechain_builder(text='我也想吃KFC'))


@bot.on(FriendMessage)
async def sendmsgtogroup(event: FriendMessage):
"""向某群发送消息,假装机器人"""
Expand Down
4 changes: 2 additions & 2 deletions plugin/ImgOperation/groupmember_imgoperation.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,8 +191,8 @@ async def diuren(event: GroupMessage):
if userid:
img = await throwpeople(userid)
await bot.send(event, messagechain_builder(imgbase64=img))
else:
await bot.send(event, messagechain_builder(text='请At要丢的人哦~'))
# else:
# await bot.send(event, messagechain_builder(text='请At要丢的人哦~'))
return


Expand Down
8 changes: 4 additions & 4 deletions plugin/MajSoulInfo/majsoulinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -557,12 +557,12 @@ def getrank(playerinfo: dict):
averagerank = (rankdict['1'] + rankdict['2'] * 2 +
rankdict['3'] * 3 + rankdict['4'] * 4) / len(paipuresponse)
if selecttype == "4":
paipumsg += f"{rankdict['1']}次①位,{rankdict['2']}次②位,{rankdict['3']}次③位,{rankdict['4']}次④位,平均顺位:{averagerank:1.2f}"
paipumsg += f"{rankdict['1']}次①位,{rankdict['2']}次②位,{rankdict['3']}次③位,{rankdict['4']}次④位"
else:
paipumsg += f"{rankdict['1']}次①位,{rankdict['2']}次②位,{rankdict['3']}次③位,平均顺位:{averagerank:1.2f}"
paipumsg += f"{rankdict['1']}次①位,{rankdict['2']}次②位,{rankdict['3']}次③位"
if rankdict['fly'] > 0:
paipumsg += f"被飞了{rankdict['fly']},"
paipumsg += f"\nPT总得失: {ptchange}\n\n"
paipumsg += f",被飞了{rankdict['fly']}次"
paipumsg += f",平均顺位:{averagerank:1.2f}\nPT总得失: {ptchange}\n\n"
msg += paipumsg
except asyncio.exceptions.TimeoutError as e:
print(f'\n牌谱读取超时:\t{e}\n')
Expand Down
10 changes: 10 additions & 0 deletions plugin/TenHouPlugin/folder_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,4 +105,14 @@ def file_init():
w_cfg_to_file(commands, path=r'./config/command.yml')


# if not os.path.exists(r'./config/TenHouPlugin/command.yml'):
# w_cfg_to_file(thcmds, path=r'./config/command.yml')
# else:
# commands = loadcfg_from_file(r'./config/TenHouPlugin/command.yml')
# for key in ['thpt', 'addwatch', 'delwatch', 'getwatch', 'clearwatch', 'tagon', 'tagoff', 'taglist']:
# if key not in commands.keys():
# commands['tenhou'] = thcmds
# w_cfg_to_file(commands, path=r'./config/command.yml')
# break

file_init()
1 change: 1 addition & 0 deletions plugin/TencentCloudAPI/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
from plugin.TencentCloudAPI.folder_init import *
from plugin.TencentCloudAPI.bot_TencentCloudAPI import *
122 changes: 72 additions & 50 deletions plugin/TencentCloudAPI/bot_TencentCloudAPI.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,64 +4,86 @@
from core import config, bot, commandpre, commands_map
from plugin.TencentCloudAPI.text_to_voice import VoiceCreater
from utils.MessageChainBuilder import messagechain_builder
from utils.cfg_loader import *

__all__ = []
vc = None
__plugin_enable = True
master = config.get('master')
_voice_enable = config.get('settings', dict()).get('voice', False)
_TencentCloudConfig = config.get('voicesetting', None)
_cfg: dict = loadcfg_from_file(r'./config/TencentCloudAPI/config.yml')
_secretId = _cfg.get('secretId', None)
_secretKey = _cfg.get('secretKey', None)
if _secretId:
if isinstance(_secretId,str):
if _secretId.strip() == '':
__plugin_enable = False
else:
__plugin_enable = False
else:
__plugin_enable = False

if _voice_enable:
vc = VoiceCreater(setting=_TencentCloudConfig)
__all__.extend(['send_group_voice', 'send_voice_to_group'])
if _secretKey:
if isinstance(_secretKey,str):
if _secretKey.strip() == '':
__plugin_enable = False
else:
__plugin_enable = False
else:
__plugin_enable = False

if __plugin_enable:

def getbase64voice(text):
voice = dict(error=False, file=None, errmsg=None)
if vc:
voice['file'] = vc.getbase64voice(text=text)
else:
voice['error'] = True
return voice
_voice_enable = _cfg.get('voicesetting', dict()).get('enable', False)
if _voice_enable:
vc = VoiceCreater(setting=_cfg.get('voicesetting'), secretId=_secretId, secretKey=_secretKey)
__all__.extend(['send_group_voice', 'send_voice_to_group'])


def getbase64voice(text):
voice = dict(error=False, file=None, errmsg=None)
if vc:
voice['file'] = vc.getbase64voice(text=text)
else:
voice['error'] = True
return voice


@bot.on(GroupMessage)
async def send_group_voice(event: GroupMessage):
msg = "".join(map(str, event.message_chain[Plain]))
m = re.match(fr"^{commandpre}{commands_map['sendvoice']['sendvoice']}", msg.strip())
if m:
if _voice_enable:
if _TencentCloudConfig['private']:
if event.sender.id != master:
return
text = m.group(1).strip()
if len(text) > 40:
return await bot.send(event, messagechain_builder(text="文本太长啦", rndimg=True))
voice = getbase64voice(text)
if not voice['error']:
return await bot.send(event, Voice(base64=voice['file']))
# return await bot.send(event, await Voice.from_local(content=voice['file'])) # 有问题
# return await bot.send(event, await Voice.from_local(filename=f'./data/audio/{text}.{vc.codec}'))
@bot.on(GroupMessage)
async def send_group_voice(event: GroupMessage):
msg = "".join(map(str, event.message_chain[Plain]))
m = re.match(fr"^{commandpre}{commands_map['sendvoice']['sendvoice']}", msg.strip())
if m:
if _voice_enable:
if _cfg.get('voicesetting', dict()).get('private', False):
if event.sender.id != master:
return
text = m.group(1).strip()
if len(text) > 40:
return await bot.send(event, messagechain_builder(text="文本太长啦", rndimg=True))
voice = getbase64voice(text)
if not voice['error']:
return await bot.send(event, Voice(base64=voice['file']))
# return await bot.send(event, await Voice.from_local(content=voice['file'])) # 有问题
# return await bot.send(event, await Voice.from_local(filename=f'./data/audio/{text}.{vc.codec}'))


@bot.on(FriendMessage)
async def send_voice_to_group(event: FriendMessage):
msg = "".join(map(str, event.message_chain[Plain]))
m = re.match(fr"^{commandpre}{commands_map['sendvoice']['sendgroupvoice']}", msg.strip())
if m:
if _voice_enable:
if _TencentCloudConfig['private']:
if event.sender.id != master:
return
groupid = int(m.group(1))
text = m.group(2).strip()
if len(text) > 40:
return await bot.send(event, messagechain_builder(text="文本太长啦", rndimg=True))
voice = getbase64voice(text)
if not voice['error']:
return await bot.send_group_message(groupid, Voice(base64=voice['file']))
# return await bot.send(event, await Voice.from_local(content=voice['file'])) # 有问题
# return await bot.send(event, await Voice.from_local(filename=f'./data/audio/{text}.{vc.codec}'))
@bot.on(FriendMessage)
async def send_voice_to_group(event: FriendMessage):
msg = "".join(map(str, event.message_chain[Plain]))
m = re.match(fr"^{commandpre}{commands_map['sendvoice']['sendgroupvoice']}", msg.strip())
if m:
if _voice_enable:
if _cfg.get('voicesetting', dict()).get('private', False):
if event.sender.id != master:
return
groupid = int(m.group(1))
text = m.group(2).strip()
if len(text) > 40:
return await bot.send(event, messagechain_builder(text="文本太长啦", rndimg=True))
voice = getbase64voice(text)
if not voice['error']:
return await bot.send_group_message(groupid, Voice(base64=voice['file']))
# return await bot.send(event, await Voice.from_local(content=voice['file'])) # 有问题
# return await bot.send(event, await Voice.from_local(filename=f'./data/audio/{text}.{vc.codec}'))

if len(__all__) > 0:
print(f' |---已启用的腾讯云API服务{__all__}')
if len(__all__) > 0:
print(f' |---已启用的腾讯云API服务{__all__}')
24 changes: 24 additions & 0 deletions plugin/TencentCloudAPI/folder_init.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import os
from utils.cfg_loader import w_cfg_to_file


def file_init():
if not os.path.exists("./config/TencentCloudAPI"):
os.mkdir("./config/TencentCloudAPI")

if not os.path.exists(r'./config/TencentCloudAPI/config.yml'):
_cfg = {
'secretId': '',
'secretKey': '',
'voicesetting': {
'enable': False,
'volume': 1,
'speed': 0.9,
'voicetype': 1002,
'private': True,
'codec': 'mp3'}
}
w_cfg_to_file(content=_cfg, path=r'./config/TencentCloudAPI/config.yml')


file_init()
8 changes: 3 additions & 5 deletions plugin/TencentCloudAPI/text_to_voice.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,16 @@
class VoiceCreater:

def __init__(self, setting=None, secretId=None, secretKey=None, volume=1, speed=0.9, voicetype=1002, codec='mp3',
token=None, timestamp=None):
token=None, timestamp=None, **kwargs):
self.secretId = secretId
self.secretKey = secretKey
if setting:
self.secretId = setting['secretId']
self.secretKey = setting['secretKey']
self.volume = setting['volume']
self.speed = setting['speed']
self.voicetype = setting['voicetype']
self.codec = setting['codec']
else:
self.token = token
self.secretId = secretId
self.secretKey = secretKey
self.timestamp = timestamp
self.volume = volume
self.speed = speed
Expand Down

0 comments on commit fd20fb5

Please sign in to comment.