async def tts(bot: NoneBot, event: Event, message: Message): print('before_send_message') for seg in message: if seg.type != 'text': continue text = seg.data.get('text') if text: speech_base64 = await tencent_ai.tts(text) if speech_base64: seg.type = 'record' seg.data = {'base64': speech_base64} message.reduce()
async def tagrc(session: CommandSession): # 从会话状态(session.state)中获取城市名称(city),如果当前不存在,则询问用户 # tags = session.get('tags', prompt='输入tag列表,空格隔开') # 获取城市的天气预报 setu_path = await get_setu_path() if not setu_path: return msg = Message("test") msg_seg = MessageSegment.image(setu_path) msg.append(msg_seg) print(msg) print(str(msg)) print(str(msg_seg)) # 向用户发送天气预报 await session.send(msg)
async def _(session: CommandSession): hour: str = session.get('hour', prompt='您想几点运行,多个时间用逗号隔开') minute: str = session.get('minute', prompt='您想几分运行,多个时间用逗号隔开') cmd: str = session.get('cmd', prompt='请输入要运行的指令') cmd = cmd.strip('命令') #Hoshino消息只处理一次,加上命令前缀防止触发命令 session.event.raw_message = cmd session.event.message = Message(MessageSegment.text(cmd)) try: global _running_jobs job = add_cron_job(task, hour=hour, minute=minute, args=[session.event]) _running_jobs.append(job) global _tasks #对event先处理,剔除由RexTrigger添加的match对象 if 'match' in session.event: del session.event['match'] _tasks['data'].append( dict({ "id": job.id, "event": session.event, "hour": hour, "minute": minute })) save_config(_tasks, _task_path) await session.send('设置成功') except ValueError as ex: sv.logger.error(f'添加定时任务时出现异常{ex}') await session.send('参数错误,请重新设置') except: print_exc()
def msg_from_text(cls, text: str): text = text.strip() msg: Message = Message() for t in text.split(): if msg: msg.append(MessageSegment.text(' ')) msg.append(cls.build(t)) return msg
async def _(): for tsk in _tasks['data']: #构造Event对象event event = Event(tsk['event']) event.message = Message(tsk['event']['message']) #构造消息段对象 hour = tsk['hour'] minute = tsk['minute'] id = tsk['id'] try: job = add_cron_job(task, id=id, hour=hour, minute=minute, args=[event]) global _running_jobs _running_jobs.append(job) except ValueError as ex: sv.logger.error(f'添加定时任务时出现异常{ex}')
async def _(session: CommandSession): delay: str = session.get('delay', prompt='请输入延迟时间,单位为秒') if not delay.isdigit(): await session.send('参数错误,请确保输入为数字') session.finish() cmd: str = session.get('cmd', prompt='请输入要运行的指令') cmd = cmd.strip('命令') #将当前event中的消息段替换 session.event['raw_message'] = cmd session.event['message'] = Message([{ 'type': 'text', 'data': { 'text': f'{cmd}' } }]) try: add_delay_job(task=task, delay_time=int(delay), args=[session.event]) await session.send('设置成功') except ValueError as ex: await sv.logger.error(f'添加延时任务时出现异常{ex}') await session.send('参数错误,请重新设置')
def _check_hbtitle_is_cmd(ctx, title): ctx = ctx.copy() # 复制一份,避免影响原有的ctx ctx['message'] = Message(title) _check_calling_me_nickname(bot, ctx) cmd, _ = parse_command(bot, str(ctx['message']).lstrip()) return bool(cmd)
import random from datetime import timedelta import nonebot from nonebot import on_command, message_preprocessor, Message, MessageSegment from nonebot.command import parse_command from nonebot.message import _check_calling_me_nickname from hoshino import logger, util from hoshino.service import Service from hoshino.res import R bot = nonebot.get_bot() BLANK_MESSAGE = Message(MessageSegment.text('')) @message_preprocessor async def black_filter(bot, ctx): first_msg_seg = ctx['message'][0] if first_msg_seg.type == 'hb': return # pass normal Luck Money Pack to avoid abuse if ctx['message_type'] == 'group' and Service.check_block_group(ctx['group_id']) \ or Service.check_block_user(ctx['user_id']): ctx['message'] = BLANK_MESSAGE def _check_hbtitle_is_cmd(ctx, title): ctx = ctx.copy() # 复制一份,避免影响原有的ctx ctx['message'] = Message(title) _check_calling_me_nickname(bot, ctx) cmd, _ = parse_command(bot, str(ctx['message']).lstrip()) return bool(cmd)
async def vote(s: CommandSession, user, group, user_in_group, state): parser = ArgumentParser(session=s, usage=USAGE) parser.add_argument( 'command', choices=['list', 'new', 'yea', 'nay', 'commit', 'count', 'announce']) parser.add_argument('ITEM') parser.add_argument('extra', nargs='?') args = parser.parse_args(s.argv) name = args.ITEM.strip() db: orm.Session = orm.getSession() vote_item = db.query(VoteItem).filter(VoteItem.GroupId == group.GroupId, VoteItem.Name == name).one_or_none() try: if args.command == 'list': msg = Message("List of available vote items:\n") items = None if args.extra == 'all': # Extract all items items = db.query(VoteItem).filter( VoteItem.GroupId == group.GroupId).all() else: # Extract active items items = db.query(VoteItem).filter( VoteItem.GroupId == group.GroupId, VoteItem.Committed == False).all() for item in items: msg.append( MessageSegment.text( f"'{item.Name}' - {item.Description}\n")) await s.send(msg) elif args.command == 'new': if not vote_item: if not args.extra: desc = f"Vote on {name}" else: desc = args.extra item = VoteItem(GroupId=group.GroupId, ProposerId=user.UserId, Name=name, Committed=False, Description=desc) db.add(item) db.commit() await s.send( f"Vote item '{item.Description}' ({item.Name}) created.", at_sender=True) else: await s.send(f"Vote item '{vote_item.Name}' already exisist.", at_sender=True) elif args.command == 'yea': if not vote_item: raise _VoteItemNotFound() if vote_item.Committed: raise _VoteClosed() vote = db.query(Vote).filter( Vote.Item == vote_item.Id, Vote.Voter == user.UserId).one_or_none() if not vote: vote = Vote(Item=vote_item.Id, Voter=user.UserId, Ballot=_BALLOT_YEA) db.add(vote) else: vote.Ballot = _BALLOT_YEA db.commit() await s.send( f"You voted YES to '{vote_item.Description}' ({vote_item.Name}).", at_sender=True) elif args.command == 'nay': if not vote_item: raise _VoteItemNotFound if vote_item.Committed: raise _VoteClosed vote = db.query(Vote).filter( Vote.Item == vote_item.Id, Vote.Voter == user.UserId).one_or_none() if not vote: vote = Vote(Item=vote_item.Id, Voter=user.UserId, Ballot=_BALLOT_NAY) db.add(vote) else: vote.Ballot = _BALLOT_NAY db.commit() await s.send( f"You voted NO to '{vote_item.Description}' ({vote_item.Name}).", at_sender=True) elif args.command == 'commit': if not vote_item: raise _VoteItemNotFound() if vote_item.ProposerId != user.UserId: raise _NotVoteOwner() vote_item.Committed = True db.commit() await s.send( f"You concluded vote item '{vote_item.Description}' ({vote_item.Name}).", at_sender=True) elif args.command == 'count': if not vote_item: raise _VoteItemNotFound total_count = db.query(Vote).filter( Vote.Item == vote_item.Id).count() positives = db.query(Vote).filter( Vote.Item == vote_item.Id, Vote.Ballot == _BALLOT_YEA).count() await s.send( f"Vote item '{vote_item.Description}' ({vote_item.Name}) got {positives} YES among {total_count} votes." ) elif args.command == 'announce': if not vote_item: raise _VoteItemNotFound total_count = db.query(Vote).filter( Vote.Item == vote_item.Id).count() # proposer = db.query(orm.User).filter(orm.User.UserId==vote_item.ProposerId).one() positives = db.query(Vote).filter( Vote.Item == vote_item.Id, Vote.Ballot == _BALLOT_YEA).all() # positives = db.query(Vote, orm.User) \ # .join(Vote.Voter == orm.User.UserId) \ # .filter(Item=vote_item.Id, Ballot=_BALLOT_YEA) \ # .all() msg = nonebot.Message( f"Vote item '{vote_item.Description}' ({vote_item.Name}) initiated by " ) msg.append(MessageSegment.at(vote_item.ProposerId)) msg.append( MessageSegment.text( f" got {len(positives)} YES among {total_count} votes. ")) msg.append( MessageSegment.text( f"The following users in favor of the item:")) segs = [ nonebot.MessageSegment.at(vote.Voter) for vote in positives ] for seg in segs: msg.append(seg) await s.send(msg) else: raise Exception except _VoteItemNotFound: await s.send(f"Vote item '{name}' does not exist.", at_sender=True) except _NotVoteOwner: await s.send(f"You does not own vote item '{name}'.", at_sender=True) except _VoteClosed: await s.send(f"Voting for '{name}' is already closed.", at_sender=True)