Пример #1
0
def join(bot: DeltaBot, payload: str, message: Message,
         replies: Replies) -> None:
    """Join the given IRC channel."""
    sender = message.get_sender_contact()
    if not payload:
        replies.add(text="Wrong syntax")
        return
    if not bot.is_admin(sender.addr) and \
       not db.is_whitelisted(payload):
        replies.add(text="That channel isn't in the whitelist")
        return

    g = bot.get_chat(db.get_chat(payload))
    if g and sender in g.get_contacts():
        replies.add(text='You are already a member of this group', chat=g)
        return
    if g is None:
        chat = bot.create_group(payload, [sender])
        db.add_channel(payload, chat.id)
        irc_bridge.join_channel(payload)
        irc_bridge.preactor.join_channel(sender.addr, payload)
    else:
        _add_contact(g, sender)
        chat = bot.get_chat(sender)

    nick = db.get_nick(sender.addr)
    text = '** You joined {} as {}'.format(payload, nick)
    replies.add(text=text, chat=chat)
Пример #2
0
def c4_play(bot: DeltaBot, payload: str, message: Message, replies: Replies) -> None:
    """Invite a friend to play Connect4.

    Example: `/c4_play [email protected]`
    """
    if not payload:
        replies.add(text="Missing address")
        return

    if payload == bot.self_contact.addr:
        replies.add(text="Sorry, I don't want to play")
        return

    p1 = message.get_sender_contact().addr
    p2 = payload
    if p1 == p2:
        replies.add(text="You can't play with yourself")
        return

    g = db.get_game_by_players(p1, p2)

    if g is None:  # first time playing with p2
        chat = bot.create_group(
            '4️⃣ {} 🆚 {} [c4]'.format(p1, p2), [p1, p2])
        b = Board()
        db.add_game(p1, p2, chat.id, b.export(), p1)
        text = 'Hello {1},\nYou have been invited by {0} to play Connect4'
        text += '\n\n{2}: {0}\n{3}: {1}\n\n'
        text = text.format(
            p1, p2, b.get_disc(BLACK), b.get_disc(WHITE))
        replies.add(text=text + _run_turn(chat.id), chat=chat)
    else:
        text = 'You already have a game group with {}'.format(p2)
        replies.add(text=text, chat=bot.get_chat(g['gid']))
Пример #3
0
def lines_play(bot: DeltaBot, message: Message, replies: Replies) -> None:
    """Start a new Color Lines game.

    Example: `/lines_play`
    """
    player = message.get_sender_contact()
    if not db.get_nick(player.addr):
        text = "You need to set a nick before start playing,"
        text += " send /lines_nick Your Nick"
        replies.add(text=text)
        return
    game = db.get_game_by_addr(player.addr)

    if game is None:  # create a new chat
        chat = bot.create_group('🌈 Color Lines', [player.addr])
        db.add_game(player.addr, chat.id, Board().export())
        text = 'Hello {}, in this group you can play Color Lines.\n\n'
        replies.add(text=text.format(player.name) + _run_turn(chat.id),
                    chat=chat)
    else:
        db.set_board(game['addr'], Board(old_score=game['score']).export())
        if message.chat.id == game['gid']:
            chat = message.chat
        else:
            chat = bot.get_chat(game['gid'])
        replies.add(text='Game started!\n\n' + _run_turn(game['gid']),
                    chat=chat)
Пример #4
0
def feed_sub(bot: DeltaBot, payload: str, message: Message,
             replies: Replies) -> None:
    """Subscribe current chat to the given feed.
    """
    url = db.normalize_url(payload)
    feed = db.get_feed(url)

    if feed:
        d = feedparser.parse(feed['url'])
    else:
        max_fc = int(_getdefault(bot, 'max_feed_count'))
        if 0 <= max_fc <= len(db.get_feeds()):
            replies.add(text='Sorry, maximum number of feeds reached')
            return
        d = feedparser.parse(url)
        bozo_exception = d.get('bozo_exception', '')
        if (d.get('bozo') == 1 and not isinstance(
                bozo_exception, CharacterEncodingOverride)) or not d.entries:
            replies.add(text='Invalid feed url: {}'.format(url))
            bot.logger.warning('Invalid feed %s: %s', url, bozo_exception)
            return
        feed = dict(
            url=url,
            etag=d.get('etag'),
            modified=d.get('modified') or d.get('updated'),
            latest=get_latest_date(d.entries),
        )
        db.add_feed(url, feed['etag'], feed['modified'], feed['latest'])
    assert feed

    if message.chat.is_group():
        chat = message.chat
    else:
        chat = bot.create_group(
            d.feed.get('title') or url, [message.get_sender_contact()])

    if chat.id in db.get_fchats(feed['url']):
        replies.add(text='Chat alredy subscribed to that feed.', chat=chat)
        return

    db.add_fchat(chat.id, feed['url'])
    title = d.feed.get('title') or '-'
    desc = d.feed.get('description') or '-'
    text = 'Title: {}\n\nURL: {}\n\nDescription: {}'.format(
        title, feed['url'], desc)

    if d.entries and feed['latest']:
        latest = tuple(map(int, feed['latest'].split()))
        html = format_entries(get_old_entries(d.entries, latest)[:5])
        replies.add(text=text, html=html, chat=chat)
    else:
        replies.add(text=text, chat=chat)
