Exemplo n.º 1
0
def fmt(ls, delimite=10):
    ls_len = len(ls)

    c, i = divmod(ls_len, delimite)
    if i > 0:
        c+=1
    
    if ls_len < delimite:
        range_delimite = ls_len
    else:
        range_delimite = delimite

    output_list = []
    for j in range(range_delimite):
        line = ""
        for i in range(c):
            l = j + delimite * i

            if l >= ls_len:
                break

            line += ls[l] + RText(",  ")

        if j < (range_delimite - 1):
            line = line + RText("\n")

        output_list.append(line)
    return output_list
Exemplo n.º 2
0
def check_rcon(server):

    rcon_result = server.rcon_query(f"list")
    if rcon_result is None:
        prompt = RText("rcon 没有开启, 请分别server.properties, MCDR/config.yml 开启。", RColor.red)
        server.logger.warning(prompt)
        server.say(RText(f"RCON 没有配置成功,请联系服主。", RColor.red))
        return False
Exemplo n.º 3
0
def on_load(server: ServerInterface, prev):
    global data
    data = get_data(DEFAULT_DATA_PATH)
    server.register_help_message(
        DEFAULT_PREFIX,
        RText('将输入的数或表达式转换成ホモ特有表达式').h('表达式参数支持Python格式的四则运算(+-*/)和乘方(**)'))
    server.register_command(
        Literal(DEFAULT_PREFIX).runs(
            lambda src: src.reply(RText('请输入参数以生成表达式!', RColor.red))).then(
                GreedyText('expr').runs(reply)))
Exemplo n.º 4
0
def get_seed(server: ServerInterface) -> RTextBase:
    try:
        seed = server.rcon_query('/seed').split('[')[1].split(']')[0]
        return RTextList(
            RTextTranslation('commands.seed.success'), '[',
            RText(seed,
                  RColor.green).c(RAction.copy_to_clipboard,
                                  seed).h(RTextTranslation('chat.copy.click')),
            ']')
    except Exception:
        warning = RText(
            f'§cPlugin {NAME} §lCANNOT§c get server seed by §lRCON§c, please checkout config of §lMCDR§c!'
        ).c(RAction.open_url, LINK).h(f'§lDocs§r: §n{LINK}§r')
        server.logger.warning(warning.to_plain_text())
        return RText(warning)
Exemplo n.º 5
0
def simple_RText(message, text='', command='', action=RAction.run_command):
    Rtext = RText(message).set_hover_text(text).set_click_event(
        RAction.suggest_command, '')
    if command:
        Rtext.set_click_event(action, command)
    if text:
        Rtext.set_hover_text(text)
    else:
        Rtext.set_hover_text(command)
    return Rtext
Exemplo n.º 6
0
def reply(src: CommandSource, ctx: Dict[Union[str, Any], Union[str, Any]]):
    expr = ctx['expr'].replace('//', '/')
    if not bool(re.search(r'[^\d. (+\-*/)]', expr)):
        try:
            num = eval(expr)  # type: Union[int, float]
            h**o = gen_expr(num)
            src.reply(
                RTextList(
                    RText(re.sub(r'\.0*$', '', str(num)),
                          RColor.gray).c(RAction.copy_to_clipboard,
                                         expr).h(expr), ' = ',
                    RText(h**o).c(RAction.copy_to_clipboard, h**o).h(
                        RTextTranslation('chat.copy.click'))))
        except Exception as e:
            src.get_server().logger.warning(e)
            src.reply(RText('这么恶臭的表达式还有计算的必要吗, 自裁罢(无慈悲', RColor.red))
    else:
        src.reply(RText('参数包含非法字符!', RColor.red))
Exemplo n.º 7
0
def print_config_edit(source: PlayerCommandSource):
    global voting_lock, teamed_players, conf
    timer = conf["timer"]
    timer_len = conf["timer_len"]
    msg = ''
    if not source.player in teamed_players:
        msg = not_start_menu.copy()
    elif voting_lock.locked():
        msg = '§c无法修改游戏配置,请先完成投票:§r\n'
        msg += vote_title + vote_choice_msg
    elif game_status != 'not_start':
        msg = '§c只有游戏未开始时可以修改游戏配置!§r'
    else:
        msg = RTextList(
            RText('  '),
            RText(f'§{"a" if timer else "c"}限时模式§r')
            .h(f'{"§c关闭" if timer else "§a打开"}§r限时模式')
            .c(RAction.run_command, f'{to_all}{Prefix} timer'),
            RText('  '),
            RText('限时时长')
            .h(f'当前 {timer_len}s, 点击切换')
            .c(RAction.suggest_command, f'{to_all}{Prefix} timer 30'),
            RText('    '),
            RText('物品稀有度')
            .h('物品的稀有度分布 <S> <A> <B> <C> <D>,\n要求<S>+<A>+<B>+<C>+<D> = 25')
            .c(RAction.suggest_command, f'{to_all}{Prefix} card 2 6 9 6 2')
        )
    print_msg(source, msg, prefix='')
