Ejemplo n.º 1
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)
Ejemplo n.º 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']))
Ejemplo n.º 3
0
def _run_turn(gid: int, db: DBManager, bot: DeltaBot) -> str:
    game = db.get_game_by_gid(gid)
    if not game:
        return 'This is not your game group'
    if not game['board']:
        return 'There is no game running'
    board = Board(game['board'])
    b_orb = board.get_orb(Atom.BLACK)
    w_orb = board.get_orb(Atom.WHITE)
    result = board.result()
    pboard = '{}\n\n{} {} – {} {}'.format(board, b_orb, result[Atom.BLACK],
                                          result[Atom.WHITE], w_orb)
    if 0 in result.values() and not board.fist_round:
        db.set_board(game['p1'], game['p2'], None)
        if result[Atom.WHITE] == 0:
            winner = '{} {}'.format(board.get_orb(Atom.BLACK),
                                    bot.get_contact(game['black']).name)
        else:
            player2 = game['p2'] if game['black'] == game['p1'] else game['p1']
            winner = '{} {}'.format(board.get_orb(Atom.WHITE),
                                    bot.get_contact(player2).name)
        text = '🏆 Game over.\n{} Wins!!!\n\n{}'.format(winner, pboard)
        text += '\n\n▶️ Play again? /chr_new'
    else:
        if board.turn == Atom.BLACK:
            turn = bot.get_contact(game['black']).name
        else:
            turn = bot.get_contact(game['p2'] if game['black'] ==
                                   game['p1'] else game['p1']).name
        text = "{} {} it's your turn...\n\n{}".format(
            board.get_orb(board.turn), turn, pboard)
    return text
Ejemplo n.º 4
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)
Ejemplo n.º 5
0
def filter_messages(bot: DeltaBot, message: Message, replies: Replies) -> None:
    """Process turns in Exquisite Corpse game groups
    """
    if not message.chat.is_group():
        sender = message.get_sender_contact()
        g = db.get_game_by_turn(sender.addr)

        if g is None:
            return

        if len(message.text.split()) < 10:
            text = '❌ Text too short. Send a message with at least 10 words'
            replies.add(text=text)
        else:
            paragraph = g['text'] + ' ' + message.text
            db.set_text(g['gid'], paragraph)

            p = db.get_player_by_addr(sender.addr)
            assert p is not None
            if p['round'] == 3:
                db.delete_player(p['addr'])
            else:
                db.set_player(p['addr'], p['round'] + 1, g['gid'])

            p = _get_by_round(g['gid'])

            if p is None:  # End Game
                text = _end_game(g['gid'])
                replies.add(text=text, chat=bot.get_chat(g['gid']))
            else:
                db.set_turn(g['gid'], p['addr'])
                _run_turn(bot, p, bot.get_chat(g['gid']), paragraph)
Ejemplo n.º 6
0
def filter_messages(bot: DeltaBot, message: Message, replies: Replies) -> None:
    """Detect messages like +1 or -1 to increase/decrease score.
    """
    if not message.quote:
        return
    score = _parse(message.text)
    if not score:
        return
    sender = message.get_sender_contact().addr
    is_admin = bot.is_admin(sender)
    if score < 0 and not is_admin:
        return
    if not is_admin and db.get_score(sender) - score < 0:
        replies.add(text="❌ You can't give what you don't have...",
                    quote=message)
        return
    receiver = message.quote.get_sender_contact().addr
    if sender == receiver:
        return

    sender_score = _add_score(sender, -score)
    receiver_score = _add_score(receiver, score)
    if is_admin:
        text = '{0}: {1}{4}'
    else:
        text = '{0}: {1}{4}\n{2}: {3}{4}'
    text = text.format(
        bot.get_contact(receiver).name, receiver_score,
        bot.get_contact(sender).name, sender_score,
        _getdefault(bot, 'score_badge'))
    replies.add(text=text, quote=message)
