Esempio n. 1
0
def moveback():
    if isfile(project_config_file) and isfile(
            library_config_file) and getmtime(library_config_file) == getmtime(
                project_config_file):
        print('config file did not change')
        return
    print(f"[WARN] copy to {project_config_file}")
    copy2(src=library_config_file, dst=project_config_file)
Esempio n. 2
0
    def step_request_command(msg: discord.Message):
        print("Requested Command:", proposed_cmd)

        dir_path = helpers.dir_path + "/server_proposed_actions"
        if not os.path.exists(dir_path):
            os.mkdir(dir_path)

        dir_path += "/" + str(msg.channel.guild.id)
        if not os.path.exists(dir_path):
            os.mkdir(dir_path)

        command_template = f'''
import discord
from helpers import get_gif

commands = ["{proposed_cmd['proposed_command_name']}"]
requires_mention = False
accepts_mention = {'{Pings}' in proposed_cmd['response_description_ping']}
description = "{proposed_cmd['proposed_command_name']} by {proposed_cmd['proposed_command_author']}"


async def execute(message):
    gif = get_gif("{proposed_cmd['proposed_command_gif']}", lmt=25, pos=0, wo_anime=True)

    embed = discord.Embed()
    if accepts_mention:
        if len(message.mentions) == 1:
            # 1 mention
            embed.description = f"{proposed_cmd['response_description_ping'].replace('{Pings}', '{message.mentions[0].mention}').replace('{Author}', '{message.author.mention}')}"
        elif len(message.mentions) > 1:
            # > 1 mentions
            embed.description = f"{proposed_cmd['response_description_ping'].replace('{Pings}', "{', '.join([x.mention for x in message.mentions])}").replace('{Author}', '{message.author.mention}')}"
        else:
            # 0 mentions
            embed.description = f"{proposed_cmd['response_description'].replace('{Author}', '{message.author.mention}')}"
    else:
        embed.description = f"{proposed_cmd['response_description'].replace('{Author}', '{message.author.mention}')}"

    embed.set_footer(text="Ein Befehl von {proposed_cmd['proposed_command_author']}", icon_url="{proposed_cmd['proposed_command_author_icon']}")
    embed.set_image(url=gif)
    await message.channel.send(embed=embed)
'''
        save_author_name = re.sub(r'[\\/*?:"<>|]', '',
                                  proposed_cmd['proposed_command_author'])
        save_command_name = re.sub(r'[\\/*?:"<>|]', '',
                                   proposed_cmd['proposed_command_name'])

        author_path = dir_path + "/" + save_author_name
        if not os.path.exists(author_path):
            os.mkdir(author_path)

        f = open(author_path + "/" + save_command_name + ".py", "w")
        f.write(command_template)
        f.flush()
        f.close()
        return 1
Esempio n. 3
0
def main(argv):
    exclusive_kill()
    serial_instance = open_port(get_port_number_from_first_arg(argv))
    if serial_instance is None:
        do_exit(1)
    r = flash(serial_instance, '--force' in argv, False)
    if not r:
        print("刷机失败")
        return
    serial_instance.baudrate = 115200
    print("切换到串口输出,请等待程序解压缩……")
    term(serial_instance)
async def execute(message):
    params = ('roll', 25, 0, True)
    gif = get_gif(*params)
    while gif in blacklist:
        print("skipping role gif", blacklist.index(gif))
        gif = get_gif(*params)

    embed = discord.Embed()

    if len(message.mentions) == 0:
        msg = '{} rollt durch die Gegend'.format(message.author.mention)
    else:
        msg = '{} rollt gegen {}'.format(message.author.mention,
                                         message.mentions[0].mention)
    embed.description = msg
    embed.set_image(url=gif)
    await message.channel.send(embed=embed)
Esempio n. 5
0
async def on_ready():
    print(f"[{Fore.MAGENTA}{'System':20}{Fore.RESET}] Started")
    print(f"[{Fore.MAGENTA}{'System':20}{Fore.RESET}] Name:", client.user.name)
    print(f"[{Fore.MAGENTA}{'System':20}{Fore.RESET}] Id:", client.user.id)
    print(
        f"[{Fore.MAGENTA}{'System':20}{Fore.RESET}] Current guilds (max 25):",
        [x["name"] for x in await client.fetch_guilds().get_guilds(25)])

    await client.change_presence(activity=discord.Activity(
        type=discord.ActivityType.watching, name='+help'))