Пример #5
0
def cmd_chan(bot: DeltaBot, payload: str, message: Message,
             replies: Replies) -> None:
    """Create a new channel with the given name.
    """
    if not payload:
        replies.add(text='❌ You must provide a channel name')
        return
    if db.get_channel_by_name(payload):
        replies.add(text='❌ There is already a channel with that name')
        return
    g = bot.create_group(payload, [message.get_sender_contact()])
    db.add_channel(payload, None, g.id)
    replies.add(text='✔️Channel created', chat=g)
Пример #6
0
def group_join(bot: DeltaBot, args: list, message: Message,
               replies: Replies) -> None:
    """Join the given group/channel.
    """
    sender = message.get_sender_contact()
    is_admin = bot.is_admin(sender.addr)
    text = '{}\n\n{}\n\n⬅️ /group_remove_{}'
    arg = args[0] if args else ''
    if arg.startswith('g'):
        gid = int(arg[1:])
        gr = db.get_group(gid)
        if gr:
            g = bot.get_chat(gr['id'])
            contacts = g.get_contacts()
            if sender in contacts:
                replies.add(
                    text='❌ {}, you are already a member of this group'.format(
                        sender.addr),
                    chat=g)
            elif len(contacts) < int(_getdefault(
                    bot, 'max_group_size')) or is_admin:
                _add_contact(g, sender)
                replies.add(chat=bot.get_chat(sender),
                            text=text.format(g.get_name(), gr['topic'] or '-',
                                             arg))
            else:
                replies.add(text='❌ Group is full')
            return
    elif arg.startswith('c'):
        gid = int(arg[1:])
        ch = db.get_channel_by_id(gid)
        if ch:
            for g in _get_cchats(bot, ch['id'], include_admin=True):
                if sender in g.get_contacts():
                    replies.add(
                        text='❌ {}, you are already a member of this channel'.
                        format(sender.addr),
                        chat=g)
                    return
            g = bot.create_group(ch['name'], [sender])
            db.add_cchat(g.id, ch['id'])
            img = bot.get_chat(ch['id']).get_profile_image()
            if img:
                g.set_profile_image(img)
            replies.add(text=text.format(ch['name'], ch['topic'] or '-', arg),
                        chat=g)
            return

    replies.add(text='❌ Invalid ID')
Пример #7
0
def cmd_login(bot: DeltaBot, payload: str, message: Message, replies: Replies) -> None:
    """Login to your WriteFreely instance.

    Example: `/wf_login https://write.as YourUser YourPassword` or
    `/wf_login https://write.as YourToken`
    """
    sender = message.get_sender_contact()
    args = payload.split(maxsplit=2)
    if len(args) == 3:
        client = wf.client(host=args[0], user=args[1], password=args[2])
    else:
        client = wf.client(host=args[0], token=args[1])
    db.add_account(sender.addr, client.host, client.token)
    for blog in client.get_collections():
        g = bot.create_group(
            '{} [WF]'.format(blog['title'] or blog['alias']), [sender])
        db.add_chat(g.id, blog['alias'], sender.addr)
        replies.add(text='All messages sent here will be published to'
                    ' blog:\nAlias: {}\nDescription: {}'.format(
                        blog['alias'], blog['description']), chat=g)
    replies.add(text='✔️Logged in')