Ejemplo n.º 7
0
def poll_end(bot: DeltaBot, args: str, message: Message,
             replies: Replies) -> None:
    """Close the poll with the given id."""
    if args:
        addr = message.get_sender_contact().addr
        try:
            with session_scope() as session:
                poll = session.query(Poll).filter_by(id=int(args[0]),
                                                     addr=addr).one()
                text, html = _format_poll(bot, poll, closed=True)
                addresses = set(vote.addr for vote in poll.votes)
                session.delete(poll)
            addresses.add(addr)
            for addr in addresses:
                contact = bot.get_contact(addr)
                if not contact.is_blocked():
                    replies.add(text=text,
                                html=html,
                                chat=bot.get_chat(contact))
        except NoResultFound:
            replies.add(text="❌ Invalid poll",
                        quote=message,
                        chat=message.get_sender_chat())
    else:
        replies.add(text="❌ Invalid poll",
                    quote=message,
                    chat=message.get_sender_chat())
Ejemplo n.º 8
0
def filter_messages(bot: DeltaBot, message: Message, replies: Replies) -> None:
    """Detect messages like +1 or -1 to increase/decrease score."""
    if message.quote:
        receiver_addr = message.quote.get_sender_contact().addr
        score = _parse(message.text)
    else:
        args = message.text.split(maxsplit=2)
        if len(args) == 2 and "@" in args[0]:
            receiver_addr = args[0]
            score = _parse(args[1])
        else:
            score = 0
    if not score:
        return
    sender_addr = message.get_sender_contact().addr
    is_admin = bot.is_admin(sender_addr)
    if (score < 0 and not is_admin) or sender_addr == receiver_addr:
        return

    with session_scope() as session:
        sender = session.query(User).filter_by(addr=sender_addr).first()
        if not sender:
            sender = User(addr=sender_addr)
            session.add(sender)
        if not is_admin and sender.score - score < 0:
            replies.add(text="❌ You can't give what you don't have...",
                        quote=message)
            return

        if not is_admin:
            sender.score -= score
        sender_score = sender.score

        receiver = session.query(User).filter_by(addr=receiver_addr).first()
        if not receiver:
            receiver = User(addr=receiver_addr)
            session.add(receiver)

        receiver.score += score
        receiver_score = receiver.score

    if is_admin:
        text = "{0}: {1}{4}"
    else:
        text = "{0}: {1}{4}\n{2}: {3}{4}"
    text = text.format(
        bot.get_contact(receiver_addr).name,
        receiver_score,
        bot.get_contact(sender_addr).name,
        sender_score,
        _getdefault(bot, "score_badge"),
    )
    replies.add(text=text, quote=message)
Ejemplo n.º 9
0
def group_adminchan(bot: DeltaBot, args: list, message: Message,
                    replies: Replies) -> None:
    """Join the admin group of the given channel.
    """
    ch = db.get_channel_by_id(int(args[0]))
    if ch:
        sender = message.get_sender_contact()
        _add_contact(bot.get_chat(ch['admin']), sender)
        text = '{}\n\n{}'.format(ch['name'], ch['topic'] or '-')
        replies.add(text=text, chat=bot.get_chat(sender))
    else:
        replies.add(text='❌ Invalid ID')
Ejemplo n.º 10
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')
Ejemplo n.º 11
0
def friends_profile(bot: DeltaBot, payload: str, message: Message, replies: Replies) -> None:
    """See the biography of the given address or your own in no address provided.
    """
    if payload.isnumeric():
        contact = bot.get_contact(int(payload))
    elif '@' not in payload:
        contact = message.get_sender_contact()
    else:
        contact = bot.get_contact(payload)
    bio = db.get_bio(contact.addr)
    if bio is None:
        replies.add(text='No biography found for {}'.format(contact.addr))
    else:
        replies.add(filename=contact.get_profile_image(),
                    text='{}:\n{}'.format(contact.addr, bio))
