Beispiel #1
0
def execute(inp):
    res = re.search(r"```py(.|\n)*```", inp.content_text)
    if res is None:
        return Out("No syntax found", inp.channel)
    cont = res.group()[5: -3]
    print("executing: " + cont)
    return Out(execute_safe(cont), inp.channel)
Beispiel #2
0
def cah_host(inp):
    global current_cah_game
    current_cah_game = Game(rando=("rando" in inp.args))

    if "full" in inp.args:
        meta_data = current_cah_game.add_libs(get_globals("cah config|full"))
    else:
        meta_data = current_cah_game.add_libs(inp.args[1:])

    if len(current_cah_game._whites_tot) < 1:
        current_cah_game = None
        return Out("No white cards", inp.channel)

    if len(current_cah_game._blacks_tot) < 1:
        current_cah_game = None
        return Out("No black cards", inp.channel)

    current_cah_game.join(inp.author)

    em = discord.Embed(title="New c-a-h game", colour=0x000000)
    em.description = inp.author.display_name + "just created a new \"Cards against Humanity\" game\n\n__Libraries:__"
    for meta_instance in meta_data:
        em.add_field(name=meta_instance["filename"],
                     value=meta_instance["outcome"])
        if meta_instance["outcome"] != "success":
            message = Out(
                meta_instance["outcome"] + ":\n" +
                "\n".join([str(x) for x in meta_instance["errors"]]) +
                "\nin file " + meta_instance["filename"], inp.channel)
            push_message(message)
    em.set_author(name="CaH", icon_url=get_globals("cah config|image url"))
    return Out(em, inp.channel)
Beispiel #3
0
def yt_check(data):
    client = get_globals("client")

    for channel, prev_video in data["youtube_follow_channels"].items():
        # Get newest video
        url = f"https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={channel}&maxResults=1&" \
                "order=date&key=AIzaSyAHpipWEHy1I3YIkdjyPdCsrSzE3hcKXhE"
        rep = requests.get(url)
        print("request yt api", datetime.now().isoformat())
        content_object = json.loads(rep.text)
        if "error" in content_object:
            stderr.write(f"Error {content_object['error']['code']} occurred in 'yt_check' routine:\n"
                         f"{content_object['error']['message']}")
            return

        video = content_object["items"][0]
        video_id = video["id"]["videoId"]

        if video_id != prev_video:
            # Found a new video
            # Display message
            em = discord.Embed(title=f"{video['snippet']['channelTitle']} uploaded a new video", colour=YOUTUBE_RED)\
              .add_field(name=video["snippet"]["title"], value=video["snippet"]["description"], inline=False)\
              .set_author(name="Executer Youtube Division", icon_url=YOUTUBE_IMAGE_URL)

            # Update the database
            current_list = data["youtube_follow_channels"]
            current_list[channel] = video_id
            update_server_data(data["discord_id"], youtube_follow_channels=current_list)

            main_channel = client.get_channel(data["default_channel_id"])
            push_message(Out(em, main_channel))
            push_message(Out("https://www.youtube.com/watch?v=" + video_id, main_channel))
Beispiel #4
0
def cah_join(inp):
    global current_cah_game
    if current_cah_game.game_stat != 0:
        return Out("You cannot join now", inp.channel)

    current_cah_game.join(inp.author)

    em = discord.Embed(title="User Joined", colour=0x20ff1d)
    em.set_thumbnail(url=inp.author.avatar_url)
    em.description = inp.author.display_name + " just joined ..."
    em.set_author(name="CaH", icon_url=CAH_IMAGE_URL)
    # Join a game
    return Out(em, inp.channel)
Beispiel #5
0
def set_default_channel(inp):
    if isinstance(inp.raw_message.channel, (discord.DMChannel, discord.GroupChannel)):
        return Out("Can't perform this command in a private or group channel", inp.channel)
    if len(inp.args) > 1:
        channel_name = inp.args[1]
        server = inp.raw_message.guild
        default_channel = discord.utils.get(server.channels, name=channel_name)
        if default_channel is None:
            return Out(f"No such channel: {inp.args[1]}", inp.channel)
    else:
        default_channel = inp.channel

    update_server_data(inp.channel.guild.id, default_channel_id=default_channel.id)
    return Out(f"Set default channel to {default_channel.name}({default_channel.id})", inp.channel)
Beispiel #6
0
def approves(inp):
    client = get_globals("client")
    em = discord.Embed(title="Executor approval Rating", color=0x51ff00,
                       description=f"{client.user.name} approves :white_check_mark:")
    em.set_author(name=client.user.name, icon_url=client.user.avatar_url)
    em.set_footer(text="determined after long consideration")
    return Out(em, inp.channel)
