Exemplo n.º 1
0
def to_me():
    if plugin_config.haruka_to_me:
        from nonebot.rule import to_me
        return to_me()
    async def _to_me(bot: Bot, event: Event, state: dict):
        return True
    return Rule(_to_me)
Exemplo n.º 2
0
def to_me():
    if config.haruka_to_me:
        from nonebot.rule import to_me
        return to_me()
    async def _to_me(bot: Bot, event: Event, state: T_State) -> bool:
        return True
    return Rule(_to_me)
Exemplo n.º 3
0
 def check_service(self, only_to_me: bool = False, only_group: bool = True) -> Rule:
     async def _cs(bot: Bot, event: CQEvent, state: T_State) -> bool:
         if not 'group_id' in event.__dict__:
             return not only_group
         else:
             group_id = event.group_id
             return self.check_enabled(group_id) and not priv.check_block_group(group_id) and priv.check_priv(event, self.use_priv)
     rule = Rule(_cs)
     if only_to_me:
         rule = rule & (to_me())
     return rule
Exemplo n.º 4
0
async def test_to_me(app: App, expected: bool):
    from nonebot.rule import ToMeRule, to_me

    test_keyword = to_me()
    dependent = list(test_keyword.checkers)[0]
    checker = dependent.call

    assert isinstance(checker, ToMeRule)

    event = make_fake_event(_to_me=expected)()
    assert await dependent(event=event) == expected
Exemplo n.º 5
0
import nonebot
from nonebot.plugin import on_message, on_command
from nonebot.rule import to_me, Rule
from nonebot.typing import T_State
from nonebot.adapters.mirai import Bot, Event, MessageSegment

from .config import Config

global_config = nonebot.get_driver().config
plugin_config = Config(**global_config.dict())

manual = on_message(rule=to_me(), priority=99)
help = on_command('help', priority=98)


@manual.handle()
async def manual_handle(bot: Bot, event: Event, state: T_State):
    await manual.finish(plugin_config.about)


@help.handle()
async def help_handle(bot: Bot, event: Event, state: T_State):
    args = str(event.get_message()).strip()
    if args == "r":
        await help.finish(plugin_config.help_r)
    elif args == "check":
        await help.finish(plugin_config.help_check)
    elif args == "choose":
        await help.finish(plugin_config.help_choose)
    elif args == "daily":
        await help.finish(plugin_config.help_daily)
Exemplo n.º 6
0
import json

from nonebot import on_command
from nonebot.adapters.cqhttp import MessageSegment, Message
from nonebot.rule import to_me
from nonebot.typing import T_State
from nonebot.adapters import Bot, Event
from .data_source import search_pic

searchPic = on_command("搜图", rule=to_me(), priority=5)


@searchPic.handle()
async def handle_first_receive(bot: Bot, event: Event, state: T_State):
    args = str(event.get_message()).strip()  # 首次发送命令时跟随的参数,例:/天气 上海,则args为上海
    if args:
        state["keywords"] = args  # 如果用户发送了参数则直接赋值


@searchPic.got("keywords", prompt="请输入关键字")
async def handle_search(bot: Bot, event: Event, state: T_State):
    keywords = state["keywords"]
    data = await search_pic(keywords)
    if data == "404":
        await bot.send(event=event, message="没有符合条件的图")
    else:
        await bot.send(event=event, message=Message("找到图了!但是发给主人了~"))
        await bot.call_api("send_private_msg",
                           user_id=1924451951,
                           message=MessageSegment.image(file=data['url']))
Exemplo n.º 7
0
from nonebot.plugin import on_keyword, on_command
from nonebot.rule import to_me
from nonebot.adapters.mirai import Bot, MessageEvent

message_test = on_keyword({'reply'}, rule=to_me())


@message_test.handle()
async def _message(bot: Bot, event: MessageEvent):
    text = event.get_plaintext()
    await bot.send(event, text, at_sender=True)


command_test = on_command('miecho')


@command_test.handle()
async def _echo(bot: Bot, event: MessageEvent):
    text = event.get_plaintext()
    await bot.send(event, text, at_sender=True)
Exemplo n.º 8
0
import json
from nonebot import on_command
from nonebot.rule import to_me
from nonebot.typing import T_State
from nonebot.adapters.cqhttp import Bot, Event
from nonebot.adapters import Event