Ejemplo n.º 12
0
def _run_turn(bot: DeltaBot, player: sqlite3.Row, group: Chat,
              paragraph: str) -> None:
    contact = bot.get_contact(player['addr'])
    text = ec + "⏳ Round {}/3\n\n{}, it's your turn...".format(
        player['round'], contact.name)
    group.send_text(text)

    if paragraph:
        text = ec + '📝 Complete the phrase:\n...{}\n\n'.format(' '.join(
            paragraph.rsplit(maxsplit=5)[-5:]))
    else:
        text = '📝 You are the first!\nSend a message with at least 10 words.'
        text = ec + text

    bot.get_chat(contact).send_text(text)
Ejemplo n.º 13
0
def poll_get(bot: DeltaBot, payload: str, message: Message,
             replies: Replies) -> None:
    """Get poll with given id.
    """
    args = payload.split()
    if len(args) not in (1, 2):
        replies.add(text='Invalid syntax')
        return
    if len(args) == 2:
        chat = bot.get_chat(int(args[0]))
        payload = args[1]
        if message.get_sender_contact() not in chat.get_contacts():
            replies.add(text='You are not a member of that group')
            return
    else:
        chat = message.chat

    pid = int(payload)
    poll = db.get_gpoll_by_id(pid)
    if poll and chat.id == poll['gid']:
        closed = poll['status'] == Status.CLOSED
        replies.add(text=format_gpoll(poll, closed=closed))
    elif len(args) == 1:
        poll = db.get_poll_by_id(pid)
        if poll:
            closed = poll['status'] == Status.CLOSED
            replies.add(text=_format_poll(bot, poll, closed=closed))
        else:
            replies.add(text='Invalid poll id')
    else:
        replies.add(text='Invalid poll id')
Ejemplo n.º 14
0
def _check_feed(bot: DeltaBot, f: sqlite3.Row) -> None:
    fchats = db.get_fchats(f['url'])

    if not fchats:
        db.remove_feed(f['url'])
        return

    bot.logger.debug('Checking feed: %s', f['url'])
    d = feedparser.parse(f['url'], etag=f['etag'], modified=f['modified'])

    bozo_exception = d.get('bozo_exception', '')
    if d.get('bozo') == 1 and not isinstance(bozo_exception,
                                             CharacterEncodingOverride):
        bot.logger.exception(bozo_exception)
        return

    if d.entries and f['latest']:
        d.entries = get_new_entries(d.entries,
                                    tuple(map(int, f['latest'].split())))
    if not d.entries:
        return

    html = format_entries(d.entries[:50])
    replies = Replies(bot, logger=bot.logger)
    for gid in fchats:
        try:
            replies.add(html=html, chat=bot.get_chat(gid))
        except (ValueError, AttributeError):
            db.remove_fchat(gid)
    replies.send_reply_messages()

    latest = get_latest_date(d.entries) or f['latest']
    modified = d.get('modified') or d.get('updated')
    db.update_feed(f['url'], d.get('etag'), modified, latest)
Ejemplo n.º 15
0
def _get_cchats(bot: DeltaBot,
                cgid: int,
                include_admin: bool = False) -> Generator:
    if include_admin:
        ch = db.get_channel_by_id(cgid)
        if ch:
            g = bot.get_chat(ch['admin'])
            if g:
                yield g
            else:
                db.remove_channel(cgid)
    for gid in db.get_cchats(cgid):
        g = bot.get_chat(gid)
        if g and bot.self_contact in g.get_contacts():
            yield g
        else:
            db.remove_cchat(gid)