Beispiel #7
0
def cah_stats(inp):
    global current_cah_game
    em = discord.Embed(title="Game statistics", colour=BLACK)
    for author, points in current_cah_game.stats():
        em.add_field(name=author, value=points, inline=False)
    em.set_author(name="CaH", icon_url=CAH_IMAGE_URL)
    return Out(em, inp.channel)
Beispiel #8
0
def random_sentence(inp):
    category = "lefty_problem"
    if len(inp.args) > 1:
        category = inp.args[1]
    matrix = get_globals("function specific|random_sentence_matrix").get(category, [[""]])
    sentence = " ".join([random.choice(i) for i in matrix])
    return Out(sentence, inp.channel)
Beispiel #9
0
def minesweeper(inp):
    mines = 10 if len(inp.args) < 4 else int(inp.args[3])
    height = 10 if len(inp.args) < 3 else int(inp.args[2])
    width = 10 if len(inp.args) < 2 else int(inp.args[1])
    field_string = f"There are {mines} mines\n"

    mine_matrix = np.zeros((height, width), np.bool)
    for i in range(mines):
        location = (random.randint(0, height - 1), random.randint(0, width - 1))
        while mine_matrix[location[0], location[1]]:
            location = (random.randint(0, height - 1), random.randint(0, width - 1))
        mine_matrix[location[0], location[1]] = True

    for y, row in enumerate(mine_matrix):
        for x, cell in enumerate(row):
            character = ":bomb:"
            if not cell:
                neighbour_bombs = 0
                for n in POSSIBLE_NEIGHBOURS:
                    if 0 <= x + n[0] < width and 0 <= y + n[1] < height:
                        if mine_matrix[y + n[1], x + n[0]]:
                            neighbour_bombs += 1

                character = NUMBER_EMOJIS[neighbour_bombs]
            field_string += "||" + character + "|| "
        field_string += "\n"

    if len(field_string) > 2000:
        field_string = "board contains to much Text. Try a smaller board"

    return Out(field_string, inp.channel)
Beispiel #10
0
def brain_fuck(inp):
    # TBD
    command, arguments = inp.args[1:2]
    arguments = list(arguments)
    command = list(command)
    ram = []
    ram_pos = 0
    outp = ""
    bracket_pos_stack = []
    i = 0
    while i < len(command):
        if i == '.':
            outp += chr(ram[ram_pos])
        if i == ',':
            ram[ram_pos] = ord(arguments.pop(0))
        if i == '>':
            ram_pos += 1
        if i == '<':
            ram_pos -= 1
        if i == '+':
            ram[ram_pos] += 1
        if i == '-':
            ram[ram_pos] -= 1
        if i == '[':
            bracket_pos_stack.append(i)
        if i == ']':
            if ram[ram_pos] == 0:
                i = bracket_pos_stack[-1]
            else:
                bracket_pos_stack.pop()
        i += 1
    return Out(outp, inp.channel)
Beispiel #11
0
def help_(inp):
    em = discord.Embed(title="Bot Help", color=0xFCDE53)
    for name, i in get_globals("response_dict").items():
        show_state = i["maintenance state"] != FunctionMaintenanceState.FUNCTIONAL
        description = i["description"] + (": " + i["maintenance state"].__str__() if show_state else "")
        em.add_field(name="%" + name, value=description, inline=True)
    return Out(em, inp.channel)
Beispiel #12
0
def add_youtube_channel(inp):
    # Get channel
    url = f"https://www.googleapis.com/youtube/v3/search?part=snippet&type=channel" \
          f"&order=relevance&q={inp.content_text}&key=AIzaSyAHpipWEHy1I3YIkdjyPdCsrSzE3hcKXhE"
    channel_content = json.loads(requests.get(url).text)["items"][0]
    channel_id = channel_content["id"]["channelId"]

    # Get the video
    url = f"https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={channel_id}&maxResults=1&" \
          "order=date&key=AIzaSyAHpipWEHy1I3YIkdjyPdCsrSzE3hcKXhE"
    rep = requests.get(url)
    video_content = json.loads(rep.text)["items"][0]
    video_id = video_content["id"]["videoId"]

    # Write embed
    ch_name = channel_content["snippet"]["title"]
    em = discord.Embed(title="Added youtube channel", colour=YOUTUBE_RED, 
                       description=f"Posts a notification every time {ch_name} uploads a video in the main channel")\
                .add_field(name="Channel", value=ch_name, inline=False)\
                .add_field(name="Current last video", value=video_content["snippet"]["title"], inline=False)\
                .set_image(url=video_content["snippet"]["thumbnails"]["medium"]["url"])\
                .set_thumbnail(url=channel_content["snippet"]["thumbnails"]["medium"]["url"])\
                .set_footer(text=f"For removal type %yt_rmv_channel {ch_name}")\
                .set_author(name="Executer Youtube Division", icon_url=YOUTUBE_IMAGE_URL)

    # Update database
    current_list = inp.data["server data"]["youtube_follow_channels"]
    current_list[channel_id] = video_id
    update_server_data(inp.channel.guild.id, youtube_follow_channels=current_list)

    return Out(em, inp.channel)