Exemplo n.º 8
0
def check_level(server, info):
    # 查看玩家的等级够不够
    level = server.rcon_query(f"experience query {info.player} levels")

    l = re.match(f"{info.player} has ([0-9]+) experience levels", level).group(1)

    server.logger.debug(f"玩家 {info.player} 等级: {l}")

    if int(l) < 1:
        server.reply(info, RText("经验不足,至少需要1级", RColor.red))
        return False
    else:
        # 扣掉1级
        server.rcon_query(f"experience add {info.player} -1 levels")
        return True
Exemplo n.º 9
0
def get_list(src: Union[CommandSource, str]):  # 获得玩家列表
    global config
    list_text = ''
    query_result = MultiRcon.get_instance().group_command('list')
    formatters = (
        # <1.16
        # There are 6 of a max 100 players online: 122, abc, xxx, www, QwQ, bot_tob
        r'There are {amount:d} of a max {limit:d} players online:{players}There are {dummy}',
        r'There are {amount:d} of a max {limit:d} players online:{players}',
        # >=1.16
        # There are 1 of a max of 20 players online: Fallen_Breath
        r'There are {amount:d} of a max of {limit:d} players online:{players}There are {dummy}',
        r'There are {amount:d} of a max of {limit:d} players online:{players}',
    )
    for server in query_result:
        list_text += get_server_rtext(server) + ' '

        res = query_result.get(server)
        if res.get('connected'):
            for formatter in formatters:
                parsed = parse.parse(formatter, res['data'])
                if parsed is not None and parsed['players'].startswith(' '):
                    player_number = parsed['amount']
                    players_str = parsed['players'][1:]

                    list_text += RTextList(
                        RText(tr("total_online_num"), color=RColor.gray),
                        RText(' ' + str(player_number), color=RColor.green))
                    if player_number != 0:
                        list_text += RTextList(
                            ' ',
                            RText(tr("online_player_list"), color=RColor.gray),
                            RText(' ' + players_str, RColor.gold))
                    break
            else:
                list_text += RText(tr('unparseable_list'), color=RColor.red)
                src.get_server().as_plugin_server_interface().logger.warning(
                    f"Cant parse text: {res['data']}")
        else:
            list_text += RText(tr('server_stopped'), color=RColor.red)
        list_text += "\n"
    if isinstance(src, str):
        PluginServerInterface.get_instance().tell(src, list_text)
    else:
        src.reply(list_text)
Exemplo n.º 10
0
def get_list():  # 获得玩家列表
    times = 0
    list = ''
    config = get_config()
    number = get_number()
    while times < number:
        server = config[str(times + 1)]
        name = server['name']
        host = server['host']
        port = int(server['port'])
        password = server['password']
        try:
            result = main(host, port, password)
            if result[10] != '0':
                player_list = result[int(result.find(':')) + 1:]
                player_number = result.count(',') + 1
            else:
                player_list = ''
                player_number = 0
            list += RTextList(
                get_server_rtext(name),
                RText(" 在线人数:",color=RColor.gray),
                RText(str(player_number),color=RColor.green)
            )
            if player_number != 0:
                list += RTextList(
                    RText(" 在线列表:",color=RColor.gray),
                    RText(player_list,RColor.gold)
                )
            list += "\n"
        except:
            list += RTextList(
                RText(name,color=RColor.aqua),
                RText(" 未开启\n",color=RColor.red)
            )
        times += 1
    return list
Exemplo n.º 11
0
import json
import re

from mcdreforged.api.types import ServerInterface, CommandSource
from mcdreforged.api.command import Literal, GreedyText
from mcdreforged.api.rtext import RText, RTextTranslation, RTextList, RColor, RAction

PLUGIN_METADATA = {
    'id':
    'homo_calculator',
    'version':
    '1.0.2',
    'name':
    'HomoCalc',
    'description':
    RText('通过 "!!h**o <number>" 命令, 用114514生成ホモ特有表达式').h(
        RText('良い世, 来いよ', RColor.gold)),
    'author': ['Van_Nya'],
    'link':
    'https://github.com/Van-Nya/HomoCalc',
    'dependencies': {
        'mcdreforged': '>=1.0.0',
    }
}

DEFAULT_DATA_PATH = 'config/HomoData.json'
DEFAULT_PREFIX = '!!h**o'
REPO_URL = PLUGIN_METADATA['link']

data = dict()  # type: Dict[str, str]

Exemplo n.º 12
0
def on_load(server: ServerInterface, old):
    register_command(server)
    server.register_help_message(Prefix, RText(
        'bingo游戏菜单').h('点击显示').c(RAction.run_command, Prefix))
Exemplo n.º 13
0
def print_unknown_argument_message(source: CommandSource, error: UnknownArgument):
    print_msg(source, RText('参数错误!请输入§7{}§r以获取插件信息'.format(
        Prefix)).h('点击查看帮助').c(RAction.run_command, Prefix))