Esempio n. 6
0
def main(argv):
    from os.path import join, dirname

    action = argv[0]
    argv = argv[1:]

    handler = loadJob(action)
    if handler is None:
        print("action not found: " + action)
        Usage(True)

    if not isdir(BIN_PATH):
        mkdir(BIN_PATH)

    if not isdir(SELF_BIN_PATH):
        mkdir(SELF_BIN_PATH)

    handler(argv)
    do_exit(0)
async def execute(message):
    command, channel, params, mentions, author = parse(message)
    mention_strings = [m.mention for m in mentions]
    actual_params = []
    for param in params:
        if param not in mention_strings:
            actual_params.append(param)
    print("Params", params, "|", mention_strings, "=>", actual_params)
    if len(actual_params) == 0:
        gif = get_islieb()
    else:
        gif = get_islieb(' '.join(actual_params))

    file = discord.File(dir_path + "/assets/islieb/" + gif, filename=gif)
    embed = discord.Embed()
    if len(message.mentions) != 0:
        embed.description = 'Eine Comic für {}!'.format(message.mentions[0].mention)
    embed.set_image(url="attachment://" + gif)
    await message.channel.send(file=file, embed=embed)
Esempio n. 8
0
def term(serial_instance):
    encoding = 'Latin1'

    if not hasattr(serial_instance, 'cancel_read'):
        # enable timeout for alive flag polling if cancel_read is not available
        serial_instance.timeout = 1
    serial_instance.write_timeout = None

    serial_instance.baudrate = 115200

    miniterm = Miniterm(serial_instance, echo=False, eol='lf')
    miniterm.raw = True
    miniterm.set_rx_encoding(encoding)
    miniterm.set_tx_encoding(encoding)

    print(
        '--- Miniterm on {p.name}  {p.baudrate},{p.bytesize},{p.parity},{p.stopbits} ---\n'
        .format(p=miniterm.serial))
    print('--- Quit: {} | Menu: {} | Help: {} followed by {} ---\n'.format(
        key_description(miniterm.exit_character),
        key_description(miniterm.menu_character),
        key_description(miniterm.menu_character), key_description('\x08')))

    miniterm.start()
    try:
        miniterm.join(True)
    except KeyboardInterrupt:
        pass
    print('\n--- exit ---\n')
    miniterm.join()
    miniterm.close()
Esempio n. 9
0
async def on_guild_join(guild):
    print("Joined guild", guild)
async def execute(message):
    command, channel, params, mentions, author = parse(message)
    mention_strings = [m.mention for m in mentions]
    actual_params = []
    for param in params:
        if param not in mention_strings:
            actual_params.append(param)
    print("Params", params, "|", mention_strings, "=>", actual_params)
    if len(actual_params) == 0:
        await message.channel.send("Aus welchem Sub-Reddit? :O")
        return

    response = requests.get(
        f'https://www.reddit.com/r/{actual_params[0]}/randomrising.json?obey_over18=true',
        headers=reddit_headers)
    if response.status_code != 200:
        print("response.status_code != 200")
        await message.channel.send(
            f"AHHHHHHHHH, IRGENDWAS ist kaputt gegangen! o.O\n(Error Code: RED{response.status_code})"
        )
        return
    try:
        response_json = response.json()
        children = response_json["data"]["children"]
        for c in [x["data"] for x in children]:
            print(c)
            try:
                if c["over_18"] or c["url"] is None or "preview" not in c:
                    print(c["over_18"], "|", c["url"] is None, "|", "preview"
                          not in c)
                    continue
            except Exception as ex:
                print("Exception in if", ex)
                continue
            e = discord.Embed()
            e.title = c["title"]
            if c["selftext"] is not None:
                e.description = c["selftext"]
            img_url = c["preview"]["images"][0]["source"]["url"].replace(
                "&amp;s", "&s")
            e.set_image(url=img_url)
            print(c["permalink"])
            e.url = "https://www.reddit.com/" + c["permalink"]
            e.set_footer(
                text=
                f'🔼 {c["ups"]} | 🔽 {c["downs"]} | 💬 {c["num_comments"]}'
            )
            print("=>", img_url)
            await message.channel.send(embed=e)
            return
        await message.channel.send(
            f"AHHHHHHHHH, IRGENDWAS ist kaputt gegangen! o.O\n(Error Code: RED0NC)"
        )
        return
    except Exception as ex:
        print(str(ex))
        await message.channel.send(
            "AHHHHHHHHH, IRGENDWAS ist kaputt gegangen! o.O\n(Error Code: RED123123)"
        )
        return