Пример #8
0
def chr_play(payload: str, message: Message, bot: DeltaBot,
             replies: Replies) -> None:
    """Invite a friend to play Chain Reaction.

    Example: `/chr_play [email protected]`
    """
    if not payload:
        replies.add(text="Missing address")
        return

    if payload == bot.self_contact.addr:
        replies.add(text="Sorry, I don't want to play")
        return

    player1 = message.get_sender_contact()
    player2 = bot.get_contact(payload)
    if player1 == player2:
        replies.add(text="You can't play with yourself")
        return

    game = DBASE.get_game_by_players(player1.addr, player2.addr)

    if game is None:  # first time playing with player2
        board = Board()
        chat = bot.create_group(
            '🧬 {} 🆚 {} [ChainReaction]'.format(player1.addr, player2.addr),
            [player1, player2])
        DBASE.add_game(player1.addr, player2.addr, chat.id,
                       Board().export(), player1.addr)
        text = 'Hello {1},' \
               'You have been invited by {0} to play Chain Reaction'
        text += '\n\n{2}: {0}\n{3}: {1}\n\n'
        text = text.format(player1.name,
                           player2.name, board.get_orb(Atom.BLACK),
                           board.get_orb(Atom.WHITE))
        replies.add(text=text + _run_turn(chat.id, DBASE, bot), chat=chat)
    else:
        text = 'You already have a game group with {}'.format(player2.name)
        replies.add(text=text, chat=bot.get_chat(game['gid']))
Пример #9
0
def chess_play(bot: DeltaBot, payload: str, message: Message,
               replies: Replies) -> None:
    """Invite a friend to play Chess.

    Example: `/chess_play [email protected]`
    To move use Standard Algebraic Notation or Long Algebraic Notation
    (without hyphens), more info in Wikipedia.
    For example, to move pawn from e2 to e4, send a message: e4 or: e2e4,
    to move knight from g1 to f3, send a message: Nf3 or: g1f3
    """
    if not payload:
        replies.add(text="Missing address")
        return

    if payload == bot.self_contact.addr:
        replies.add(text="Sorry, I don't want to play")
        return

    p1 = message.get_sender_contact().addr
    p2 = payload
    if p1 == p2:
        replies.add(text="You can't play with yourself")
        return

    g = db.get_game_by_players(p1, p2)

    if g is None:  # first time playing with p2
        chat = bot.create_group('♞ {} 🆚 {} [Chess]'.format(p1, p2), [p1, p2])
        b = chgame.Board(p1=p1, p2=p2, theme=int(_getdefault(bot, 'theme')))
        db.add_game(p1, p2, chat.id, b.export())
        text = 'Hello {1},\nYou have been invited by {0} to play Chess'
        text += '\n\n{2} White: {0}\n{3} Black: {1}\n\n'
        text = text.format(p1, p2, b.theme['P'], b.theme['p'])
        text += _run_turn(bot, chat.id)
        replies.add(text=text, chat=chat)
    else:
        text = 'You already have a game group with {}'.format(p2)
        replies.add(text=text, chat=bot.get_chat(g['gid']))
Пример #10
0
def sudoku_play(bot: DeltaBot, message: Message, replies: Replies) -> None:
    """Start a new Sudoku game.

    Example: `/sudoku_play`
    """
    player = message.get_sender_contact()
    game = db.get_game_by_addr(player.addr)

    if game is None:  # make a new chat
        b = Board()
        chat = bot.create_group('#️⃣ Sudoku', [player.addr])
        db.add_game(player.addr, chat.id, b.export(), time.time())
        text = 'Hello {}, in this group you can play Sudoku.\n\n'.format(
            player.name)
        replies.add(text=text + _run_turn(chat.id), chat=chat)
    else:
        db.set_game(game['addr'], Board().export(), time.time())
        if message.chat.id == game['gid']:
            chat = message.chat
        else:
            chat = bot.get_chat(game['gid'])
        replies.add(
            text='Game started!\n\n' + _run_turn(game['gid']), chat=chat)
Пример #11
0
def checkers_play(bot: DeltaBot, payload: str, message: Message,
                  replies: Replies) -> None:
    """Invite a friend to play Checkers.

    Example: `/checkers_play [email protected]`
    """
    if not payload:
        replies.add(text="Missing address")
        return

    if payload == bot.self_contact.addr:
        replies.add(text="Sorry, I don't want to play")
        return

    player1 = message.get_sender_contact().addr
    player2 = payload
    if player1 == player2:
        replies.add(text="You can't play with yourself")
        return

    game = DBASE.get_game_by_players(player1, player2)

    if game is None:  # first time playing with player2
        board = Board()
        chat = bot.create_group(
            '🔴 {} 🆚 {} [checkers]'.format(player1, player2),
            [player1, player2])
        DBASE.add_game(player1, player2, chat.id, board.export(), player1)
        text = 'Hello {1},\nYou have been invited by {0} to play Checkers'
        text += '\n\n{2}: {0}\n{3}: {1}\n\n'
        text = text.format(player1, player2, board.get_disc(BLACK),
                           board.get_disc(WHITE))
        replies.add(text=text + _run_turn(chat.id), chat=chat)
    else:
        text = 'You already have a game group with {}'.format(player2)
        replies.add(text=text, chat=bot.get_chat(game['gid']))