Exemplo n.º 14
0
def vote(source: PlayerCommandSource, command):
    global vote_agree_list, vote_disagree_list, voting_lock, vote_title
    if reseting_game_lock.locked():
        print_msg(source, '§c重置游戏中,无法进行投票§r', True)
        return
    elif source.player in spec_players:
        print_msg(source, '§c观察者不能投票§r', True)
        print_msg(source, team_msg)
        return
    elif not source.player in teamed_players:
        print_msg(source, RText('§c加入非观察者队伍才能投票§r \n'), True)
        print_msg(source, team_msg)
        return
    elif command == 'restart' and game_status in ['started', 'to_be_start']:
        print_msg(source,
                  '游戏进行中,点击开启 ' +
                  RText('§6◤§c结束游戏§6◢§r').c(RAction.run_command,
                                            f'{to_all}{Prefix} vote end')
                  + ' 投票')
        return
    else:
        acquire = voting_lock.acquire(blocking=False)
        if not acquire:
            print_msg(source, '§c已有进行中的投票:§r', True)
            print_msg(source, vote_title, True, '')
            print_msg(source, vote_choice_msg, True, '')
            return
        elif acquire:
            vote_agree_list.append(source.player)
            vote_title = f'{source.player} 发起投票:{command}'
            print_msg(source, vote_title+',请在30s内表决', False, '')
            print_msg(source, vote_choice_msg, False, '')
            vote_timer = 0
            server = source.get_server()
            server.execute(
                'bossbar add bingo:vote {"text":"Vote time left:","color":"red"}')
            server.execute('bossbar set bingo:vote color red')
            server.execute('bossbar set bingo:vote style notched_6')
            server.execute('bossbar set bingo:vote max 300')
            server.execute('bossbar set bingo:vote players @a')
            while(vote_timer < 300):
                time.sleep(0.1)
                vote_timer += 1

                server.execute(
                    f'bossbar set bingo:vote value {300 - vote_timer}')
                if len(vote_agree_list) >= len(teamed_players) / 2 \
                        or len(vote_disagree_list) >= len(teamed_players) / 2:
                    break
                elif vote_timer % 10 == 0:
                    server.execute(
                        'bossbar set bingo:vote name {"text":"Vote time left:' + str(300-vote_timer/10)+'s","color":"red"}')
                    if vote_timer % 100 == 0 or vote_timer >= 250:
                        server.say(f'距离投票结束还有{30 - vote_timer / 10}秒')
            server.execute('bossbar remove bingo:vote')
            execute_vote_result(source, command, len(vote_agree_list)
                                >= len(vote_disagree_list), vote_timer >= 300)
            vote_agree_list = []
            vote_disagree_list = []
            vote_title = ''
            voting_lock.release()
Exemplo n.º 15
0
bingo_msg = '''§7-----§6{1}§r V§a{2}§7-----
§6Bingo §7小游戏管理插件
§a!!bg§7 显示快捷控制面板
§e{0}§7 显示这条帮助信息
§e{0} team§7 选择队伍
§e{0} vote§7 进行投票
§e{0} config§7 快捷修改游戏设置
§e{0} mode §7修改游戏模式
§e{0} timer§7 开/关限时模式
§e{0} timer§a [<限时时长>] §7修改限时模式时间,单位:分钟
§e{0} card§7 修改物品稀有度'''.format(Prefix, PLUGIN_METADATA['name'], PLUGIN_METADATA['version'])

to_all = "/all "

team_msg = RTextList(
    RText('§6--------选择队伍---------§r\n'),
    RText('§6◤§c红队§6◢   ').c(RAction.run_command,
                             f'{to_all}{Prefix} team red'),
    RText('§6◤§9蓝队§6◢   ').c(RAction.run_command,
                             f'{to_all}{Prefix} team blue'),
    RText('§6◤§a绿队§6◢ \n').c(RAction.run_command,
                             f'{to_all}{Prefix} team green'),
    RText('§6◤§e黄队§6◢   ').c(RAction.run_command,
                             f'{to_all}{Prefix} team yellow'),
    RText('§6◤§d粉队§6◢   ').c(RAction.run_command,
                             f'{to_all}{Prefix} team pink'),
    RText('§6◤§3天蓝§6◢ \n').c(RAction.run_command,
                             f'{to_all}{Prefix} team aqua'),
    RText('§6◤§7灰队§6◢   ').c(RAction.run_command,
                             f'{to_all}{Prefix} team gray'),
    RText('§6◤§6橙色§6◢   ').c(RAction.run_command,
Exemplo n.º 16
0
def get_server_rtext(name):
    config = get_config()
    if config['click_event']:
        return RText(name,color=RColor.aqua).c(RAction.run_command,f"/server {name}")
    else:
        return RText(name,color=RColor.aqua)