Esempio n. 11
0
    action = argv[0]
    argv = argv[1:]

    handler = loadJob(action)
    if handler is None:
        print("action not found: " + action)
        Usage(True)

    if not isdir(BIN_PATH):
        mkdir(BIN_PATH)

    if not isdir(SELF_BIN_PATH):
        mkdir(SELF_BIN_PATH)

    handler(argv)
    do_exit(0)


if len(argv) == 1:
    Usage(True)
try:
    main(argv[1:])
except KeyboardInterrupt:
    print('\r^C')
except SystemExit as e:
    exit(e.code)
except:
    traceback.print_exc()
    do_exit(1)
Esempio n. 12
0
def main(argv):
    argv.append(f"--sconstruct={join(SELF_ROOT, 'SConstruct')}")
    if '--verbose' not in argv:
        if '-j' not in argv and len(
            [i for i in argv if i.startswith('--jobs')]) == 0:
            import multiprocessing
            argv.append(f'--jobs={multiprocessing.cpu_count()}')

    environ['GCC_COLORS'] = ':'.join(GCC_COLORS)
    environ['GCC_URLS'] = 'st'
    environ['PROJECT_ROOT'] = PROJECT_ROOT
    environ['BINARY_NAME'] = BINARY_NAME
    set_env_if_not('BUILD_ENV')
    if set_env_if_not('GCC_OPT', required=False) is None:
        environ['GCC_OPT'] = '2'

    if set_env_if_not('RTT_ROOT', global_store=True, required=False) is None:
        rtt_root = join(ENV_ROOT, 'rt-thread-src')
        if isdir(rtt_root):
            environ['RTT_ROOT'] = rtt_root
        else:
            die("missing rt-thread source code. use './control.py rtt update'."
                )

    gcc_bin = set_env_if_not('RTT_EXEC_PATH', global_store=True)
    gcc_exec = 'arm-none-eabi-gcc'
    if not isfile(join(gcc_bin, gcc_exec)):
        if isfile(join(gcc_bin, 'bin', gcc_exec)):
            environ['RTT_EXEC_PATH'] = join(gcc_bin, 'bin')
        else:
            die(f"missing arm gcc binary (in {gcc_bin})\n\nplease download one from {ARM_GCC_DOWNLOAD_URL}."
                )

    rtconfig_file = join(SELF_ROOT, 'rtconfig.h')
    if not isfile(rtconfig_file):
        with open(rtconfig_file, 'wt') as f:
            f.write('#pragma once')

    rtconfig_project_file = join(PROJECT_ROOT, 'rtconfig_project.h')
    if not isfile(rtconfig_project_file):
        with open(rtconfig_project_file, 'wt') as f:
            f.write('#pragma once\n\n// place custom config here')

    is_menuconfig = ('--menuconfig' in argv) or ('--pyconfig' in argv)
    if is_menuconfig:
        copy_config()
    elif isfile(project_config_file):
        if md5_file(project_config_file) != get_last_hash():
            print(
                "config changed, updateing rtconfig.h. project will full rebuild."
            )
            exec_pass('scons', [f'--useconfig={project_config_file}'],
                      cwd=SELF_ROOT)
            write_last_hash(project_config_file)
    else:
        die("you have never run '\x1B[38;5;14m./control.py config\x1B[0m', no way to compile."
            )

    exec_pass('scons', argv, cwd=SELF_ROOT)

    if is_menuconfig:
        if moveback():
            exec_pass('scons', [f'--useconfig={project_config_file}'],
                      cwd=SELF_ROOT)

    print("\x1B[38;5;10mscons success.\x1B[0m")
    cdb_file = join(SELF_ROOT, '.vscode/compile_commands.json')
    if isfile(cdb_file):
        dst = join(PROJECT_ROOT, '.vscode/compile_commands.json')
        print(f"copy cdb file to {dst}")
        copy2(src=cdb_file, dst=dst)
        remove(cdb_file)