Beispiel #13
0
def cah_play(inp):
    global current_cah_game
    if any([re.match(r"^\w*\d$", x) is None for x in inp.args[1:]]):
        return Out("All arguments must be positive integers between 0 and 9",
                   inp.channel)

    if current_cah_game.game_stat != 1:
        return Out("You cannot play now", inp.channel)

    if len(inp.args) - 1 != current_cah_game.cards_needed:
        return Out(
            "You have to play exactly {} cards".format(
                current_cah_game.cards_needed), inp.channel)

    if current_cah_game.tsar.discord_implement == inp.author:
        return Out("The tsar cannot play", inp.channel)

    push_message(
        Out(
            current_cah_game.lay_card(inp.author.display_name,
                                      [int(x) for x in inp.args[1:]]),
            inp.channel))
    if current_cah_game.all_played:
        em = discord.Embed(title="The Cards are laid out", colour=BLACK)
        em.description = current_cah_game.show()
        em.set_author(name="CaH", icon_url=CAH_IMAGE_URL)
        push_message(Out(em, inp.channel))

    cards_em = discord.Embed(title="White Cards", colour=WHITE)
    cards_em.description = current_cah_game.get_player(
        inp.author.display_name).get_cards()
    cards_em.set_author(name="CaH", icon_url=CAH_IMAGE_URL)
    return Out(cards_em, inp.author)
Beispiel #14
0
def cah_leave(inp):
    global current_cah_game
    current_cah_game.leave(inp.author)

    em = discord.Embed(title="User Left", colour=0xa305d5)
    em.set_thumbnail(url=inp.author.avatar_url)
    em.description = author_ment + " just left ..."
    em.set_author(name="CaH", icon_url=CAH_IMAGE_URL)
    return Out(em, inp.channel)
Beispiel #15
0
def cah_end(inp):
    global current_cah_game
    push_message(cah_stats(inp))

    current_cah_game = None
    em = discord.Embed(title="Game Finished", colour=0xff1c1d)
    em.description = "The game has just been finished"
    em.set_author(name="CaH", icon_url=CAH_IMAGE_URL)
    # Finish the game
    return Out(em, inp.channel)
Beispiel #16
0
def get_latest(inp):
    # Get channel
    url = f"https://www.googleapis.com/youtube/v3/search?part=snippet&type=channel" \
          f"&order=relevance&q={inp.content_text}&key=AIzaSyAHpipWEHy1I3YIkdjyPdCsrSzE3hcKXhE"
    content = json.loads(requests.get(url).text)
    channel_id = content["items"][0]["id"]["channelId"]

    # Get the video
    url = f"https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={channel_id}&maxResults=1&" \
          "order=date&key=AIzaSyAHpipWEHy1I3YIkdjyPdCsrSzE3hcKXhE"
    rep = requests.get(url)
    content = json.loads(rep.text)
    video_url = "https://www.youtube.com/watch?v=" + content["items"][0]["id"]["videoId"]

    em = discord.Embed(title=content["items"][0]["snippet"]["title"], colour=YOUTUBE_RED)
    em = _add_yt_video(em, content["items"][0])
    em.set_author(name="Executer Youtube Division", icon_url=YOUTUBE_IMAGE_URL)
    push_message(Out(em, inp.channel))
    return Out(video_url, inp.channel)
Beispiel #17
0
def cah_choose(inp):
    global current_cah_game
    if current_cah_game.tsar.discord_implement != inp.author:
        return Out("Only the tsar can choose", inp.channel)

    if current_cah_game.game_stat != 2:
        return Out("You cannot choose right now", inp.channel)

    try:
        player_chosen = int(inp.args[1])
    except ValueError:
        return Out(inp.author.mention() + "player must be an integer",
                   inp.channel)
    if player_chosen >= current_cah_game.player_num - 1:
        return Out(
            inp.author.mention() +
            "player must be a number between 0 and {}".format(
                current_cah_game.player_num - 2), inp.channel)
    return Out(current_cah_game.choose(player_chosen), inp.channel)