jj_cx = on_command("cx", rule=to_me(), priority=1)


@jj_cx.handle()
async def handle1(bot: Bot, event: Event, state: T_State):
    userid = str(event.get_user_id())
    jjcx = await read_data(userid)
    await jj_cx.finish(jjcx)


async def read_data(userid):
    data_file = "/root/testbot/testbot/plugins/jjconfig/"
    data_file = data_file + userid + '/data.json'
    with open(data_file, encoding='utf-8') as f:
        data = json.load(f)
    return data
Exemplo n.º 9
0
            except Exception as e:
                text = str(e)
            finally:
                time.sleep(1)
    closeconnsql(conn)

scheduler = require('nonebot_plugin_apscheduler').scheduler
@scheduler.scheduled_job('cron',hour='7',minute='0',second='0', id='moring')
async def moring():
   await sendmoring()

    #print(nonebot.get_bots())
        #print(i[0])


#test
command_test = on_keyword({"提示"},rule=to_me())
@command_test.handle()
async def _echo(bot: Bot, event: MessageEvent):
    if event.get_plaintext()!='提示':
        return
    bot = nonebot.get_bots()[get_attr('botqq')]
    if event.get_user_id()not in get_attr('SUPER'):
        text="你暂无此权限"
        await  bot.send(event,text,at_sender=True)
        return
    else:
        await sendmoring()

#
Exemplo n.º 10
0
from nonebot import on_command
from nonebot.rule import to_me
from nonebot.adapters.cqhttp import Bot, Event, MessageSegment

import random
import requests
import lxml
from bs4 import BeautifulSoup
import json
import os
import platform

from christinaqqbot.utils.rule import _gruop_white_list

waifu = on_command('waifu', rule=to_me() & _gruop_white_list)


def save_pic(pic_url):
    pic_name = pic_url.split('/')[-1]
    try:
        r = requests.get(url=pic_url)
    except Exception:
        raise Exception
    with open('./pic/' + pic_name, 'wb') as f:
        f.write(r.content)
        f.close()
    return pic_name


@waifu.handle()
async def _(bot: Bot, event: Event, state: dict) -> None:
Exemplo n.º 11
0
from nonebot import on_command
from nonebot.rule import to_me
from nonebot.params import CommandArg
from nonebot.adapters.onebot.v11 import Message, MessageSegment

from .data_source import get_voice

speak = on_command("说", block=True, rule=to_me(), priority=10)


@speak.handle()
async def _(msg: Message = CommandArg()):
    text = msg.extract_plain_text().strip()
    if not text:
        await speak.finish()

    voice = await get_voice(text)
    if voice:
        if isinstance(voice, str):
            await speak.finish(voice)
        else:
            await speak.finish(MessageSegment.record(voice))
    else:
        await speak.finish("出错了,请稍后再试")
Exemplo n.º 12
0
func_list = """DD机目前支持的功能有:

  主播列表
  修复配置
  开启权限
  关闭权限
  添加主播 uid
  删除主播 uid
  开启动态 uid
  关闭动态 uid
  开启直播 uid
  关闭直播 uid
  开启at uid
  关闭at uid


命令中的uid需要替换为对应主播的uid,注意是uid不是直播间id

群聊默认开启权限,只有管理员或机器人主人才能触发指令

所有群聊/私聊的推送都是分开的,在哪里添加就只会在哪里推送
"""

help = on_command('帮助', rule=to_me(), priority=5)


@help.handle()
async def _(bot: Bot, event: Event, state: dict):
    await help.finish(func_list)
Exemplo n.º 13
0
from nonebot.rule import to_me
from nonebot.typing import T_State

from .data_source import get_nickname

LuckyKing = on_notice()
"""群红包运气王提醒事件"""


@LuckyKing.handle()
async def handle_first_receive(bot: Bot, event: LuckyKingNotifyEvent, state: T_State):
    rely = f'[CQ:at,qq={event.target_id}]是运气王!\n\t来自{event.user_id}的红包'
    await bot.send(event=event, message=rely)


poke = on_notice(rule=to_me())
"""戳一戳提醒事件"""