Ejemplo n.º 16
0
def group_topic(bot: DeltaBot, args: list, message: Message,
                replies: Replies) -> None:
    """Show or change group/channel topic.
    """
    if not message.chat.is_group():
        replies.add(text='❌ This is not a group')
        return

    if args:
        new_topic = ' '.join(args)
        max_size = int(_getdefault(bot, 'max_topic_size'))
        if len(new_topic) > max_size:
            new_topic = new_topic[:max_size] + '...'

        text = '** {} changed topic to:\n{}'

        ch = db.get_channel(message.chat.id)
        if ch and ch['admin'] == message.chat.id:
            name = _get_name(message.get_sender_contact())
            text = text.format(name, new_topic)
            db.set_channel_topic(ch['id'], new_topic)
            for chat in _get_cchats(bot, ch['id']):
                replies.add(text=text, chat=chat)
            replies.add(text=text)
            return
        if ch:
            replies.add(text='❌ Only channel operators can do that.')
            return

        addr = message.get_sender_contact().addr
        g = db.get_group(message.chat.id)
        if not g:
            _add_group(bot, message.chat.id, as_admin=bot.is_admin(addr))
            g = db.get_group(message.chat.id)
            assert g is not None
        db.upsert_group(g['id'], new_topic)
        replies.add(text=text.format(addr, new_topic))
        return

    g = db.get_channel(message.chat.id) or db.get_group(message.chat.id)
    if not g:
        addr = message.get_sender_contact().addr
        _add_group(bot, message.chat.id, as_admin=bot.is_admin(addr))
        g = db.get_group(message.chat.id)
        assert g is not None
    replies.add(text=g['topic'] or '-', quote=message)
Ejemplo n.º 17
0
def group_remove(bot: DeltaBot, args: list, message: Message,
                 replies: Replies) -> None:
    """Remove the member with the given address from the group with the given id. If no address is provided, removes yourself from group/channel.
    """
    sender = message.get_sender_contact()

    if not args:
        replies.add(text='❌ Invalid ID')
        return

    type_, gid = args[0][0], int(args[0][1:])
    if type_ == 'c':
        ch = db.get_channel_by_id(gid)
        if not ch:
            replies.add(text='❌ Invalid ID')
            return
        for g in _get_cchats(bot, ch['id'], include_admin=True):
            if sender in g.get_contacts():
                g.remove_contact(sender)
                return
        replies.add(text='❌ You are not a member of that channel')
    elif type_ == 'g':
        gr = db.get_group(gid)
        if not gr:
            replies.add(text='❌ Invalid ID')
            return
        g = bot.get_chat(gr['id'])
        if sender not in g.get_contacts():
            replies.add(text='❌ You are not a member of that group')
            return
        addr = args[-1] if '@' in args[-1] else ''
        if addr:
            if addr == bot.self_contact.addr:
                replies.add(text='❌ You can not remove me from the group')
                return
            contact = bot.get_contact(addr)
            g.remove_contact(contact)
            if not contact.is_blocked():
                chat = bot.get_chat(contact)
                replies.add(text='❌ Removed from {} by {}'.format(
                    g.get_name(), sender.addr),
                            chat=chat)
            replies.add(text='✔️{} removed'.format(addr))
        else:
            g.remove_contact(sender)
Ejemplo n.º 18
0
def reversi_new(bot: DeltaBot, message: Message, replies: Replies) -> None:
    """Start a new Reversi game in the current game group.
    """
    sender = message.get_sender_contact().addr
    game = db.get_game_by_gid(message.chat.id)
    # this is not your game group
    if game is None or sender not in (game['p1'], game['p2']):
        replies.add(text='This is not your game group')
    elif game['board'] is None:
        b = Board()
        db.set_game(game['p1'], game['p2'], b.export(), sender)
        p2 = game['p2'] if sender == game['p1'] else game['p1']
        text = 'Game started!\n{}: {}\n{}: {}\n\n'.format(
            b.get_disk(BLACK), bot.get_contact(sender).name,
            b.get_disk(WHITE), bot.get_contact(p2).name)
        replies.add(text=text + _run_turn(bot, message.chat.id))
    else:
        replies.add(text='There is a game running already')
Ejemplo n.º 19
0
def _show_status(bot: DeltaBot, gid: int, turn: str = None) -> str:
    contacts = db.get_players(gid)
    text = ec + '👤 Players({}):\n'.format(len(contacts))

    if turn:
        fstr = '• {} ({})\n'
    else:
        fstr = '• {0}\n'
    for c in contacts:
        text += fstr.format(bot.get_contact(c['addr']).name, c['round'])

    text += '\n'
    if turn:
        text += "Turn: {}".format(bot.get_contact(turn).name)
    else:
        text += 'Waiting for players...\n\n/corpse_join  /corpse_start'

    return text