Beispiel #18
0
def search_youtube(inp):
    number = 1
    url = f"https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults={number}" \
          f"&order=relevance&q={inp.content_text}&key=AIzaSyAHpipWEHy1I3YIkdjyPdCsrSzE3hcKXhE"
    rep = requests.get(url)
    content = json.loads(rep.text)
    for i in range(number):
        em = discord.Embed(title=content["items"][0]["snippet"]["title"], colour=YOUTUBE_RED)
        em = _add_yt_video(em, content["items"][0])
        push_message(Out(em, inp.channel))
    return None
Beispiel #19
0
def gather_initiative(inp):
    def get_user_name(i):
        user = inp.guild.get_member(i)
        if user is None:
            return "NULL"
        else:
            return user.display_name

    ids_sorted = sorted(last_dice_rolls.items(), key=lambda x: x[1], reverse=True)
    users_sorted = [(get_user_name(t[0]), t[1]) for t in ids_sorted]

    em = discord.Embed(title="Initiative", colour=0xf0f000)
    if len(users_sorted) > 0:
        res_string = "\n".join([f"{t[1]}\t{t[0]}" for t in users_sorted])
        for t in users_sorted:
            em.add_field(name=t[0], value=t[1], inline=False)
        push_message(Out("Copyable text: \n```" + res_string + "```", inp.author))
    else:
        em.description = "Noone rolled yet"
    return Out(em, inp.channel)
Beispiel #20
0
def cah_close_host(inp):
    global current_cah_game
    if current_cah_game.game_stat != 0:
        return Out("Host already closed", inp.channel)

    if current_cah_game.tsar.discord_implement != inp.author:
        return Out("You cannot close the host", inp.channel)

    push_message(Out(current_cah_game.close_joining(), inp.channel))

    em = discord.Embed(title="Game Start", colour=BLACK)
    em.description = "Nobody can join now anymore"
    em.set_author(name="CaH", icon_url=CAH_IMAGE_URL)
    # Close the joining
    for player in current_cah_game.player_list:
        cards_em = discord.Embed(title="White Cards", colour=WHITE)
        cards_em.description = player.get_cards()
        cards_em.set_author(name="CaH", icon_url=CAH_IMAGE_URL)
        push_message(Out(cards_em, player.discord_implement))

    return Out(em, inp.channel)
Beispiel #21
0
def msg(inp):
    message_text = "Content: {} \n".format(inp.content_text)
    length = max(len(message_text), 18) - 1

    em = discord.Embed(title="+++Incoming Transmission+++\n" + "+" * length + "\n", colour=inp.author.color)
    em.description = message_text
    url = inp.author.avatar_url
    if url == "":
        url = inp.author.default_avatar_url
    em.set_author(name="-Signed, " + inp.author.display_name, icon_url=url)
    em.set_footer(text="+++Transmission ends+++")
    return Out(em, inp.channel)
Beispiel #22
0
def spam(inp):
    spam_max = inp.data["data"]["general"]
    txt = "spam"
    times = 3
    args = inp.args[1:]
    if len(args) == 1:
        if isint(args[0]):
            times = int(args[0])
    if len(args) > 1:
        if isint(args[0]):
            times = int(args[0])
            txt = " ".join(args[1:])
        else:
            txt = " ".join(args)
    output_txt = "\n".join([txt] * min(times, spam_max)) + ("\nOk, I'm bored now" if times > spam_max else "")
    return Out(output_txt, inp.channel)
Beispiel #23
0
def cah_random(inp):
    global current_cah_game
    if current_cah_game is None:
        current_cah_game = Game()
        current_cah_game.add_libs(["cah_lib"])
    return Out(current_cah_game.random(), inp.channel)
Beispiel #24
0
def my_permissions(inp):
    return Out("".join([perm[0] + "\n" if perm[1] else "" for perm in inp.channel.permissions_for(inp.author)]),
               inp.channel)
Beispiel #25
0
def infinite_loop(inp):
    return Out("%!inf_blink", inp.channel)
Beispiel #26
0
def shutup(inp):
    return Out("---", inp.channel)
Beispiel #27
0
def test_message(inp):
    return Out("args = {}:\n\nkwargs = {}".format("\n".join(inp.args), "\n".join([key + " : " + value for key, value in
                                                                                  inp.kwargs.items()])), inp.channel)
Beispiel #28
0
def copycat(inp):
    return Out(" ".join(inp.args[1:]), inp.channel)
Beispiel #29
0
def dice_legacy(inp: ResponseInput):
    return Out(legacy(inp.args, inp.author.id), inp.channel)
Beispiel #30
0
def reload_data(inp):
    reload()
    return Out("Reload sucessfully", inp.channel)