@poke.handle()
async def handle_first_receive(bot: Bot, event: PokeNotifyEvent, state: T_State):
    expr_poke = [
        f'[CQ:poke,qq={event.get_user_id()}]',
        '那里不可以!(>﹏<)',
        '再戳就要坏了!',
        '我在!',
        '干嘛!'
    ]
    await bot.send(event=event, message=Message(random.choice(expr_poke)))

from nonebot.adapters import Bot
from nonebot.typing import T_State
from nonebot import on_shell_command
from nonebot.rule import to_me, ArgumentParser

parser = ArgumentParser()
parser.add_argument("-a", action="store_true")

shell = on_shell_command("ls", to_me(), parser=parser)


@shell.handle()
async def _(bot: Bot, state: T_State):
    print(state["argv"])
    print(state["args"])
Exemplo n.º 15
0
from nonebot import on_command
from nonebot.log import logger
from nonebot.rule import to_me
from nonebot.typing import T_State
from nonebot.adapters import Bot, Event
from nonebot.adapters.cqhttp import Message

from .data_source import get_help_data

help = on_command("help", aliases={"帮助"}, rule=to_me(), priority=1)


@help.handle()
async def handle(bot: Bot, event: Event, state: T_State):
    logger.success(f'help: {event}\n')
    data = await get_help_data()
    await help.send(
        Message(
            f'[CQ:share,url={data["url"]},title={data["title"]},content={data["content"]},image={data["image"]}]'
        ))
Exemplo n.º 16
0
        for c in result:
            flag = False
            for sub in config.esport_name:
                if sub in c['contest_name']:
                    flag = True

            if flag:
                msg += f"{c['contest_name']} {c['match_name']}\n" \
                       f"{c['team_a_name']} VS {c['team_b_name']} - {c['start_time']}\n"
    except Exception as e:
        logger.error(f'Error: {type(e)}')

    return msg


esports = on_command("赛程", aliases=set(["esports"]), priority=1, rule=to_me())


@esports.handle()
async def handle(bot: Bot, event: Event, state: T_State):
    args = str(event.get_message()).strip()
    if args:
        state["date"] = args
        logger.debug(args)
    else:
        state["date"] = "0"
        logger.debug("None")


@esports.got("date", prompt="日期")
async def handle_event(bot: Bot, event: Event, state: T_State):
Exemplo n.º 17
0
from nonebot import on_command
from nonebot.matcher import Matcher
from nonebot.permission import SUPERUSER
from nonebot.rule import to_me
from nonebot.typing import T_State
from nonebot.adapters import Bot, Event
from nonebot.adapters.cqhttp import Bot, unescape, MessageEvent, Message, MessageSegment
from nonebot.log import logger

from .prompt import *
from .utils import *
from .alioss import *
from awesome_bot.config.utils import exception_log

# Add To MySQL
add = on_command("add", rule=to_me(), priority=1, permission=SUPERUSER)


@add.handle()
async def handle(bot: Bot, event: Event, state: T_State):
    args = str(event.get_message()).strip()
    if args:
        state["args"] = args


@add.got("args", prompt=ADD_ARGS_PROMPT)
async def handle(bot: Bot, event: Event, state: T_State):
    try:
        user_id = event.get_user_id()
        at_ = "[CQ:at,qq={}]".format(user_id)
        args = str(state["args"]).split()
Exemplo n.º 18
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from nonebot.rule import to_me
from nonebot.typing import Event
from nonebot.plugin import on_command
from nonebot.adapters.cqhttp import Bot

test_command = on_command("帮助", to_me())


@test_command.handle()
async def test_handler(bot: Bot, event: Event, state: dict):
    print("[!] Command:", state["_prefix"])
    args = str(event.message)[len(state["_prefix"]):].strip()
    if args:
        state["help"] = args
    else:
        await bot.send_private_msg(message="命令:\n1. test1\n2. test2",
                                   user_id=event.user_id)


@test_command.got("help", prompt="你要帮助的命令是?")
async def test_handler(bot: Bot, event: Event, state: dict):
    print("[!] Command 帮助:", state["help"])
    if state["help"] not in ["test1", "test2"]:
        await bot.send_private_msg(message=f"{state['help']} 不支持,请重新输入!")
        test_command.reject()
    await bot.send_private_msg(message=f"{state['help']} 帮助:\n...")
