Beispiel #1
0
def save_channel_history(token, channel_id):
    Message.drop_table()
    Message.create_table()

    cursor = None
    count = 0

    while True:
        data, cursor = conversation.history(token, channel_id, cursor)
        first_msg = data[0]
        print(
            'first message',
            time.strftime('%Y-%m-%d %H:%M:%S',
                          time.localtime(float(first_msg["ts"]))),
            first_msg['text'])

        def save_messages(messages, is_thread):
            nonlocal count
            for msg in messages:
                Message(None, msg["ts"], channel_id, msg.get('user', None),
                        msg.get('bot_id', None), msg.get('subtype',
                                                         None), msg["text"],
                        msg.get('icons', {}).get('image_64', None),
                        msg.get('username', None), msg.get('thread_ts', None),
                        is_thread).save()
                count += 1

                if 'thread_ts' in msg and not is_thread:
                    data, cursor = conversation.replies(
                        token, channel_id, msg['thread_ts'])
                    save_messages(data, True)

        save_messages(data, False)

        if not cursor:
            break

    Message.commit()
    print(f'saved {count} messages.')