Esempio n. 13
0
async def on_member_ban(guild, user):
    print("Guild", guild, "banned", user)
Esempio n. 14
0
async def on_guild_update(old_guild, new_guild):
    print("Guild was updated", old_guild, "=>", new_guild)
Esempio n. 15
0
def main(argv):
    if not isfile(BIN_FILE):
        die(f"application not compiled. (missing {BIN_FILE})")

    if not isfile(VERSION_FILE):
        print(
            f'version file did not exists, create one with v0.0.0. ({VERSION_FILE})'
        )
        f = open(VERSION_FILE, 'wt')
        f.write('0.0.0')
        f.close()

    runMakeImg = load_wm_module('makeimg').main
    runMakeImgFls = load_wm_module('makeimg_fls').main

    python_pass([tools_path('wm_gzip.py'), BIN_FILE])

    eval_pass(runMakeImg, [
        BIN_FILE + '.gz', IMG_FILE, '0', '1', VERSION_FILE, '90000', '10100',
        BIN_FILE
    ], 'makeimg')
    print()
    eval_pass(runMakeImgFls, [tools_path('secboot.img'), IMG_FILE, FLS_FILE],
              'makeimg_fls')
    print()

    size = Path(BIN_FILE).stat().st_size
    size_k = ceil(size / 1000)
    if size > 0x808FFFF - 0x8010100:
        print(
            f"\x1B[38;5;9mbin file size: {size} bytes ({size_k}kb) > {0x808FFFF - 0x8010100}\x1B[0m"
        )
    else:
        print(f"bin file size: {size} bytes ({size_k}kb)")

    with open(IMG_FILE + '.md5',
              'rt+' if isfile(IMG_FILE + '.md5') else 'wt+') as f:
        f.seek(0)
        old_hash = f.read().strip()
        new_hash = md5_file(IMG_FILE)
        print("Output file hash: %s" % (new_hash))
        if old_hash != new_hash:
            f.seek(0)
            f.truncate()
            f.write(new_hash)
            f.flush()
            if isfile(FLASH_SIGNAL):
                remove(FLASH_SIGNAL)

    print("Done.")
Esempio n. 16
0
from helpers import print
from app import app, db
from app.models import AccountModel, GoogleAccountModel, UserModel
import config
import os


@app.shell_context_processor
def make_shell_context():
    return {
        'db': db,
        'UserModel': UserModel,
        'AccountModel': AccountModel,
        'GoogleAccountModel': GoogleAccountModel
    }


if __name__ == '__main__':
    print("application.py")
    if not os.path.exists(os.path.join(config.basedir, 'app.db')):
        print("Creating the database...")
        db.create_all()

    app.run(host='0.0.0.0', port=80, debug=True, threaded=False)
from colorama import Fore
import os
import importlib.util
from helpers import print


print(f"[{Fore.MAGENTA}{'System':20}{Fore.RESET}] Reloading actions")

actions = []
command_actions = {}

dir_path = os.path.dirname(os.path.realpath(__file__))
for itm in sorted(os.listdir(dir_path)):
    if itm.startswith("__"):
        continue
    # print("Loading", itm)
    try:
        spec = importlib.util.spec_from_file_location(itm, dir_path + "/" + itm)
        loaded_module = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(loaded_module)
        actions.append(loaded_module)
        for command in loaded_module.commands:
            command_actions[command] = loaded_module
    except Exception as e:
        print("Exception on load of", itm, "->", e)