Exemplo n.º 19
0
# Author: BeiYu
# Github: https://github.com/beiyuouo
# Date  : 2021/1/14 21:01
# Description:
import httpx
from nonebot import on_command
from nonebot.adapters.cqhttp import Message
from nonebot.rule import to_me
from nonebot.typing import T_State
from nonebot.adapters import Bot, Event
from nonebot.log import logger

setu = on_command("setu",
                  aliases=set(['瑟图', '色图', '来张色图', '来张瑟图']),
                  rule=to_me(),
                  priority=1)


@setu.handle()
async def handle(bot: Bot, event: Event, state: T_State):
    at_ = "[CQ:at,qq={}]".format(event.get_user_id())
    async with httpx.AsyncClient() as client:
        resp = await client.get(
            'https://api.mtyqx.cn/api/random.php?return=json')
        logger.debug(resp.json())
        imgurl = resp.json()['imgurl']
        cqimg = f"[CQ:image,file=1.{imgurl.split('.')[1]},url={imgurl}]"
        await setu.send(Message(at_ + cqimg))
Exemplo n.º 20
0
    stripped_arg = event.raw_message.split()[1:]
    logger.debug(f"{stripped_arg}, {len(stripped_arg)}")
    if len(list(stripped_arg)) < 2:
        await add.finish("输入错误")
        return
    elif stripped_arg[-1] == '帅':
        await add.finish('咕咕鸟从来不骗人, 不能说这句')
        return
    else:
        keyword, sentence = stripped_arg[0], ''.join(
            str(i) for i in stripped_arg[1:])
        await redis_client.sadd(keyword, sentence)
        await add.finish(f"你说: {keyword}, 我说: {sentence}")


del_event = on_command("del", rule=to_me(), priority=5)


@del_event.handle()
async def _(bot: Bot, event: MessageEvent):
    stripped_arg = event.raw_message.split()[1:]
    logger.debug(f"{stripped_arg}, {len(stripped_arg)}")
    if len(stripped_arg) < 2:
        await add.finish("输入错误")
        return
    key, word = stripped_arg[0], stripped_arg[-1]
    res = await redis_client.srem(key, word)
    if res == 1:
        await del_event.finish("如果你不想听我就不说了")
    else:
        await del_event.finish("我可不想忘记[CQ:face,id=14]")
Exemplo n.º 21
0
from nonebot import on_command
from nonebot.log import logger
from nonebot.rule import to_me
from nonebot.typing import T_State
from nonebot.adapters import Bot, Event

from .data_source import get_yourls

yourls = on_command("yourls", aliases={"短链接"}, rule=to_me(), priority=1)


@yourls.handle()
async def handle(bot: Bot, event: Event, state: T_State):
    args = str(event.get_message()).strip()
    logger.success(f'yourls: {event}\n')
    if args:
        state["yourls"] = args


@yourls.got("yourls", prompt="请输入链接")
async def handle_weather_got(bot: Bot, event: Event, state: T_State):
    url = await get_yourls(state['yourls'])
    if url:
        await yourls.send(url)
        # await yourls.send(Message(
        #     f'[CQ:share,url={data["url"]},title={data["title"]},content={data["content"]},image={data["image"]}]'))
    else:
        await yourls.send("转换短链接失败")
Exemplo n.º 22
0
花价