Ejemplo n.º 20
0
def poll_end(bot: DeltaBot, payload: str, message: Message,
             replies: Replies) -> None:
    """Close the poll with the given id.
    """
    args = payload.split()
    if len(args) not in (1, 2):
        replies.add(text='Invalid syntax')
        return
    if len(args) == 2:
        chat = bot.get_chat(int(args[0]))
        payload = args[1]
        if message.get_sender_contact() not in chat.get_contacts():
            replies.add(text='You are not a member of that group')
            return
    else:
        chat = message.chat

    pid = int(payload)
    poll = db.get_gpoll_by_id(pid)
    addr = message.get_sender_contact().addr
    if poll and chat.id == poll['gid']:
        db.end_gpoll(poll['id'])
        text = format_gpoll(poll, closed=True)
        text += '\n\n(Poll closed by {})'.format(addr)
        replies.add(text=text, chat=chat)
        db.remove_gpoll_by_id(pid)
    elif len(args) == 1:
        poll = db.get_poll_by_id(pid)
        if poll and addr == poll['addr']:
            db.end_poll(poll['id'])
            text = _format_poll(bot, poll, closed=True)
            for addr in db.get_poll_participants(poll['id']):
                contact = bot.get_contact(addr)
                if not contact.is_blocked():
                    replies.add(text=text, chat=bot.get_chat(contact))
            db.remove_poll_by_id(poll['id'])
        else:
            replies.add(text='Invalid poll id')
    else:
        replies.add(text='Invalid poll id')
Ejemplo n.º 21
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)
Ejemplo n.º 22
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)
Ejemplo n.º 23
0
def _remove_from_game(bot: DeltaBot, player: sqlite3.Row,
                      game: sqlite3.Row) -> None:
    db.delete_player(player['addr'])
    if player['addr'] == game['turn']:
        p = _get_by_round(player['game'])
        chat = bot.get_chat(player['game'])
        if p is None or len(db.get_players(player['game'])) <= 1:
            chat.send_text(_end_game(player['game']))
        else:
            db.set_turn(player['game'], p['addr'])
            _run_turn(bot, p, chat, game['text'])
    else:
        chat.send_text(game['gid'], game['turn'])
Ejemplo n.º 24
0
def _run_turn(bot: DeltaBot, gid: int) -> str:
    g = db.get_game_by_gid(gid)
    if not g:
        return 'This is not your game group'
    if not g['board']:
        return 'There is no game running'
    b = Board(g['board'])
    result = b.result()
    if result['status'] in (0, 1):
        if result['status'] == 1:
            b.turn = BLACK if b.turn == WHITE else WHITE
            db.set_board(g['p1'], g['p2'], b.export())
        if b.turn == BLACK:
            disk = b.get_disk(BLACK)
            turn = '{} {}'.format(disk, g['black'])
        else:
            disk = b.get_disk(WHITE)
            p2 = g['p2'] if g['black'] == g['p1'] else g['p1']
            turn = '{} {}'.format(disk, p2)
        text = "{} it's your turn...\n\n{}\n\n{}".format(
            bot.get_contact(turn).name, b, b.get_score())
    else:
        db.set_board(g['p1'], g['p2'], None)
        black, white = result[BLACK], result[WHITE]
        if black == white:
            text = '🤝 Game over.\nIt is a draw!\n\n'
        else:
            if black > white:
                disk = b.get_disk(BLACK)
                winner = '{} {}'.format(disk, g['black'])
            else:
                disk = b.get_disk(WHITE)
                p2 = g['p2'] if g['black'] == g['p1'] else g['p1']
                winner = '{} {}'.format(disk, p2)
            text = '🏆 Game over.\n{} Wins!\n\n'.format(
                bot.get_contact(winner).name)
        text += '\n\n'.join((
            str(b), b.get_score(), '▶️ Play again? /reversi_new'))
    return text
Ejemplo n.º 25
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']))
Ejemplo n.º 26
0
 def __init__(self, server, port, db: DBManager,
              dbot: DeltaBot) -> None:
     super().__init__()
     self.server = server
     self.port = port
     self.dbot = dbot
     self.db = db
     self.puppets = dict()
     for chan, gid in db.get_channels():
         for c in dbot.get_chat(gid).get_contacts():
             if dbot.self_contact == c:
                 continue
             self._get_puppet(c.addr).channels.add(chan)