Esempio n. 18
0
def flash(serial_port, force, low_speed):
    # init
    stat_image_file = stat(IMG_FILE)
    p_bar = ProgBar(stat_image_file.st_size)

    def clear_buffer():
        serial_port.reset_output_buffer()
        serial_port.reset_input_buffer()

    def read_with_bar(data, timeout=0):
        return serial_port.read(data)

    def write_with_bar(data, timeout=0):
        write_with_bar.current += len(data)
        p_bar.title = "%d / %d" % (write_with_bar.current,
                                   stat_image_file.st_size)
        p_bar.update(len(data))
        ret = serial_port.write(data)
        sleep(0.001)
        return ret

    write_with_bar.current = 0

    # go to flash
    mode = goto_flash_mode(serial_port)
    if mode == False:
        return False

    if mode == 'C':
        image_file = IMG_FILE

        mac = ''
        get_mac_cmd = bytes.fromhex('210600ea2d38000000')
        serial_port.timeout = 3
        sleep(0.1)
        serial_port.write(get_mac_cmd)
        mac = (serial_port.read_until())
        pos = mac.find(b'MAC:')
        if pos >= 0:
            mac = mac[pos + 4:len(mac) - 1].decode("ascii")

            print('MAC Address: %s' % mac)

            if isfile(FLASH_SIGNAL) and not force:
                with open(FLASH_SIGNAL, 'rt') as f:
                    if f.read().strip() == mac:
                        print(
                            "this device already flash this program! skip flash. (--force to overwrite)"
                        )
                        clear_buffer()
                        control_reset(serial_port)
                        return True
        else:
            print(
                'bootloader not response MAC address, seems level 1 running.')
            mode = 'P'

    if mode == 'P':
        image_file = FLS_FILE

    # up speed
    def switch_baudrate(br):
        clear_buffer()
        serial_port.baudrate = br

    if not low_speed:
        print('switching to 2M baudrate...')
        sleep(0.2)
        speed_magic = bytes.fromhex('210a00ef2a3100000080841e00')
        serial_port.write(speed_magic)
        sleep(0.01)
        switch_baudrate(2000000)
        serial_port.timeout = 0.3
        sleep(0.01)
        wront_cnt = 0
        while True:
            c_in = serial_port.read(1)
            # print('got: "%s"' % c_in)
            if c_in == b'C' or c_in == b'P':
                break
            if c_in == b'\x00':
                continue
            elif wront_cnt >= 10:
                print('retry...')
                wront_cnt = 0
                switch_baudrate(115200)
                serial_port.write(speed_magic)
                switch_baudrate(2000000)
                sleep(0.01)
            else:
                wront_cnt += 1
        print('high speed mode!')
    serial_port.timeout = None

    print('sending file:', image_file)
    stream = open(image_file, 'rb')

    clear_buffer()
    modem = XMODEM(getc=read_with_bar, putc=write_with_bar)
    print("please wait for download....")
    result = modem.send(stream)
    print('')
    if result:
        print("download image success!")
        if mode == 'C':
            with open(FLASH_SIGNAL, 'wt') as f:
                f.write(mac)
        else:
            control_reset(serial_port)
    else:
        print("download image fail!")
        return False

    stream.close()

    clear_buffer()
    return True
Esempio n. 19
0
async def on_guild_remove(guild):
    print("Left guild", guild)
