async def send_msgs(event: Event, msgs): bot = get_bot() if not msgs: return for msg in msgs: await bot.send(event, msg)
from os import path import asyncio import datetime import re from apscheduler.triggers.date import DateTrigger # 一次性触发器 from nonebot import permission as perm from nonebot import on_command, on_request, RequestSession, CommandSession, scheduler from nonebot import message from nonebot import get_bot from nonebot import log from .database import * from .game import * bot = get_bot() is_baohuang_open = set() db = Database(os.path.join(sys.path[0], "hoshino/modules/baohuang")) on_table = [] table = None buqiang = [] basepoint = 500 @on_command('开启保皇', only_to_me=False, permission=perm.SUPERUSER) async def open_baohuang(session): if session.current_arg == '' and session.event.detail_type == 'group': global is_baohuang_open is_baohuang_open.add(session.event.group_id) log.logger.debug(str(is_baohuang_open)) await session.send(message.MessageSegment.text('保皇功能已开启')) @on_command('关闭保皇', only_to_me=False, permission=perm.SUPERUSER)
from nonebot import on_command, CommandSession from nonebot import on_natural_language, NLPSession, IntentCommand from nonebot.helpers import context_id, render_expression as expr from nonebot import get_bot from nonebot.log import logger import optparse import time import json import ssl import subprocess import logging TXCHAT_NOANSWER = get_bot().config.TXCHAT_NOANSWER TXAI_APP_ID = get_bot().config.TXAI_APP_ID TXAI_APP_KEY = get_bot().config.TXAI_APP_KEY @on_command('aichat',only_to_me=True) async def aichat(session: CommandSession): chat = session.state.get('chat') logger.info('[腾讯闲聊]指令被触发了,开始运行') aichat_re = await call_txai_api(chat) if aichat_re == 'ERROR4': logger.info('[腾讯闲聊]出现意外了:腾讯端还不会回答用户的问题,代码:4 - TXAI-16394') logger.info('[腾讯闲聊]向用户告知不会回答并结束') await session.send(expr(TXCHAT_NOANSWER),at_sender=True) elif aichat_re == 'ERROR6': logger.info('[腾讯闲聊]出现错误了:代码:6 - TXAI-YourNetworkBad') logger.debug('[腾讯闲聊]小提醒:腾讯端网络堵塞,请重新触发即可') logger.info('[腾讯闲聊]指令出现错误并结束') await session.send('通往次元的轮船堵船啦,请稍后再找我吧-_-|||',at_sender=True)
async def welcome_new(qq_account: str): bot = nonebot.get_bot() bot.send_private_msg(user_id=int(qq_account), message=f"欢迎使用本机器人,请输入\n命令列表\n来浏览命令。\nCopyright SkyRain 2020") pass
elif f_type.startswith('audio'): folder = R.record_dir folder = R.image_dir if not path.exists(folder): os.mkdir(folder) with open(path.join(folder, fobj.filename), 'wb') as f: f.write(fobj.read()) return str(R.record(fobj.filename)) else: raise TypeError('不支持的文件类型') import nonebot from datetime import timedelta app = nonebot.get_bot().server_app public_address = '333.33.33.33' #改为你服务器的公网ip port = nonebot.get_bot().config.PORT passwd = 'xcw' #登录密码 @reply.before_request async def _(): user_ip = request.remote_addr if request.path == '/login': return if session.get('user_ip') == user_ip: #登录过 return #没有登录,重定向至登录界面 return redirect('/login')
def url(self): """ @return: 资源文件的url,供cqhttp使用 """ return urljoin(get_bot().config.RESOURCE_URL, pathname2url(self.__path))
async def check_task(): bot = nonebot.get_bot() weihu = hoshino.config.SUPERUSERS[0] result = await check.get_check_easy() await bot.send_private_msg(user_id=weihu, message=result)
# sample json fetch: # http://api.openweathermap.org/data/2.5/forecast?appid=AAAAAAAAAAAAAAA&q=London&units=metric from datetime import datetime import json import random import aiohttp from nonebot import get_bot from utils_bot.typing import Union # 'weather' for current weather instead URL_BASE: str = 'http://api.openweathermap.org/data/2.5/forecast?appid=' # + API_KEY: str = get_bot().config.OPENWEATHERMAP_API_KEY # + URL_MODE: str = '&units=metric&cnt=25&q=' # + #city # fetch weather json data async def fetch(*city: str) -> dict: headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36' } async with aiohttp.ClientSession() as session: try:
with open(DATA_PATH, 'w') as datafile: json.dump( {"global": {"full_match": {}, "inclusive_match": {}, "regex_match" : {}} }, datafile, indent=4) def load_data() -> dict: with open(DATA_PATH) as datafile: return json.load(datafile) # load reply data REPLIES: dict = load_data() # acquires global event monitor bot: NoneBot = get_bot() # auto reply in group chats def process_var(ctx: Context_T, myText: str) -> str: 'process whether the reply keyword contains variables.' if not re.search(r'{SENDER_.+]', myText): return myText else: # define pointer constants try: SENDER_ID: str = str(ctx['sender']['user_id']) SENDER_NICK: str = ctx['sender']['nickname'] SENDER_CARD: str = ctx['sender']['card'] SENDER_ROLE: str = ctx['sender']['role'] SENDER_TITLE: str = ctx['sender']['title']
def get_bot() -> nonebot.NoneBot: return nonebot.get_bot()
async def start_game(group_id): bot = nonebot.get_bot() hr = HorseRace() state = await hr.race_state() current_round = state response = "行动阶段#%s\n" % current_round horse_list = await hr.search_horse() for horse in horse_list: move = await hr.move_horse(horse[0]) if move > 0: response += "%s的%s向前冲了%s步!\n" % (await get_nick_name( group_id, horse[2]), horse[1], move) else: response += "%s的%s摸鱼了!\n" % (await get_nick_name( group_id, horse[2]), horse[1]) response += "战斗阶段\n" r = random.randint(1, 8) if r <= 3: response += "上帝鸽了\n" else: response += await hr.god_attack(group_id) ub_list = await hr.search_sorted_horse_ascend() for horse in ub_list: if horse[4] >= 100: response += await hr.ub(horse, group_id) response += "最终状态\n" horse_list = await hr.search_horse() champ_list = list() for horse in horse_list: if horse[1] in HORSE_SKIN.keys(): skin = HORSE_SKIN[horse[1]] else: skin = HORSE horse_line = "[CQ:emoji,id=%s]:" % (10000048 + horse[0]) + "=" * ( horse[3] - 1) + skin + "=" * (10 - horse[3]) + "\n" response += horse_line if horse[3] == 10: champ_list.append(horse) await bot.send_group_msg(group_id=group_id, message=response) if len(champ_list) > 0: response = "赛马结束了!恭喜\n" for horse in champ_list: response += "%s的%s\n" % (await get_nick_name(group_id, horse[2]), horse[1]) await hr.add_winner(horse[1]) response += "获得了冠军!" for horse in horse_list: await hr.add_race(horse[1]) await bot.send_group_msg(group_id=group_id, message=response) await resolve_gamble(group_id, champ_list) await hr.end_race() else: await hr.set_state(current_round + 1) delta = datetime.timedelta(seconds=10) trigger = DateTrigger(run_date=datetime.datetime.now() + delta) scheduler.add_job( func=start_game, trigger=trigger, args=(group_id, ), misfire_grace_time=60, )
async def bighead(session: CommandSession): parser = ArgumentParser(session=session, usage=BIGUSAGE) group = parser.add_argument_group() group.add_argument('-p', '--price', type=int, help="大头菜的价格") group.add_argument('-l', '--list', action='store_true', help="列出当前有的大头菜价格", default=False) group.add_argument('-d', '--delt', action='store_true', help='删除你自己的大头菜价格', default=False) args = parser.parse_args(session.argv) if args.price != None: if args.price > 810 or args.price < 0: session.finish('小老弟,你怎么回事?') async with db.pool.acquire() as conn: try: state = await conn.execute( '''insert into datou (qid,price) values ({0},{1});'''. format(session.event.user_id, args.price)) except asyncpg.exceptions.ForeignKeyViolationError as e: await conn.execute( '''insert into quser (qid,swid) values ({0},{1});'''. format( session.event.user_id, swFormatter( session.event.sender['card'] if session. event['message_type'] != 'private' else '-1'))) state = await conn.execute( '''insert into datou (qid,price) values ({0},{1});'''. format(session.event.user_id, args.price)) except asyncpg.exceptions.UniqueViolationError as e: state = await conn.execute( '''update datou set price = {1} where qid='{0}';'''.format( session.event.user_id, args.price)) values = await conn.fetch( '''select * from datou where qid = {0}'''.format( session.event.user_id)) logger.info('大头菜上市完成') session.finish( '已{}如下记录:\n'.format('添加' if 'UPDATE' not in state else '更新') + roomPaser(values[0], 1)) elif args.list == True: bot = nonebot.get_bot() async with db.pool.acquire() as conn: values = await conn.fetch( '''select * from datou order by price DESC''') if len(values) == 0: session.finish('很遗憾,当前没有大头菜报价。') for i in range(min(maxbig_head, len(values))): await session.send(roomPaser(values[i])) if session.event['message_type'] == 'group' and len( values) <= maxbig_head: await session.send( unescape(f"{cq.at(session.event.user_id)} 全部报价如上。")) try: for value in values[maxbig_head:]: await bot.send_private_msg(message=roomPaser(value), user_id=session.event.user_id) if len(values) > maxbig_head: await bot.send_private_msg(message='全部报价如上。', user_id=session.event.user_id) except CQHttpError: session.finish( unescape( f'{cq.at(session.event.user_id)} 剩余大头菜报价信息发送失败,请尝试与我发送临时消息。' )) if len(values ) > maxbig_head and session.event['message_type'] == 'group': pass # await session.send(unescape(f'{cq.at(session.event.user_id)} 剩余大头菜报价已私发,请查收。')) elif args.delt == True: async with db.pool.acquire() as conn: value = await conn.execute( f'select * from datou where qid={session.event.user_id}') if len(value) == 0: session.finish('你貌似并没有上市的大头菜。') await conn.execute( f'''delete from datou where qid={session.event.user_id};''') session.finish('删除完成')
async def _arena_query(session:CommandSession, region:int): arena.refresh_quick_key_dic() uid = session.ctx['user_id'] if not lmt.check(uid): session.finish('您查询得过于频繁,请稍等片刻', at_sender=True) lmt.start_cd(uid) # 处理输入数据 argv = session.current_arg_text.strip() argv = re.sub(r'[??,,_]', ' ', argv) argv = argv.split() if 0 >= len(argv): session.finish('请输入防守方角色,用空格隔开', at_sender=True) if 5 < len(argv): session.finish('编队不能多于5名角色', at_sender=True) defen = [ Chara.name2id(name) for name in argv ] for i, id_ in enumerate(defen): if Chara.UNKNOWN == id_: await session.finish(f'编队中含未知角色"{argv[i]}",请尝试使用官方译名\n您可@bot来杯咖啡+反馈未收录别称\n或前往 github.com/Ice-Cirno/HoshinoBot/issues/5 回帖补充', at_sender=True) if len(defen) != len(set(defen)): await session.finish('编队中出现重复角色', at_sender=True) if 1004 in defen: await session.send('\n⚠️您正在查询普通版炸弹人\n※万圣版可用万圣炸弹人/瓜炸等别称', at_sender=True) # 执行查询 sv.logger.info('Doing query...') res = await arena.do_query(defen, uid, region) sv.logger.info('Got response!') # 处理查询结果 if res is None: session.finish('查询出错,请联系维护组调教\n请先移步pcrdfans.com进行查询', at_sender=True) if not len(res): session.finish('抱歉没有查询到解法\n※没有作业说明随便拆 发挥你的想象力~★\n作业上传请前往pcrdfans.com', at_sender=True) res = res[:min(6, len(res))] # 限制显示数量,截断结果 # 发送回复 if get_bot().config.IS_CQPRO: sv.logger.info('Arena generating picture...') atk_team = [ Chara.gen_team_pic(entry['atk']) for entry in res ] atk_team = concat_pic(atk_team) atk_team = pic2b64(atk_team) atk_team = str(MessageSegment.image(atk_team)) sv.logger.info('Arena picture ready!') else: atk_team = '\n'.join(map(lambda entry: ' '.join(map(lambda x: f"{x.name}{x.star if x.star else ''}{'专' if x.equip else ''}" , entry['atk'])) , res)) details = [ " ".join([ f"赞{e['up']}+{e['my_up']}" if e['my_up'] else f"赞{e['up']}", f"踩{e['down']}+{e['my_down']}" if e['my_down'] else f"踩{e['down']}", e['qkey'] ]) for e in res ] defen = [ Chara.fromid(x).name for x in defen ] defen = f"防守方【{' '.join(defen)}】" at = str(MessageSegment.at(session.ctx["user_id"])) msg1 = [ defen, f'已为骑士{at}查询到以下进攻方案:', f'{atk_team}Support by pcrdfans_com' ] msg2 = [ f'为骑士{at}查询到作业评价👍&👎:', *details, '※发送"点赞/点踩"可进行评价', '※手机QQ无法正常显示图片故分条发送 如有刷屏还请谅解', ] if region == 1: msg2.append('※使用"b怎么拆"或"台怎么拆"可按服过滤') sv.logger.debug('Arena sending result...') await session.send('\n'.join(msg1)) await session.send('\n'.join(msg2)) sv.logger.debug('Arena result sent!')
async def debug(msg): bot = nb.get_bot() await bot.send_private_msg(user_id=724463877, message=msg)
def get_app_key() -> str: return nonebot.get_bot().config.TENCENT_AI_APP_KEY
makefile(filepath) filepath = os.path.abspath(os.path.join(os.getcwd(), "../../__init__.py")) makefile(filepath, "from .src.client import nonebot_plugin") sys.exit() from nonebot import get_bot, scheduler from .yobot import Yobot verinfo = { "run-as": "nonebot-plugin", "ver_name": "yobot{}插件版".format(Yobot.Version), } rcnb = get_bot() bot = Yobot(data_path="./yobot_data", verinfo=verinfo) @rcnb.on_message async def handle_msg(context): if context["message_type"] == "group" or context[ "message_type"] == "private": reply = bot.proc(context) else: reply = None if reply != "" and reply is not None: return {'reply': reply, 'at_sender': False} else: return None
def __init__(self, res_path): res_dir = os.path.expanduser(get_bot().config.RESOURCE_DIR) self.fullpath = os.path.abspath(os.path.join(res_dir, res_path)) if not self.fullpath.startswith(os.path.abspath(res_dir)): raise ValueError('Cannot access outside RESOUCE_DIR')
def init() -> None: """ Initialize the cache module. """ bot = get_bot() caches.set_config({'default': bot.config.AIOCACHE_DEFAULT_CONFIG})
# -*- coding: utf-8 -*- # Author:w k import nonebot as rcnb import asyncio from gadget.untils.aiorequests import Aiorequests as requests RCNBOT = rcnb.get_bot() ### 百度 # 获取百度语音合成的token @rcnb.scheduler.scheduled_job('interval', days=10) async def get_bd_token(): token_url = 'https://aip.baidubce.com/oauth/2.0/token' data = { 'grant_type': 'client_credentials', 'client_id': RCNBOT.config.BD_CLIENT_ID, 'client_secret': RCNBOT.config.BD_CLIENT_SECRET, } headers = {'Content-Type': 'application/json; charset=UTF-8'} response = await requests.post(token_url, data=data, headers=headers) key = response['access_token'] if key: RCNBOT.config.BD_TOKEN = key else: await asyncio.sleep(60) return await get_bd_token()
async def add(session: CommandSession): # 从会话状态(session.state)中获取订阅信息链接(link),如果当前不存在,则询问用户 rss_dy_link = session.get( 'add', prompt= '要订阅的信息不能为空呢,请重新输入\n输入样例:\ntest /twitter/user/xx 11,11 -1 5 1 0 \n订阅名 订阅地址 qq(,分隔,为空-1) 群号(,分隔,为空-1) 更新时间(分钟,可选) 1/0(代理,可选) 1/0(第三方订阅链接,可选) 1/0(翻译,可选) 1/0(仅标题,可选) 1/0(仅图片,可选)' ) # 权限判断 user_id = session.ctx['user_id'] if user_id in config.ROOTUSER: # 获取、处理信息 dy = rss_dy_link.split(' ') # await session.send('')#反馈 # print('\n\n\n'+str(len(dy)),dy[0]+'\n\n\n') try: name = dy[0] name = re.sub(r'\?|\*|\:|\"|\<|\>|\\|/|\|', '_', name) if name == 'rss': name = 'rss_' url = dy[1] user_id = dy[2] group_id = dy[3] if len(dy) > 4: times = int(dy[4]) else: times = 5 if len(dy) > 5: proxy = bool(int(dy[5])) else: proxy = False if len(dy) > 6: notrsshub = bool(int(dy[6])) else: notrsshub = False if len(dy) > 7: translation = bool(int(dy[7])) else: translation = False if len(dy) > 8: only_title = bool(int(dy[8])) else: only_title = False if len(dy) > 9: only_pic = bool(int(dy[9])) else: only_pic = False rss = RSS_class.rss(name, url, user_id, group_id, times, proxy, notrsshub, translation, only_title, only_pic) # 写入订阅配置文件 # 先读看是否重复再写 flag = 0 bot = nonebot.get_bot() try: list_rss = RWlist.readRss() for old in list_rss: if old.name == rss.name or old.url == rss.url: flag = 1 if flag == 0: list_rss.append(rss) RWlist.writeRss(list_rss) else: # 向用户发送失败信息 logger.info('添加' + rss.name + '失败,已存在') await session.send('订阅名或订阅链接已经存在!') except: list_rss = [] list_rss.append(rss) RWlist.writeRss(list_rss) if flag == 0: # 加入订阅任务队列 TR.rss_trigger(times, rss) logger.info('添加' + rss.name + '成功') # 向用户发送成功信息 await session.send(rss.name + '订阅成功!') except: await session.send('参数不对哟!') else: await session.send('你没有权限进行此操作!\n关于插件:http://ii1.fun/7byIVb')
def bot(self): return nonebot.get_bot()
async def image_cleaner(): self_id = list(nonebot.get_bot()._wsr_api_clients.keys())[0] await nonebot.get_bot().clean_data_dir(self_id=self_id, data_dir='image') logger.info('Image 文件夹已清理')
import json import requests from os import path from random import choice import thulac import nonebot as nb import sys from ...hanziconv import HanziConv from ...log import logger RECOMMENDER_MUSIC = nb.get_bot().config.RECOMMENDER_MUSIC PLAYLIST_MUSIC = nb.get_bot().config.PLAYLIST_MUSIC async def get_recommend(music_command: str): music_command = HanziConv.toSimplified(music_command) logger.debug("Start fetching keywords……") keywords = [] user_words_path = path.join(path.dirname(__file__), "user_words.txt") user_words = [] with open(user_words_path, 'r', encoding='UTF-8') as f: for line in f: usr = str(line.strip('\n')) if usr.lower() in music_command.lower(): keywords.append(usr.lower()) user_words.append(usr) thu1 = thulac.thulac() words = thu1.cut(music_command)
from nonebot import NLPSession, get_bot, on_natural_language, scheduler from nonebot.command.argfilter.extractors import extract_text from nonebot.exceptions import CQHttpError from nonebot.log import logger from utils.decorators import SyncToAsync from utils.exception import ExceptionProcess from utils.objects import callModuleAPI from . import models from .access import RecordDAO DatabaseIO = RecordDAO() on_startup = get_bot().server_app.before_serving @scheduler.scheduled_job("interval", minutes=10) @SyncToAsync def saveDetail(): logger.info("Refreshing detail of users and groups.") groupList: List[Dict[str, Any]] = callModuleAPI("get_group_list") groupData: Dict[int, Dict[str, Any]] = {} usersData: Dict[int, List[Dict[str, Any]]] = {} for group in groupList: groupID: int = group["group_id"] groupName: str = group["group_name"] data = callModuleAPI("get_group_member_list", params={"group_id": groupID}, ignoreError=True)
import nonebot from .view import switcher app = nonebot.get_bot().server_app app.register_blueprint(switcher)
async def _(): bot = nonebot.get_bot() now = datetime.now() cf = getFirstCf() niuke = getFirstNiuke() codechef = getFirstCodeChef() atcoder = getFirstAtcoder() # cf name = list(cf) time = cf[name[0]] print("*" * 10 + "cf") print(time) dates = datetime.strptime(time, "%Y-%m-%d %H:%M") print(dates) ans = getAns(dates, now) # loadGroup() if ans == 1: if dates.minute < 10: text = "比赛平台 codeforces \r\n" + name[ 0] + ", 将会在今天 %s : 0%s 举行记得准时参加哦" % (str( dates.hour), str(dates.minute)) else: text = "比赛平台 codeforces \r\n" + name[ 0] + ", 将会在今天 %s : %s 举行记得准时参加哦" % (str( dates.hour), str(dates.minute)) try: group = loadGroup() for it in group: await bot.send_group_msg(group_id=it, message=text) ID = loadId() for it in ID: await bot.send_private_msg(user_id=it, message=text) except CQHttpError: pass # 牛客 name = list(niuke) time = niuke[name[0]] print("*" * 10 + "牛客") print(time) dates = datetime.strptime(time, "%Y-%m-%d %H:%M") ans = getAns(dates, now) if ans == 1: text = "" if (dates.minute < 10): text = "比赛平台:牛客 \r\n " + name[ 0] + ", 将会在今天 %s : 0%s 举行记得准时参加哦" % (str( dates.hour), str(dates.minute)) else: text = "比赛平台:牛客 \r\n " + name[0] + ", 将会在今天 %s : %s 举行记得准时参加哦" % ( str(dates.hour), str(dates.minute)) try: group = loadGroup() for it in group: await bot.send_group_msg(group_id=it, message=text) ID = loadId() for it in ID: await bot.send_private_msg(user_id=it, message=text) except CQHttpError: pass # codechef name = list(codechef) time = codechef[name[0]] dates = datetime.strptime(time, "%Y-%m-%d %H:%M") print("*" * 10 + "codechef") print(dates) ans = getAns(dates, now) if ans == 1: text = "" if (dates.minute < 10): text = "比赛平台 codechef \r\n" + name[ 0] + ", 将会在今天 %s : 0%s 举行记得准时参加哦" % (str( dates.hour), str(dates.minute)) else: text = "比赛平台 codechef \r\n" + name[ 0] + ", 将会在今天 %s : %s 举行记得准时参加哦" % (str( dates.hour), str(dates.minute)) try: group = loadGroup() for it in group: await bot.send_group_msg(group_id=it, message=text) ID = loadId() for it in ID: await bot.send_private_msg(user_id=it, message=text) except CQHttpError: pass # atcoder name = list(atcoder) time = atcoder[name[0]] dates = datetime.strptime(time, "%Y-%m-%d %H:%M") print("**" * 5 + "atcoder") print(dates) ans = getAns(dates, now) if ans == 1: text = "" if (dates.minute < 10): text = "比赛平台 atcoder \r\n" + name[ 0] + ", 将会在今天 %s : 0%s 举行记得准时参加哦" % (str( dates.hour), str(dates.minute)) else: text = "比赛平台 atcoder \r\n" + name[ 0] + ", 将会在今天 %s : %s 举行记得准时参加哦" % (str( dates.hour), str(dates.minute)) try: group = loadGroup() for it in group: await bot.send_group_msg(group_id=it, message=text) ID = loadId() for it in ID: await bot.send_private_msg(user_id=it, message=text) except CQHttpError: pass
async def add(session: CommandSession): # 从会话状态(session.state)中获取订阅信息链接(link),如果当前不存在,则询问用户 user_id = session.ctx['user_id'] try: group_id = session.ctx['group_id'] except: group_id = None if group_id: rss_dy_link = session.get( 'add', prompt= '要订阅的信息不能为空呢,请重新输入\n输入样例:\ntest /twitter/user/xx \n关于插件:http://ii1.fun/7byIVb' ) else: rss_dy_link = session.get( 'add', prompt= '要订阅的信息不能为空呢,请重新输入\n输入样例:\ntest /twitter/user/xx 11,11 -1 5 1 0 \n订阅名 订阅地址 qq(,分隔,为空-1) 群号(,分隔,为空-1) 更新时间(分钟,可选) 1/0(代理,可选) 1/0(翻译,可选) 1/0(仅标题,可选) 1/0(仅图片,可选)' ) # 获取、处理信息 dy = rss_dy_link.split(' ') # await session.send('')#反馈 # print('\n\n\n'+str(len(dy)),dy[0]+'\n\n\n') try: name = dy[0] name = re.sub(r'\?|\*|\:|\"|\<|\>|\\|/|\|', '_', name) if name == 'rss': name = 'rss_' try: url = dy[1] except: url = None flag = 0 try: list_rss = RWlist.readRss() for old in list_rss: if old.name == name and not url: old_rss = old flag = 1 elif str(old.url).lower() in str(url).lower(): old_rss = old flag = 2 elif old.name == name: flag = 3 except: print("error") if group_id: if flag == 0 and url: if len(dy) > 2: only_title = bool(int(dy[2])) else: only_title = False if len(dy) > 3: only_pic = bool(int(dy[3])) else: only_pic = False translation = False times = int(config.add_uptime) proxy = config.add_proxy if user_id in config.SUPERUSERS and len(dy) > 4: proxy = bool(int(dy[4])) if user_id in config.SUPERUSERS and len(dy) > 5: times = int(dy[5]) user_id = -1 else: if flag == 1 or flag == 2: if str(group_id) not in str(old_rss.group_id): list_rss.remove(old_rss) old_rss.group_id.append(str(group_id)) list_rss.append(old_rss) RWlist.writeRss(list_rss) if flag == 1: await session.send( str(name) + '订阅名已存在,自动加入现有订阅,订阅地址为:' + str(old_rss.url)) else: await session.send( str(url) + '订阅链接已存在,订阅名使用已有的订阅名"' + str(old_rss.name) + '",订阅成功!') else: await session.send('订阅链接已经存在!') elif not url: await session.send('订阅名不存在!') else: await session.send('订阅名已存在,请更换个订阅名订阅') return elif user_id and flag == 0: user_id = dy[2] group_id = dy[3] if len(dy) > 4 and int(dy[4]) > 0: times = int(dy[4]) else: times = 5 if len(dy) > 5: proxy = bool(int(dy[5])) else: proxy = False if len(dy) > 6: notrsshub = bool(int(dy[6])) else: notrsshub = False if len(dy) > 7: translation = bool(int(dy[6])) else: translation = False if len(dy) > 8: only_title = bool(int(dy[7])) else: only_title = False if len(dy) > 9: only_pic = bool(int(dy[8])) else: only_pic = False else: # 向用户发送失败信息 logger.info('添加' + rss.name + '失败,已存在') await session.send('订阅名或订阅链接已经存在!') return rss = RSS_class.rss(name, url, str(user_id), str(group_id), times, proxy, notrsshub, translation, only_title, only_pic) # 写入订阅配置文件 bot = nonebot.get_bot() try: list_rss.append(rss) RWlist.writeRss(list_rss) except: list_rss = [] list_rss.append(rss) RWlist.writeRss(list_rss) if flag == 0: # 加入订阅任务队列 TR.rss_trigger(times, rss) logger.info('添加' + rss.name + '成功') # 向用户发送成功信息 await session.send(rss.name + '订阅成功!') except BaseException as e: logger.info(e) await session.send('参数不对哟!\n关于插件:http://ii1.fun/7byIVb')
async def love(session: NLPSession): bot = nonebot.get_bot() send_user = session.event['user_id'] for i in wife_lists.all_user: if i.id == send_user: i.fuckingBoy += 1 break if send_user in wife_lists.user: for i in wife_lists.user_wife_list: if i.husband == send_user: if i.sex == '病娇': await session.send( message=i.name + ":" + "这样啊……你不喜欢我么?那就杀死吧! 没关系,只要在身边就可以了,无论以什么形式都可以;活着也好, " "死掉也好,都可以。", at_sender=True) elif i.sex == '温柔': await session.send(message=i.name + ":" + "这段时间感谢你照顾了,以后要好好吃饭,不要再熬夜了,请一定照顾好自己……", at_sender=True) elif i.sex == '傲娇': await session.send( message=i.name + ":" + "哼,分就分,大笨蛋,我也从来就没有喜欢过你,就此别过吧……我绝对不会再想起你的,哼~永别了,八~嘎", at_sender=True) elif i.sex == '傲慢': await session.send( message=i.name + ":" + "呵,愚蠢的人类,我以前居然对你这种似人非人的生物抱有爱慕,我真是愚蠢,那么祝你下地狱吧", at_sender=True) elif i.sex == '天真': await session.send(message=i.name + ":" + "明明是我先来的~为什么……为什么你连分手都会这么熟练啊,为什么,我不懂啊!", at_sender=True) elif i.sex == '丧女': await session.send( message=i.name + ":" + "啊……也是呢,我不会说话,长得也不漂亮,也不会打扮,还整天给你添乱," "各种方面来看我都是一个一无是处的废物呢,我这种人只会招人讨厌,不如死掉好了(笑),再见了", at_sender=True) elif i.sex == '腹黑': await session.send(message=i.name + ":" + "(手后背刀)这样啊……那祝你幸福,永远找不到完整的女朋友哦", at_sender=True) elif i.sex == '蠢萌': await session.send( message=i.name + ":" + "哎?你要分手吗?为什么啊QAQ?我哪里做得不好吗,我可以改,不要丢下我好不好QWQ", at_sender=True) elif i.sex == 'M': await session.send( message=i.name + ":" + "啊……就是这样,请更多地鞭策我,你越是鞭策,我就越是喜欢你~尽管你这么说了,但我是绝对不会放弃你的", at_sender=True) elif i.sex == 'S': await session.send(message=i.name + ":" + "切~看来你需要被我用高跟鞋踩在头上好好地调教一番呢", at_sender=True) elif i.sex == '弱气': await session.send(message=i.name + ":" + "是这样吗……那以后还能做朋友吗……我还能见到你吗", at_sender=True) elif i.sex == '冒失': await session.send(message=i.name + ":" + "分手?那是什么?能吃吗?啥?你要永远离开我了?不要啊,那样我会饿死的QAQ", at_sender=True) elif i.sex == '中二病': await session.send( message=i.name + ":" + "深居于永劫深渊的恶魔啊,吾以主神宙斯之名命令汝,前去控制那个男人,让他永远沦为吾之奴仆吧!", at_sender=True) elif i.sex == '三无': await session.send(message=i.name + ":" + "哦", at_sender=True) else: await session.send(message=i.name + ":" + "祝你幸福", at_sender=True) wife_lists.user_wife_list.remove(i) wife_lists.user.remove(send_user) beifeng(wife_lists) await write(wife_lists) return else: await session.send(message="你没有老婆,谈什么分手", at_sender=True)
g_config['r18_groups'] = list(g_r18_groups) save_config(g_config) await bot.send(ctx, f'群{gid}r18开启') elif re.match(r'群(\d{5,12})r18关闭', msg): gid = int(re.match(r'群(\d{5,12})r18关闭', msg).group(1)) g_r18_groups.discard(gid) g_config['r18_groups'] = list(g_r18_groups) save_config(g_config) await bot.send(ctx, f'群{gid}r18关闭') else: pass bot = nonebot.get_bot() @bot.on_message async def del_msg(ctx): self_id = ctx['self_id'] global g_msg_to_delete print(g_msg_to_delete) try: if g_msg_to_delete == {}: return for msg_id in list(g_msg_to_delete.keys()): del_time = g_msg_to_delete.get(msg_id) if del_time: if time.time() > g_msg_to_delete[msg_id]: del g_msg_to_delete[msg_id]
async def run_script_A(session: CommandSession): bot = get_bot() groupId, code = session.get('group'), session.get('code') await session.send('脚本开始执行.') await runScriptLangAdmin(code, bot, session, groupId) await session.send('脚本执行完毕.')