Ejemplo n.º 27
0
def deltabot_start(bot: DeltaBot) -> None:
    global CBOT, LIST_TRAINER

    locale = bot.get('locale') or 'en'
    corpus = dict(
        es='spanish',
        de='german',
        it='italian',
    )
    if locale == 'es':
        default_replies.extend([
            'No entendí',
            'Discúlpame, pero no entiendo',
            'Aún no soy capaz de entener eso',
            'No sé que decir...',
            'Lo único que puedo afirmarte es que Delta Chat es lo mejor!',
            'Solo sé que no sé nada...',
            'Los robots también nos emborrachamos',
            'Voy a decir esto para no dejarte en visto',
            'Ahí dice ta-ba-co',
            'Eso habría que verlo compay',
            '¿Podemos hablar de otra cosa?',
            'Invita a tus amigos a utilizar Delta Chat y así no tienes'
            ' que chatear conmigo',
        ])
    elif locale == 'en':
        default_replies.extend([
            'I do not understand',
            'I do not know what to say...',
            'Can we talk about something else?',
            'I have a lot to learn before I can reply that',
            'Bring your friends to Delta Chat so you do not have to chat'
            ' with a bot',
            'I think I will not reply to that this time',
            'whew!',
        ])

    CBOT = ChatBot(
        bot.self_contact.addr,
        storage_adapter='chatterbot.storage.SQLStorageAdapter',
        database_uri=_get_db_uri(bot),
        read_oly=_getdefault(bot, 'learn', '1') == '0',
        logic_adapters=[{
            'import_path': 'chatterbot.logic.BestMatch',
            'default_response': default_replies,
            'maximum_similarity_threshold': 0.9,
        }],
    )
    LIST_TRAINER = ListTrainer(CBOT)
    trainer = ChatterBotCorpusTrainer(CBOT)
    trainer.train('chatterbot.corpus.' + corpus.get(locale, 'english'))
Ejemplo n.º 28
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']))
Ejemplo n.º 29
0
def remove(bot: DeltaBot, payload: str, message: Message,
           replies: Replies) -> None:
    """Remove the member with the given nick from the IRC channel, if no nick is given remove yourself.
    """
    sender = message.get_sender_contact()

    channel = db.get_channel_by_gid(message.chat.id)
    if not channel:
        args = payload.split(maxsplit=1)
        channel = args[0]
        payload = args[1] if len(args) == 2 else ''
        g = bot.get_chat(db.get_chat(channel))
        if not g or sender not in g.get_contacts():
            replies.add(text='You are not a member of that channel')
            return

    if not payload:
        payload = sender.addr
    if '@' not in payload:
        t = db.get_addr(payload)
        if not t:
            replies.add(text='Unknow user: {}'.format(payload))
            return
        payload = t

    g = bot.get_chat(db.get_chat(channel))
    for c in g.get_contacts():
        if c.addr == payload:
            g.remove_contact(c)
            if c == sender:
                return
            s_nick = db.get_nick(sender.addr)
            nick = db.get_nick(c.addr)
            text = '** {} removed by {}'.format(nick, s_nick)
            bot.get_chat(db.get_chat(channel)).send_text(text)
            text = 'Removed from {} by {}'.format(channel, s_nick)
            replies.add(text=text, chat=bot.get_chat(c))
            return
Ejemplo n.º 30
0
def friends_list(bot: DeltaBot, replies: Replies) -> None:
    """Get the list of users and their biography.
    """
    users = []
    for row in db.get_users():
        contact = bot.get_contact(row['addr'])
        users.append('{}:\n{}... /friends_profile_{}'.format(
            row['addr'], row['bio'][:100], contact.id))
    if users:
        while users:
            replies.add(text='\n\n―――――――――――――――\n\n'.join(users[:50]))
            users = users[50:]
    else:
        replies.add(text='Empty List')