Esempio n. 20
0
async def execute(message, client):
    proposed_cmd = {}

    def get_status():
        return f"Status: ```" \
               f"\nName / Befehl:                  {proposed_cmd.get('proposed_command_name', 'None')}" \
               f"\nAlternative Befehle / Aliases:  {', '.join(proposed_cmd.get('proposed_command_aliases', [])) if proposed_cmd.get('proposed_command_aliases', []) != [] and proposed_cmd.get('proposed_command_aliases', []) is not None else 'None'}" \
               f"\n" \
               f"\nAntwort Gif:                    {proposed_cmd.get('proposed_command_gif', 'None')}" \
               f"\nAntwort Text (ohne Ping):       {proposed_cmd.get('response_description', 'None') if proposed_cmd.get('response_description', 'None') is not None else 'None'}" \
               f"\nAntwort Text (mit Ping):        {proposed_cmd.get('response_description_ping', 'None') if proposed_cmd.get('response_description_ping', 'None') is not None else 'None'}" \
               f"\n" \
               f"\nAuthor:                         {proposed_cmd.get('proposed_command_author')}" \
               f"\n```"

    def step_name(msg: discord.Message):
        proposed_cmd['proposed_command_name'] = msg.content
        proposed_cmd[
            'proposed_command_author'] = msg.author.name + "#" + msg.author.discriminator
        proposed_cmd['proposed_command_author_icon'] = str(
            msg.author.avatar_url)
        return 1

    def step_aliases(msg):
        proposed_cmd['proposed_command_aliases'] = ([
            x.replace(" ", "") for x in msg.content.split(",")
        ] if msg.content != 'None' else None)
        return 1

    def step_gif(msg):
        proposed_cmd['proposed_command_gif'] = msg.content
        return 1

    def step_description_no_ping(msg):
        proposed_cmd['response_description'] = (
            msg.content if msg.content != 'None' else None)
        return 1

    def step_description_ping(msg):
        proposed_cmd['response_description_ping'] = (
            msg.content if msg.content != 'None' else None)
        return 1

    def step_request_command(msg: discord.Message):
        print("Requested Command:", proposed_cmd)

        dir_path = helpers.dir_path + "/server_proposed_actions"
        if not os.path.exists(dir_path):
            os.mkdir(dir_path)

        dir_path += "/" + str(msg.channel.guild.id)
        if not os.path.exists(dir_path):
            os.mkdir(dir_path)

        command_template = f'''
import discord
from helpers import get_gif

commands = ["{proposed_cmd['proposed_command_name']}"]
requires_mention = False
accepts_mention = {'{Pings}' in proposed_cmd['response_description_ping']}
description = "{proposed_cmd['proposed_command_name']} by {proposed_cmd['proposed_command_author']}"


async def execute(message):
    gif = get_gif("{proposed_cmd['proposed_command_gif']}", lmt=25, pos=0, wo_anime=True)

    embed = discord.Embed()
    if accepts_mention:
        if len(message.mentions) == 1:
            # 1 mention
            embed.description = f"{proposed_cmd['response_description_ping'].replace('{Pings}', '{message.mentions[0].mention}').replace('{Author}', '{message.author.mention}')}"
        elif len(message.mentions) > 1:
            # > 1 mentions
            embed.description = f"{proposed_cmd['response_description_ping'].replace('{Pings}', "{', '.join([x.mention for x in message.mentions])}").replace('{Author}', '{message.author.mention}')}"
        else:
            # 0 mentions
            embed.description = f"{proposed_cmd['response_description'].replace('{Author}', '{message.author.mention}')}"
    else:
        embed.description = f"{proposed_cmd['response_description'].replace('{Author}', '{message.author.mention}')}"

    embed.set_footer(text="Ein Befehl von {proposed_cmd['proposed_command_author']}", icon_url="{proposed_cmd['proposed_command_author_icon']}")
    embed.set_image(url=gif)
    await message.channel.send(embed=embed)
'''
        save_author_name = re.sub(r'[\\/*?:"<>|]', '',
                                  proposed_cmd['proposed_command_author'])
        save_command_name = re.sub(r'[\\/*?:"<>|]', '',
                                   proposed_cmd['proposed_command_name'])

        author_path = dir_path + "/" + save_author_name
        if not os.path.exists(author_path):
            os.mkdir(author_path)

        f = open(author_path + "/" + save_command_name + ".py", "w")
        f.write(command_template)
        f.flush()
        f.close()
        return 1

    menu_steps = [
        lambda: MenuStep(
            "Befehl erstellen",
            "Erstelle deinen eigenen kleinen Befehl für den Bot!\n(Für komplexere Befehle ping mich einfach :D)\n\nSende den **Namen** deines Befehls um fortzufahren\nSende **Cancel** um das Menü zu verlassen",
            'Ein Bot von Vincent#0212',
            'https://avatars0.githubusercontent.com/u/26576880?s=60&v=4',
            step_name),
        lambda: MenuStep(
            "Befehl erstellen",
            get_status() + f"\n"
            f"\nSende **Alternative Befehle / Aliases (durch Kommata getrennt)** deines Befehls um fortzufahren"
            f"\nSende **None** um keine Alternativen Befehle zu registrieren"
            f"\nSende **Cancel** um das Menü zu verlassen und den Befehl zu verwerfen",
            'Ein Bot von Vincent#0212',
            'https://avatars0.githubusercontent.com/u/26576880?s=60&v=4',
            step_aliases),
        lambda: MenuStep(
            "Befehl erstellen",
            get_status() + f"\n"
            f"\nSende den **Suchterm für das Gif** deines Befehls um fortzufahren"
            f"\nSende **Cancel** um das Menü zu verlassen und den Befehl zu verwerfen",
            'Ein Bot von Vincent#0212',
            'https://avatars0.githubusercontent.com/u/26576880?s=60&v=4',
            step_gif),
        lambda: MenuStep(
            "Befehl erstellen",
            get_status() + f"\n"
            f"\nSende den **Text für die Antwort wenn *keine* Nutzer gepingt werden** deines Befehlsum fortzufahren"
            f"\nVerwende um den Author einzubinden {{Author}}"
            f"\nSende **None** um keinen Text anzugeben"
            f"\nSende **Cancel** um das Menü zu verlassen und den Befehl zu verwerfen",
            'Ein Bot von Vincent#0212',
            'https://avatars0.githubusercontent.com/u/26576880?s=60&v=4',
            step_description_no_ping),
        lambda: MenuStep(
            "Befehl erstellen",
            get_status() + f"\n"
            f"\nSende den **Text für die Antwort wenn Nutzer gepingt werden** deines Befehlsum fortzufahren"
            f"\nVerwende um den Author einzubinden {{Author}} und den/die gepingten Nutzer einzubinden {{Pings}}"
            f"\nSende **None** um keinen Text anzugeben"
            f"\nSende **Cancel** um das Menü zu verlassen und den Befehl zu verwerfen",
            'Ein Bot von Vincent#0212',
            'https://avatars0.githubusercontent.com/u/26576880?s=60&v=4',
            step_description_ping),
        lambda: MenuStep(
            "Befehl erstellen",
            get_status() + f"\n"
            f"\nBitte Bestätige den Befehl mit **Ok**"
            f"\nSende **Cancel** um das Menü zu verlassen und den Befehl zu verwerfen",
            'Ein Bot von Vincent#0212',
            'https://avatars0.githubusercontent.com/u/26576880?s=60&v=4',
            step_request_command), lambda: MenuStep(
                "Befehl erstellen",
                get_status() + f"\n"
                f"\nBefehl wird angefragt - bitte habe etwas Geduld.",
                'Ein Bot von Vincent#0212',
                'https://avatars0.githubusercontent.com/u/26576880?s=60&v=4',
                lambda: None,
                wait_for_response=False)
    ]

    t_out = 60.0
    menu_idx = 0

    while True:
        print("Sending Menu item", menu_idx)
        current_step = menu_steps[menu_idx]()
        await current_step.send(message.channel)

        if not current_step.wait_for_response:
            return

        def response_check(msg):
            return msg.channel == message.channel.original and msg.author.mention == message.author.mention

        try:
            response_msg = await client.wait_for('message',
                                                 timeout=t_out,
                                                 check=response_check)
            print("Waiting for Response (Timeout: " + str(t_out) + ")")
        except asyncio.TimeoutError:
            print("No Response (Timeout)")
            await message.channel.send("Keine Antwort - Cancelled.")
            return
        else:
            print("Response: " + response_msg.content)
            if response_msg.content.lower() == 'cancel':
                await message.channel.send("Cancelled.")
                print("Cancelled")
                return

            resp = current_step.on_next(response_msg)
            if resp == 'Cancel':
                print("Ended")
                return

            menu_idx += resp