api:jx3box
"""
import httpx
import nonebot
from nonebot import on_command
from nonebot.rule import to_me
from nonebot.typing import T_State
from nonebot.adapters import Bot, Event
import asyncio
import time
import json


flower_price = on_command("花价", rule=to_me(), priority=5)


@flower_price.handle()
async def handle_first_receive(bot: Bot, event: Event, state: T_State):
    args = str(event.get_message()).strip()
    if args:
        if " " in args:  # 首先判断文本中间有没有空格
            arg_list = args.split(' ')
            if len(arg_list) == 2:  # 当参数为两个时,直接执行
                state["server"] = arg_list[0]
                state["flower"] = arg_list[1]
            else:
                await flower_price.finish("参数错误!")
        else:  # 没有空格的话就直接赋值给参数server
            state["server"] = args
Exemplo n.º 23
0
from nonebot import on_command
from nonebot.adapters.cqhttp import Event
from nonebot.adapters.cqhttp import Bot, Message
import time, requests
from nonebot.rule import to_me
weather = on_command("黄历", rule=to_me(), priority=5)


@weather.handle()
async def handle_first_receive(bot: Bot, event: Event, state: dict):
    msg = await xin()
    await weather.send(Message(msg))


async def xin():
    t = time.strftime("%Y-%m-%d", time.localtime())
    url = 'http://v.juhe.cn/laohuangli/d?date=%s&key=300e07021f3c31998962fc0c7ff229d7' % str(
        t)
    d = requests.get(url=url).json()
    yang = '阳历:' + d['result']['yangli']
    yin = '阴历:' + d['result']['yinli']
    wu = '五行:' + d['result']['wuxing']
    chong = '凶煞:' + d['result']['chongsha']
    bai = '拜祭:' + d['result']['baiji']
    j = '吉神:' + d['result']['jishen']
    yi = '宜:' + d['result']['yi']
    xiong = '凶神:' + d['result']['xiongshen']
    ji = '忌:' + d['result']['ji']
    return str(yang + '\n' + yin + '\n' + wu + '\n' + chong + '\n' + bai +
               '\n' + j + '\n' + yi + '\n' + xiong + '\n' + ji)
Exemplo n.º 24
0
            msg.append({"type": "text", "data": {"text": "看在这么惨的份大家让他/她情喝奶茶吧qwq~"}})
        elif x == 5:
            msg.append({"type": "text", "data": {"text": "弱诶!拜托,你很弱诶!你现在知道谁是老大了哦(ФωФ)"}})

    from nonebot import get_bots
    bot_dict = get_bots()
    if not bot_dict.__contains__('2485909839'):
        return
    bot = bot_dict['2485909839']
    await bot.send_group_msg(group_id=864515208, message=msg)


# 游戏开始
blackjack_start = on_command(
    "blackjack_start", aliases={"二十一点", "21点", "来把二十一点", "来把21点", "赌怪", "土块", "我要当赌怪", "我要当土块"},
    permission=group_message, rule=to_me(), priority=5)


@blackjack_start.handle()
async def blackjack_start_response(bot: Bot, event: Event, state: T_State):
    global game_state, game_group_code, player_state, current_player, game_start_time, player_list

    if game_state != 0:
        if (time.time() - game_start_time) < 300:
            await blackjack_start.send('请等这桌结束吧~菜菜也不会分身呢qwq')
            return
        else:
            await blackjack_start.send('虽然菜菜也很想把上一桌主持完,但是上一桌打了五分钟还没结束诶0.0')

    game_state = 1
    game_start_time = time.time()
Exemplo n.º 25
0
from functools import reduce

from nonebot.rule import to_me
from nonebot.plugin import on_command
from nonebot.permission import SUPERUSER
from nonebot.typing import Bot, Event, MessageSegment

say = on_command("say", to_me(), permission=SUPERUSER)


@say.handle()
async def say_unescape(bot: Bot, event: Event, state: dict):
    Message = event.message.__class__

    def _unescape(message: Message, segment: MessageSegment):
        if segment.type == "text":
            return message.append(str(segment))
        return message.append(segment)

    message = reduce(_unescape, event.message, Message())  # type: ignore
    await bot.send(message=message, event=event)


echo = on_command("echo", to_me())


@echo.handle()
async def echo_escape(bot: Bot, event: Event, state: dict):
    # Message = event.message.__class__
    # MessageSegment = event.message[0].__class__
Exemplo n.º 26
0
import re

from nonebot import on_command
from nonebot.adapters.cqhttp import Bot, Event
from nonebot.log import logger
from nonebot.rule import to_me
from bot import config

from ChatBotApi import baiduBot
from ChatBotApi import txbot

ELF_bot = on_command('', rule=to_me(), priority=5)


@ELF_bot.handle()
async def handle_first_receive(bot: Bot, event: Event, state: dict):
    try:
        if event.group_id in config.bangroup:
            return
    except:
        pass
    session = str(event.user_id)
    if event.group_id:
        await ELF_bot.send('说再见结束聊天~')
        pass
    try:
        API_Key = config.baidu_api_key
        Secret_Key = config.baidu_secret_key
        bot_id = config.baidu_bot_id

        if API_Key == None or Secret_Key == None or bot_id == None:
Exemplo n.º 27
0
from nonebot import on_keyword, on_command
from nonebot.typing import T_State
from nonebot.adapters.cqhttp import Message, Bot, Event  # 这两个没用的别删
from nonebot.adapters.cqhttp.message import MessageSegment
import requests
from nonebot.permission import *
from nonebot.rule import to_me
# matcher = on_keyword({"主人"})
matcher = on_command('主人', rule=to_me(), priority=5)


@matcher.handle()
async def _(bot: Bot, event: Event, state: T_State):
    await matcher.send('我主人是川川大帅哥')


test = on_keyword({"test"})


@test.handle()
async def h_r(bot: Bot, event: Event, state: T_State):
    id = str(event.get_user_id())
    # yuyin=f"[CQ:record,file=http://baidu.com/1.mp3]"
    # biaoqing=f"[CQ:face,id=123]"#表情包使用
    # hongbao=f"[CQ:gift,qq={id},id=8]"#礼物使用
    await test.send(MessageSegment.at(id) + '你好帅哥')


test = on_keyword({"礼物", '我要礼物', '我也要礼物'})
# test=on_command('礼物',rule=to_me(),priority=5)
Exemplo n.º 28
0
# Author: BeiYu
# Github: https://github.com/beiyuouo
# Date  : 2021/1/25 17:47
# Description:

import httpx
from nonebot import on_command
from nonebot.adapters.cqhttp import Bot, Event, unescape, Message
from nonebot.permission import SUPERUSER
from nonebot.log import logger
from nonebot.rule import to_me
from nonebot.typing import T_State
from .sql_script import *

souti = on_command("souti", aliases=set(['搜题', '查题']), rule=to_me(), priority=1)
sql = SQL()

@souti.handle()
async def handle(bot: Bot, event: Event, state: T_State):
    args = str(event.get_message()).strip()
    if args:
        state["text"] = args


@souti.got("text", prompt="输入题目")
async def handle(bot: Bot, event: Event, state: T_State):
    args = str(state["text"])
    logger.debug(args)
    db, cursor = await sql.get_connection()
    res = await sql.query_dt(args)
    logger.debug(res)
Exemplo n.º 29
0
from nonebot import on_command
from nonebot.log import logger
from nonebot.rule import to_me
from nonebot.typing import T_State
from nonebot.adapters import Bot, Event
from nonebot.adapters.cqhttp import Message

from .data_source import get_hand_painting

hand_painting = on_command("手绘", rule=to_me(), priority=1)


@hand_painting.handle()
async def handle(bot: Bot, event: Event, state: T_State):
    logger.success(f'hand_painting: {event}\n')


@hand_painting.got("img", prompt="请发送一张图片")
async def handle_hand_painting_got(bot: Bot, event: Event, state: T_State):
    img = Message(state["img"])
    try:
        if img[0].type == "image":
            await hand_painting.send("转化中")
            img_url = await get_hand_painting(img[0].data["url"])
            if img_url is None:
                await hand_painting.send("出错了,请重新开始")
            else:
                await hand_painting.send(Message(f'[CQ:image,file={img_url}]'))
        else:
            await hand_painting.send("这是啥?")
    except:
Exemplo n.º 30
0
from nonebot import on_command
from nonebot.rule import to_me
from nonebot.typing import Bot, Event

weather = on_command("天气", rule=to_me(), priority=1)


@weather.handle()
async def handle_first_receive(bot: Bot, event: Event, state: dict):
    args = str(event.message).strip()  # 首次发送命令时跟随的参数,例:/天气 上海,则args为上海
    print(f"==={args}===")
    if args:
        state["city"] = args  # 如果用户发送了参数则直接赋值


@weather.got("city", prompt="你想查询哪个城市的天气呢?")
async def handle_city(bot: Bot, event: Event, state: dict):
    city = state["city"]
    if city not in ["上海", "北京"]:
        await weather.reject("你想查询的城市暂不支持,请重新输入!")
    # weather = await get_weather_from_xxx(city)
    city_weather = "晴天"
    # await bot.send(city_weather)
    await weather.finish(city_weather)