Esempio n. 21
0
async def on_message(message: discord.Message):
    if message.author == client.user:
        return

    if not message.content.startswith(prefix) or len(message.content) < 1:
        return

    command, channel, params, mentions, author = parse(message)
    if dev_mode:
        importlib.reload(actions)

    if command in get_server_actions(channel.guild.id)[0].keys():
        print(
            f"[{Fore.LIGHTBLUE_EX}{message.guild.name:20}{Fore.RESET}] Executing Server Command {command} {author.name}#{author.discriminator}: \"{message.content}\""
        )

        class ChannelWrapper:
            def __init__(self, original):
                self.original = original

            async def send(self,
                           content=None,
                           *,
                           tts=False,
                           embed: discord.Embed = None,
                           file=None,
                           files=None,
                           delete_after=None,
                           nonce=None):
                if embed is not None:
                    embed.colour = discord.Colour.from_rgb(156, 52, 137)
                return await self.original.send(content=content,
                                                tts=tts,
                                                embed=embed,
                                                file=file,
                                                files=files,
                                                delete_after=delete_after,
                                                nonce=nonce)

        message.channel = ChannelWrapper(message.channel)
        await get_server_actions(channel.guild.id)[0][command].execute(message)

    elif command in actions.command_actions.keys():
        print(
            f"[{Fore.LIGHTBLUE_EX}{message.guild.name:20}{Fore.RESET}] Executing {command} {author.name}#{author.discriminator}: \"{message.content}\""
        )

        if command in actions.readme.commands:
            print(
                f"[{Fore.MAGENTA}{'System':20}{Fore.RESET}] Sending readme ({len(actions.actions)} actions)"
            )
            inline = True
            if len(params) != 0:
                if params[0] == '0' or params[0] == 'short':
                    inline = True
                elif params[0] == '1' or params[0] == 'long':
                    inline = False

            embed = discord.Embed()
            embed.title = f"Liste der Befehle 1/{math.ceil(len(actions.actions) / 24)}"
            embed.description = 'Prefix: ' + prefix
            itr = 0
            page_itr = 1
            for action in actions.actions:
                cmd_append = ""
                if 'readme' in action.commands:
                    cmd_append = " [Optional: Stil 0 (Default) / 1]"
                elif action.requires_mention:
                    cmd_append = " [Person]"
                elif action.accepts_mention:
                    cmd_append = " [Optional: Person]"
                joined_commands = ' / '.join(action.commands)
                joined_commands = (
                    joined_commands[:50] +
                    '..') if len(joined_commands) > 75 else joined_commands
                embed.add_field(name='**' + joined_commands + cmd_append +
                                '**',
                                value=action.description,
                                inline=inline)
                itr += 1
                if itr == 24:
                    page_itr += 1
                    print(f"Sending \"{embed.title}\"")
                    await channel.send(embed=embed)
                    embed = discord.Embed()
                    embed.title = f"Liste der Befehle {page_itr}/{math.ceil(len(actions.actions) / 24)}"
                    embed.description = 'Prefix: ' + prefix
                    itr = 0
            if len(embed.fields) != 0:
                print(f"Sending \"{embed.title}\"")
                await channel.send(embed=embed)

        elif command in actions.settings.commands:
            print("Sending settings:", params)
            if len(params) > 0:
                pass
            else:
                await channel.send("Coming soon™")
                # embed = discord.Embed()
                # embed.title = "Mögliche Einstellungen"
                # embed.description = 'Prefix: ' + prefix + 'settings [Einstellung]'
                # for setting_name in actions.settings.settings:
                #     embed.add_field(name='**' + ' / '.join(setting_name) + '**', value=actions.settings.settings[setting_name])
                # await channel.send(embed=embed)
        elif command in actions.propose_command.commands:

            class ChannelWrapper:
                def __init__(self, original):
                    self.original = original

                async def send(self,
                               content=None,
                               *,
                               tts=False,
                               embed: discord.Embed = None,
                               file=None,
                               files=None,
                               delete_after=None,
                               nonce=None):
                    if embed is not None:
                        embed.colour = discord.Colour.from_rgb(156, 52, 137)
                    return await self.original.send(content=content,
                                                    tts=tts,
                                                    embed=embed,
                                                    file=file,
                                                    files=files,
                                                    delete_after=delete_after,
                                                    nonce=nonce)

            message.channel = ChannelWrapper(message.channel)
            await actions.command_actions[command].execute(message, client)

        else:

            class ChannelWrapper:
                def __init__(self, original):
                    self.original = original

                async def send(self,
                               content=None,
                               *,
                               tts=False,
                               embed: discord.Embed = None,
                               file=None,
                               files=None,
                               delete_after=None,
                               nonce=None):
                    if embed is not None:
                        embed.colour = discord.Colour.from_rgb(156, 52, 137)
                    return await self.original.send(content=content,
                                                    tts=tts,
                                                    embed=embed,
                                                    file=file,
                                                    files=files,
                                                    delete_after=delete_after,
                                                    nonce=nonce)

            message.channel = ChannelWrapper(message.channel)
            await actions.command_actions[command].execute(message)
Esempio n. 22
0
def copy_config():
    if isfile(project_config_file):
        print(f"[WARN] copy to {library_config_file}")
        copy2(src=project_config_file, dst=library_config_file)